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 |
---|---|---|---|---|---|---|---|
@@ -19,6 +19,8 @@ package org.openqa.grid.internal;
import com.google.common.base.Predicate;
+import com.sun.org.glassfish.gmbal.ManagedObject;
+
import net.jcip.annotations.ThreadSafe;
import org.openqa.grid.internal.listeners.Prioritizer; | 1 | /*
Copyright 2011 Selenium committers
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.grid.internal;
import com.google.common.base.Predicate;
import net.jcip.annotations.ThreadSafe;
import org.openqa.grid.internal.listeners.Prioritizer;
import org.openqa.grid.internal.listeners.RegistrationListener;
import org.openqa.grid.internal.listeners.SelfHealingProxy;
import org.openqa.grid.internal.utils.CapabilityMatcher;
import org.openqa.grid.internal.utils.GridHubConfiguration;
import org.openqa.grid.web.Hub;
import org.openqa.grid.web.servlet.handler.RequestHandler;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.internal.HttpClientFactory;
import org.openqa.selenium.remote.server.log.LoggingManager;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Kernel of the grid. Keeps track of what's happening, what's free/used and assigned resources to
* incoming requests.
*/
@ThreadSafe
public class Registry {
public static final String KEY = Registry.class.getName();
private static final Logger log = Logger.getLogger(Registry.class.getName());
// lock for anything modifying the tests session currently running on this
// registry.
private final ReentrantLock lock = new ReentrantLock();
private final Condition testSessionAvailable = lock.newCondition();
private final ProxySet proxies;
private final ActiveTestSessions activeTestSessions = new ActiveTestSessions();
private final GridHubConfiguration configuration;
private final HttpClientFactory httpClientFactory;
private final NewSessionRequestQueue newSessionQueue;
private final Matcher matcherThread = new Matcher();
private final List<RemoteProxy> registeringProxies = new CopyOnWriteArrayList<RemoteProxy>();
private final CapabilityMatcher capabilityMatcher;
private volatile boolean stop = false;
// The following three variables need to be volatile because we expose a public setters
private volatile int newSessionWaitTimeout;
private volatile Prioritizer prioritizer;
private volatile Hub hub;
private Registry(Hub hub, GridHubConfiguration config) {
this.hub = hub;
this.capabilityMatcher = config.getCapabilityMatcher();
this.newSessionWaitTimeout = config.getNewSessionWaitTimeout();
this.prioritizer = config.getPrioritizer();
this.newSessionQueue = new NewSessionRequestQueue();
this.configuration = config;
this.httpClientFactory = new HttpClientFactory();
proxies = new ProxySet(config.isThrowOnCapabilityNotPresent());
this.matcherThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler());
}
@SuppressWarnings({"NullableProblems"})
public static Registry newInstance() {
return newInstance(null, new GridHubConfiguration());
}
public static Registry newInstance(Hub hub, GridHubConfiguration config) {
Registry registry = new Registry(hub, config);
registry.matcherThread.start();
// freynaud : TODO
// Registry is in a valid state when testSessionAvailable.await(); from
// assignRequestToProxy is reached. No before.
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
return registry;
}
public GridHubConfiguration getConfiguration() {
return configuration;
}
/**
* How long a session can remain in the newSession queue before being evicted.
*
* @return the new session wait timeout
*/
public int getNewSessionWaitTimeout() {
return newSessionWaitTimeout;
}
public void setNewSessionWaitTimeout(int newSessionWaitTimeout) {
this.newSessionWaitTimeout = newSessionWaitTimeout;
}
/**
* Ends this test session for the hub, releasing the resources in the hub / registry. It does not
* release anything on the remote. The resources are released in a separate thread, so the call
* returns immediately. It allows release with long duration not to block the test while the hub is
* releasing the resource.
*
* @param session The session to terminate
* @param reason the reason for termination
*/
public void terminate(final TestSession session, final SessionTerminationReason reason) {
new Thread(new Runnable() { // Thread safety reviewed
public void run() {
_release(session.getSlot(), reason);
}
}).start();
}
/**
* Release the test slot. Free the resource on the slot itself and the registry. If also invokes
* the {@link org.openqa.grid.internal.listeners.TestSessionListener#afterSession(TestSession)} if
* applicable.
*
* @param testSlot The slot to release
*/
private void _release(TestSlot testSlot, SessionTerminationReason reason) {
if (!testSlot.startReleaseProcess()) {
return;
}
if (!testSlot.performAfterSessionEvent()) {
return;
}
final String internalKey = testSlot.getInternalKey();
try {
lock.lock();
testSlot.finishReleaseProcess();
release(internalKey, reason);
} finally {
lock.unlock();
}
}
void terminateSynchronousFOR_TEST_ONLY(TestSession testSession) {
_release(testSession.getSlot(), SessionTerminationReason.CLIENT_STOPPED_SESSION);
}
public void removeIfPresent(RemoteProxy proxy) {
// Find the original proxy. While the supplied one is logically equivalent, it may be a fresh object with
// an empty TestSlot list, which doesn't figure into the proxy equivalence check. Since we want to free up
// those test sessions, we need to operate on that original object.
if (proxies.contains(proxy)) {
log.warning(String.format(
"Proxy '%s' was previously registered. Cleaning up any stale test sessions.", proxy));
final RemoteProxy p = proxies.remove(proxy);
for (TestSlot slot : p.getTestSlots()) {
forceRelease(slot, SessionTerminationReason.PROXY_REREGISTRATION);
}
p.teardown();
}
}
/**
* Releases the test slot, WITHOUT running any listener.
*/
public void forceRelease(TestSlot testSlot, SessionTerminationReason reason) {
if (testSlot.getSession() == null) {
return;
}
String internalKey = testSlot.getInternalKey();
release(internalKey, reason);
testSlot.doFinishRelease();
}
/**
* iterates the queue of incoming new session request and assign them to proxy after they've been
* sorted by priority, with priority defined by the prioritizer.
*/
class Matcher extends Thread { // Thread safety reviewed
Matcher() {
super("Matcher thread");
}
@Override
public void run() {
try {
lock.lock();
assignRequestToProxy();
} finally {
lock.unlock();
}
}
}
public void stop() {
stop = true;
matcherThread.interrupt();
newSessionQueue.stop();
proxies.teardown();
httpClientFactory.close();
}
public Hub getHub() {
return hub;
}
@SuppressWarnings({"UnusedDeclaration"})
public void setHub(Hub hub) {
this.hub = hub;
}
public void addNewSessionRequest(RequestHandler handler) {
try {
lock.lock();
proxies.verifyAbilityToHandleDesiredCapabilities(handler.getRequest().getDesiredCapabilities());
newSessionQueue.add(handler);
fireMatcherStateChanged();
} finally {
lock.unlock();
}
}
/**
* iterates the list of incoming session request to find a potential match in the list of proxies.
* If something changes in the registry, the matcher iteration is stopped to account for that
* change.
*/
private void assignRequestToProxy() {
while (!stop) {
try {
testSessionAvailable.await(5, TimeUnit.SECONDS);
newSessionQueue.processQueue(new Predicate<RequestHandler>() {
public boolean apply(RequestHandler input) {
return takeRequestHandler(input);
}
}, prioritizer);
// Just make sure we delete anything that is logged on this thread from memory
LoggingManager.perSessionLogHandler().clearThreadTempLogs();
} catch (InterruptedException e) {
log.info("Shutting down registry.");
} catch (Throwable t) {
log.log(Level.SEVERE, "Unhandled exception in Matcher thread.", t);
}
}
}
private boolean takeRequestHandler(RequestHandler handler) {
final TestSession session = proxies.getNewSession(handler.getRequest().getDesiredCapabilities());
final boolean sessionCreated = session != null;
if (sessionCreated) {
activeTestSessions.add(session);
handler.bindSession(session);
}
return sessionCreated;
}
/**
* mark the session as finished for the registry. The resources that were associated to it are now
* free to be reserved by other tests
*
* @param session The session
* @param reason the reason for the release
*/
private void release(TestSession session, SessionTerminationReason reason) {
try {
lock.lock();
boolean removed = activeTestSessions.remove(session, reason);
if (removed) {
fireMatcherStateChanged();
}
} finally {
lock.unlock();
}
}
private void release(String internalKey, SessionTerminationReason reason) {
if (internalKey == null) {
return;
}
final TestSession session1 = activeTestSessions.findSessionByInternalKey(internalKey);
if (session1 != null) {
release(session1, reason);
return;
}
log.warning("Tried to release session with internal key " + internalKey +
" but couldn't find it.");
}
/**
* Add a proxy to the list of proxy available for the grid to managed and link the proxy to the
* registry.
*
* @param proxy The proxy to add
*/
public void add(RemoteProxy proxy) {
if (proxy == null) {
return;
}
log.fine("adding " + proxy);
try {
lock.lock();
removeIfPresent(proxy);
if (registeringProxies.contains(proxy)) {
log.warning(String.format("Proxy '%s' is already queued for registration.", proxy));
return;
}
registeringProxies.add(proxy);
fireMatcherStateChanged();
} finally {
lock.unlock();
}
boolean listenerOk = true;
try {
if (proxy instanceof RegistrationListener) {
((RegistrationListener) proxy).beforeRegistration();
}
} catch (Throwable t) {
log.severe("Error running the registration listener on " + proxy + ", " + t.getMessage());
t.printStackTrace();
listenerOk = false;
}
try {
lock.lock();
registeringProxies.remove(proxy);
if (listenerOk) {
if (proxy instanceof SelfHealingProxy) {
((SelfHealingProxy) proxy).startPolling();
}
proxies.add(proxy);
fireMatcherStateChanged();
}
} finally {
lock.unlock();
}
}
/**
* If throwOnCapabilityNotPresent is set to true, the hub will reject test request for a
* capability that is not on the grid. No exception will be thrown if the capability is present
* but busy. <p/> If set to false, the test will be queued hoping a new proxy will register later
* offering that capability.
*
* @param throwOnCapabilityNotPresent true to throw if capability not present
*/
public void setThrowOnCapabilityNotPresent(boolean throwOnCapabilityNotPresent) {
proxies.setThrowOnCapabilityNotPresent(throwOnCapabilityNotPresent);
}
private void fireMatcherStateChanged() {
testSessionAvailable.signalAll();
}
public ProxySet getAllProxies() {
return proxies;
}
public List<RemoteProxy> getUsedProxies() {
return proxies.getBusyProxies();
}
/**
* gets the test session associated to this external key. The external key is the session used by
* webdriver.
*
* @param externalKey the external session key
* @return null if the hub doesn't have a node associated to the provided externalKey
*/
public TestSession getSession(ExternalSessionKey externalKey) {
return activeTestSessions.findSessionByExternalKey(externalKey);
}
/**
* gets the test existing session associated to this external key. The external key is the session
* used by webdriver.
*
* This method will log complaints and reasons if the key cannot be found
*
* @param externalKey the external session key
* @return null if the hub doesn't have a node associated to the provided externalKey
*/
public TestSession getExistingSession(ExternalSessionKey externalKey) {
return activeTestSessions.getExistingSession(externalKey);
}
/*
* May race.
*/
public int getNewSessionRequestCount() {
return newSessionQueue.getNewSessionRequestCount();
}
public void clearNewSessionRequests() {
newSessionQueue.clearNewSessionRequests();
}
public boolean removeNewSessionRequest(RequestHandler request) {
return newSessionQueue.removeNewSessionRequest(request);
}
public Iterable<DesiredCapabilities> getDesiredCapabilities() {
return newSessionQueue.getDesiredCapabilities();
}
public Set<TestSession> getActiveSessions() {
return activeTestSessions.unmodifiableSet();
}
public void setPrioritizer(Prioritizer prioritizer) {
this.prioritizer = prioritizer;
}
public Prioritizer getPrioritizer() {
return prioritizer;
}
public RemoteProxy getProxyById(String id) {
return proxies.getProxyById(id);
}
HttpClientFactory getHttpClientFactory() {
return httpClientFactory;
}
private static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
log.log(Level.SEVERE, "Matcher thread dying due to unhandled exception.", e);
}
}
public CapabilityMatcher getCapabilityMatcher() {
return capabilityMatcher;
}
}
| 1 | 11,529 | JMX offers normal APIs for this. I don't think you want the glassfish one. | SeleniumHQ-selenium | rb |
@@ -0,0 +1,7 @@
+module io.vavr {
+ requires io.vavr.match;
+ exports io.vavr;
+ exports io.vavr.collection;
+ exports io.vavr.control;
+ exports io.vavr.concurrent;
+} | 1 | 1 | 12,294 | Is this still Java 8 compatible? @danieldietrich do we need a separate, modularized Java 9 release also? | vavr-io-vavr | java |
|
@@ -293,7 +293,12 @@ hipError_t hipCreateTextureObject(hipTextureObject_t* pTexObject, const hipResou
hsa_ext_sampler_descriptor_t samplerDescriptor;
fillSamplerDescriptor(samplerDescriptor, pTexDesc->addressMode[0], pTexDesc->filterMode,
pTexDesc->normalizedCoords);
-
+ if(hipResourceTypeLinear == pResDesc->resType) {
+ samplerDescriptor.filter_mode = HSA_EXT_SAMPLER_FILTER_MODE_NEAREST;
+ samplerDescriptor.address_mode = HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_BORDER;
+ } else if(!pTexDesc->normalizedCoords) {
+ samplerDescriptor.address_mode = HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_EDGE;
+ }
hsa_access_permission_t permission = HSA_ACCESS_PERMISSION_RW;
if (HSA_STATUS_SUCCESS != hsa_ext_image_create_with_layout(
*agent, &imageDescriptor, devPtr, permission, | 1 |
#include <map>
#include <string.h>
#include "hsa/hsa.h"
#include "hsa/hsa_ext_amd.h"
#include "hip/hip_runtime.h"
#include "hip_hcc_internal.h"
#include "trace_helper.h"
#include "hip_texture.h"
static std::map<hipTextureObject_t, hipTexture*> textureHash;
void saveTextureInfo(const hipTexture* pTexture, const hipResourceDesc* pResDesc,
const hipTextureDesc* pTexDesc, const hipResourceViewDesc* pResViewDesc) {
if (pResDesc != nullptr) {
memcpy((void*)&(pTexture->resDesc), (void*)pResDesc, sizeof(hipResourceDesc));
}
if (pTexDesc != nullptr) {
memcpy((void*)&(pTexture->texDesc), (void*)pTexDesc, sizeof(hipTextureDesc));
}
if (pResViewDesc != nullptr) {
memcpy((void*)&(pTexture->resViewDesc), (void*)pResViewDesc, sizeof(hipResourceViewDesc));
}
}
void getDrvChannelOrderAndType(const enum hipArray_Format Format, unsigned int NumChannels,
hsa_ext_image_channel_order_t* channelOrder,
hsa_ext_image_channel_type_t* channelType) {
switch (Format) {
case HIP_AD_FORMAT_UNSIGNED_INT8:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT8;
break;
case HIP_AD_FORMAT_UNSIGNED_INT16:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT16;
break;
case HIP_AD_FORMAT_UNSIGNED_INT32:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32;
break;
case HIP_AD_FORMAT_SIGNED_INT8:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT8;
break;
case HIP_AD_FORMAT_SIGNED_INT16:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT16;
break;
case HIP_AD_FORMAT_SIGNED_INT32:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT32;
break;
case HIP_AD_FORMAT_HALF:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_HALF_FLOAT;
break;
case HIP_AD_FORMAT_FLOAT:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_FLOAT;
break;
default:
break;
}
if (NumChannels == 4) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_RGBA;
} else if (NumChannels == 2) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_RG;
} else if (NumChannels == 1) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_R;
}
}
void getChannelOrderAndType(const hipChannelFormatDesc& desc, enum hipTextureReadMode readMode,
hsa_ext_image_channel_order_t* channelOrder,
hsa_ext_image_channel_type_t* channelType) {
if (desc.x != 0 && desc.y != 0 && desc.z != 0 && desc.w != 0) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_RGBA;
} else if (desc.x != 0 && desc.y != 0 && desc.z != 0 && desc.w == 0) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_RGB;
} else if (desc.x != 0 && desc.y != 0 && desc.z == 0 && desc.w == 0) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_RG;
} else if (desc.x != 0 && desc.y == 0 && desc.z == 0 && desc.w == 0) {
*channelOrder = HSA_EXT_IMAGE_CHANNEL_ORDER_R;
} else {
}
switch (desc.f) {
case hipChannelFormatKindUnsigned:
switch (desc.x) {
case 32:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32;
break;
case 16:
*channelType = readMode == hipReadModeNormalizedFloat
? HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT16
: HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT16;
break;
case 8:
*channelType = readMode == hipReadModeNormalizedFloat
? HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT8
: HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT8;
break;
default:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32;
}
break;
case hipChannelFormatKindSigned:
switch (desc.x) {
case 32:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT32;
break;
case 16:
*channelType = readMode == hipReadModeNormalizedFloat
? HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT16
: HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT16;
break;
case 8:
*channelType = readMode == hipReadModeNormalizedFloat
? HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT8
: HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT8;
break;
default:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT32;
}
break;
case hipChannelFormatKindFloat:
switch (desc.x) {
case 32:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_FLOAT;
break;
case 16:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_HALF_FLOAT;
break;
case 8:
break;
default:
*channelType = HSA_EXT_IMAGE_CHANNEL_TYPE_FLOAT;
}
break;
case hipChannelFormatKindNone:
default:
break;
}
}
void fillSamplerDescriptor(hsa_ext_sampler_descriptor_t& samplerDescriptor,
enum hipTextureAddressMode addressMode,
enum hipTextureFilterMode filterMode, int normalizedCoords) {
if (normalizedCoords) {
samplerDescriptor.coordinate_mode = HSA_EXT_SAMPLER_COORDINATE_MODE_NORMALIZED;
} else {
samplerDescriptor.coordinate_mode = HSA_EXT_SAMPLER_COORDINATE_MODE_UNNORMALIZED;
}
switch (filterMode) {
case hipFilterModePoint:
samplerDescriptor.filter_mode = HSA_EXT_SAMPLER_FILTER_MODE_NEAREST;
break;
case hipFilterModeLinear:
samplerDescriptor.filter_mode = HSA_EXT_SAMPLER_FILTER_MODE_LINEAR;
break;
}
switch (addressMode) {
case hipAddressModeWrap:
samplerDescriptor.address_mode = HSA_EXT_SAMPLER_ADDRESSING_MODE_REPEAT;
break;
case hipAddressModeClamp:
samplerDescriptor.address_mode = HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_EDGE;
break;
case hipAddressModeMirror:
samplerDescriptor.address_mode = HSA_EXT_SAMPLER_ADDRESSING_MODE_MIRRORED_REPEAT;
break;
case hipAddressModeBorder:
samplerDescriptor.address_mode = HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_BORDER;
break;
}
}
bool getHipTextureObject(hipTextureObject_t* pTexObject, hsa_ext_image_t& image,
hsa_ext_sampler_t sampler) {
unsigned int* texSRD;
hipMalloc((void**)&texSRD, HIP_TEXTURE_OBJECT_SIZE_DWORD * 4);
hipMemcpy(texSRD, (void*)image.handle, HIP_IMAGE_OBJECT_SIZE_DWORD * 4,
hipMemcpyDeviceToDevice);
hipMemcpy(texSRD + HIP_SAMPLER_OBJECT_OFFSET_DWORD, (void*)sampler.handle,
HIP_SAMPLER_OBJECT_SIZE_DWORD * 4, hipMemcpyDeviceToDevice);
*pTexObject = (hipTextureObject_t)texSRD;
#ifdef DEBUG
unsigned int* srd = (unsigned int*)malloc(HIP_TEXTURE_OBJECT_SIZE_DWORD * 4);
hipMemcpy(srd, texSRD, HIP_TEXTURE_OBJECT_SIZE_DWORD * 4, hipMemcpyDeviceToHost);
printf("New SRD: \n");
for (int i = 0; i < HIP_TEXTURE_OBJECT_SIZE_DWORD; i++) {
printf("SRD[%d]: %x\n", i, srd[i]);
}
printf("\n");
#endif
return true;
}
// Texture Object APIs
hipError_t hipCreateTextureObject(hipTextureObject_t* pTexObject, const hipResourceDesc* pResDesc,
const hipTextureDesc* pTexDesc,
const hipResourceViewDesc* pResViewDesc) {
HIP_INIT_API(hipCreateTextureObject, pTexObject, pResDesc, pTexDesc, pResViewDesc);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hc::accelerator acc = ctx->getDevice()->_acc;
auto device = ctx->getWriteableDevice();
hsa_agent_t* agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent());
hipTexture* pTexture = (hipTexture*)malloc(sizeof(hipTexture));
if (pTexture != nullptr) {
memset(pTexture, 0, sizeof(hipTexture));
saveTextureInfo(pTexture, pResDesc, pTexDesc, pResViewDesc);
}
hsa_ext_image_descriptor_t imageDescriptor;
hsa_ext_image_channel_order_t channelOrder;
hsa_ext_image_channel_type_t channelType;
void* devPtr = nullptr;
size_t pitch = 0;
switch (pResDesc->resType) {
case hipResourceTypeArray:
devPtr = pResDesc->res.array.array->data;
imageDescriptor.width = pResDesc->res.array.array->width;
imageDescriptor.height = pResDesc->res.array.array->height;
switch (pResDesc->res.array.array->type) {
case hipArrayLayered:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2DA;
imageDescriptor.depth = 0;
imageDescriptor.array_size = pResDesc->res.array.array->depth;
break;
case hipArrayCubemap:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_3D;
imageDescriptor.depth = pResDesc->res.array.array->depth;
imageDescriptor.array_size = 0;
break;
case hipArraySurfaceLoadStore:
case hipArrayTextureGather:
case hipArrayDefault:
default:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2D;
imageDescriptor.depth = 0;
imageDescriptor.array_size = 0;
break;
}
getChannelOrderAndType(pResDesc->res.array.array->desc, pTexDesc->readMode,
&channelOrder, &channelType);
break;
case hipResourceTypeMipmappedArray:
devPtr = pResDesc->res.mipmap.mipmap->data;
imageDescriptor.width = pResDesc->res.mipmap.mipmap->width;
imageDescriptor.height = pResDesc->res.mipmap.mipmap->height;
imageDescriptor.depth = pResDesc->res.mipmap.mipmap->depth;
imageDescriptor.array_size = 0;
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2D;
getChannelOrderAndType(pResDesc->res.mipmap.mipmap->desc, pTexDesc->readMode,
&channelOrder, &channelType);
break;
case hipResourceTypeLinear:
devPtr = pResDesc->res.linear.devPtr;
imageDescriptor.width = pResDesc->res.linear.sizeInBytes/((pResDesc->res.linear.desc.x + pResDesc->res.linear.desc.y + pResDesc->res.linear.desc.z + pResDesc->res.linear.desc.w)/8);
imageDescriptor.height = 1;
imageDescriptor.depth = 0;
imageDescriptor.array_size = 0;
imageDescriptor.geometry =
HSA_EXT_IMAGE_GEOMETRY_1D; // ? HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR
getChannelOrderAndType(pResDesc->res.linear.desc, pTexDesc->readMode, &channelOrder,
&channelType);
break;
case hipResourceTypePitch2D:
devPtr = pResDesc->res.pitch2D.devPtr;
imageDescriptor.width = pResDesc->res.pitch2D.width;
imageDescriptor.height = pResDesc->res.pitch2D.height;
imageDescriptor.depth = 0;
imageDescriptor.array_size = 0;
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2D;
pitch = pResDesc->res.pitch2D.pitchInBytes;
getChannelOrderAndType(pResDesc->res.pitch2D.desc, pTexDesc->readMode,
&channelOrder, &channelType);
break;
default:
break;
}
imageDescriptor.format.channel_order = channelOrder;
imageDescriptor.format.channel_type = channelType;
hsa_ext_sampler_descriptor_t samplerDescriptor;
fillSamplerDescriptor(samplerDescriptor, pTexDesc->addressMode[0], pTexDesc->filterMode,
pTexDesc->normalizedCoords);
hsa_access_permission_t permission = HSA_ACCESS_PERMISSION_RW;
if (HSA_STATUS_SUCCESS != hsa_ext_image_create_with_layout(
*agent, &imageDescriptor, devPtr, permission,
HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR, pitch, 0, &(pTexture->image)) ||
HSA_STATUS_SUCCESS !=
hsa_ext_sampler_create(*agent, &samplerDescriptor, &(pTexture->sampler))) {
return ihipLogStatus(hipErrorRuntimeOther);
}
getHipTextureObject(pTexObject, pTexture->image, pTexture->sampler);
textureHash[*pTexObject] = pTexture;
}
return ihipLogStatus(hip_status);
}
hipError_t hipDestroyTextureObject(hipTextureObject_t textureObject) {
HIP_INIT_API(hipDestroyTextureObject, textureObject);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hc::accelerator acc = ctx->getDevice()->_acc;
auto device = ctx->getWriteableDevice();
hsa_agent_t* agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent());
hipTexture* pTexture = textureHash[textureObject];
if (pTexture != nullptr) {
hsa_ext_image_destroy(*agent, pTexture->image);
hsa_ext_sampler_destroy(*agent, pTexture->sampler);
free(pTexture);
textureHash.erase(textureObject);
}
}
return ihipLogStatus(hip_status);
}
hipError_t hipGetTextureObjectResourceDesc(hipResourceDesc* pResDesc,
hipTextureObject_t textureObject) {
HIP_INIT_API(hipGetTextureObjectResourceDesc, pResDesc, textureObject);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hipTexture* pTexture = textureHash[textureObject];
if (pTexture != nullptr && pResDesc != nullptr) {
memcpy((void*)pResDesc, (void*)&(pTexture->resDesc), sizeof(hipResourceDesc));
}
}
return ihipLogStatus(hip_status);
}
hipError_t hipGetTextureObjectResourceViewDesc(hipResourceViewDesc* pResViewDesc,
hipTextureObject_t textureObject) {
HIP_INIT_API(hipGetTextureObjectResourceViewDesc, pResViewDesc, textureObject);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hipTexture* pTexture = textureHash[textureObject];
if (pTexture != nullptr && pResViewDesc != nullptr) {
memcpy((void*)pResViewDesc, (void*)&(pTexture->resViewDesc),
sizeof(hipResourceViewDesc));
}
}
return ihipLogStatus(hip_status);
}
hipError_t hipGetTextureObjectTextureDesc(hipTextureDesc* pTexDesc,
hipTextureObject_t textureObject) {
HIP_INIT_API(hipGetTextureObjectTextureDesc, pTexDesc, textureObject);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hipTexture* pTexture = textureHash[textureObject];
if (pTexture != nullptr && pTexDesc != nullptr) {
memcpy((void*)pTexDesc, (void*)&(pTexture->texDesc), sizeof(hipTextureDesc));
}
}
return ihipLogStatus(hip_status);
}
// Texture Reference APIs
hipError_t ihipBindTextureImpl(TlsData *tls_, int dim, enum hipTextureReadMode readMode, size_t* offset,
const void* devPtr, const struct hipChannelFormatDesc* desc,
size_t size, textureReference* tex) {
TlsData *tls = (tls_ == nullptr) ? tls_get_ptr() : tls_;
hipError_t hip_status = hipSuccess;
enum hipTextureAddressMode addressMode = tex->addressMode[0];
enum hipTextureFilterMode filterMode = tex->filterMode;
int normalizedCoords = tex->normalized;
hipTextureObject_t& textureObject = tex->textureObject;
if(offset != nullptr)
*offset = 0;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hc::accelerator acc = ctx->getDevice()->_acc;
auto device = ctx->getWriteableDevice();
hsa_agent_t* agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent());
hipTexture* pTexture = (hipTexture*)malloc(sizeof(hipTexture));
if (pTexture != nullptr) {
memset(pTexture, 0, sizeof(hipTexture));
}
hsa_ext_image_descriptor_t imageDescriptor;
assert(dim == hipTextureType1D);
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_1D;
imageDescriptor.width = size;
imageDescriptor.height = 1;
imageDescriptor.depth = 1;
imageDescriptor.array_size = 0;
hsa_ext_image_channel_order_t channelOrder;
hsa_ext_image_channel_type_t channelType;
if (NULL == desc) {
getDrvChannelOrderAndType(tex->format, tex->numChannels, &channelOrder, &channelType);
} else {
getChannelOrderAndType(*desc, readMode, &channelOrder, &channelType);
}
imageDescriptor.format.channel_order = channelOrder;
imageDescriptor.format.channel_type = channelType;
hsa_ext_sampler_descriptor_t samplerDescriptor;
fillSamplerDescriptor(samplerDescriptor, addressMode, filterMode, normalizedCoords);
hsa_access_permission_t permission = HSA_ACCESS_PERMISSION_RW;
if (HSA_STATUS_SUCCESS != hsa_ext_image_create_with_layout(
*agent, &imageDescriptor, devPtr, permission,
HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR, 0, 0, &(pTexture->image)) ||
HSA_STATUS_SUCCESS !=
hsa_ext_sampler_create(*agent, &samplerDescriptor, &(pTexture->sampler))) {
return hipErrorRuntimeOther;
}
getHipTextureObject(&textureObject, pTexture->image, pTexture->sampler);
pTexture->devPtr = (void*) devPtr;
textureHash[textureObject] = pTexture;
}
return hip_status;
}
hipError_t hipBindTexture(size_t* offset, textureReference* tex, const void* devPtr,
const hipChannelFormatDesc* desc, size_t size) {
HIP_INIT_API(hipBindTexture, offset, tex, devPtr, desc, size);
hipError_t hip_status = hipSuccess;
// TODO: hipReadModeElementType is default.
hip_status = ihipBindTextureImpl(tls, hipTextureType1D, hipReadModeElementType, offset, devPtr, desc,
size, tex);
return ihipLogStatus(hip_status);
}
hipError_t ihipBindTexture2DImpl(TlsData *tls, int dim, enum hipTextureReadMode readMode, size_t* offset,
const void* devPtr, const struct hipChannelFormatDesc* desc,
size_t width, size_t height, textureReference* tex, size_t pitch) {
hipError_t hip_status = hipSuccess;
enum hipTextureAddressMode addressMode = tex->addressMode[0];
enum hipTextureFilterMode filterMode = tex->filterMode;
int normalizedCoords = tex->normalized;
hipTextureObject_t& textureObject = tex->textureObject;
if(offset != nullptr)
*offset = 0;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hc::accelerator acc = ctx->getDevice()->_acc;
auto device = ctx->getWriteableDevice();
hsa_agent_t* agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent());
hipTexture* pTexture = (hipTexture*)malloc(sizeof(hipTexture));
if (pTexture != nullptr) {
memset(pTexture, 0, sizeof(hipTexture));
}
hsa_ext_image_descriptor_t imageDescriptor;
assert(dim == hipTextureType2D);
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2D;
imageDescriptor.width = width;
imageDescriptor.height = height;
imageDescriptor.depth = 1;
imageDescriptor.array_size = 0;
hsa_ext_image_channel_order_t channelOrder;
hsa_ext_image_channel_type_t channelType;
if (NULL == desc) {
getDrvChannelOrderAndType(tex->format, tex->numChannels, &channelOrder, &channelType);
} else {
getChannelOrderAndType(*desc, readMode, &channelOrder, &channelType);
}
imageDescriptor.format.channel_order = channelOrder;
imageDescriptor.format.channel_type = channelType;
hsa_ext_sampler_descriptor_t samplerDescriptor;
fillSamplerDescriptor(samplerDescriptor, addressMode, filterMode, normalizedCoords);
hsa_access_permission_t permission = HSA_ACCESS_PERMISSION_RW;
if (HSA_STATUS_SUCCESS != hsa_ext_image_create_with_layout(
*agent, &imageDescriptor, devPtr, permission,
HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR, pitch, 0, &(pTexture->image)) ||
HSA_STATUS_SUCCESS !=
hsa_ext_sampler_create(*agent, &samplerDescriptor, &(pTexture->sampler))) {
return hipErrorRuntimeOther;
}
getHipTextureObject(&textureObject, pTexture->image, pTexture->sampler);
pTexture->devPtr = (void*) devPtr;
textureHash[textureObject] = pTexture;
}
return hip_status;
}
hipError_t hipBindTexture2D(size_t* offset, textureReference* tex, const void* devPtr,
const hipChannelFormatDesc* desc, size_t width, size_t height,
size_t pitch) {
HIP_INIT_API(hipBindTexture2D, offset, tex, devPtr, desc, width, height, pitch);
hipError_t hip_status = hipSuccess;
//TODO: Fix when HSA accepts user defined pitch
if(pitch % 64) pitch =0;
hip_status = ihipBindTexture2DImpl(tls, hipTextureType2D, hipReadModeElementType, offset, devPtr,
desc, width, height, tex, pitch);
return ihipLogStatus(hip_status);
}
hipError_t ihipBindTextureToArrayImpl(TlsData *tls_, int dim, enum hipTextureReadMode readMode,
hipArray_const_t array,
const struct hipChannelFormatDesc& desc,
textureReference* tex) {
TlsData *tls = (tls_ == nullptr) ? tls_get_ptr() : tls_;
hipError_t hip_status = hipSuccess;
enum hipTextureAddressMode addressMode = tex->addressMode[0];
enum hipTextureFilterMode filterMode = tex->filterMode;
int normalizedCoords = tex->normalized;
hipTextureObject_t& textureObject = tex->textureObject;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hc::accelerator acc = ctx->getDevice()->_acc;
auto device = ctx->getWriteableDevice();
hsa_agent_t* agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent());
hipTexture* pTexture = (hipTexture*)malloc(sizeof(hipTexture));
if (pTexture != nullptr) {
memset(pTexture, 0, sizeof(hipTexture));
}
hsa_ext_image_descriptor_t imageDescriptor;
imageDescriptor.width = array->width;
imageDescriptor.height = array->height;
imageDescriptor.depth = array->depth;
imageDescriptor.array_size = 0;
switch (dim) {
case hipTextureType1D:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_1D;
imageDescriptor.height = 1;
imageDescriptor.depth = 1;
break;
case hipTextureType2D:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2D;
imageDescriptor.depth = 1;
break;
case hipTextureType3D:
case hipTextureTypeCubemap:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_3D;
break;
case hipTextureType1DLayered:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_1DA;
imageDescriptor.height = 1;
imageDescriptor.array_size = array->height;
break;
case hipTextureType2DLayered:
imageDescriptor.geometry = HSA_EXT_IMAGE_GEOMETRY_2DA;
imageDescriptor.depth = 1;
imageDescriptor.array_size = array->depth;
break;
case hipTextureTypeCubemapLayered:
default:
break;
}
hsa_ext_image_channel_order_t channelOrder;
hsa_ext_image_channel_type_t channelType;
if (array->isDrv) {
getDrvChannelOrderAndType(array->Format, array->NumChannels,
&channelOrder, &channelType);
} else {
getChannelOrderAndType(desc, readMode, &channelOrder, &channelType);
}
imageDescriptor.format.channel_order = channelOrder;
imageDescriptor.format.channel_type = channelType;
hsa_ext_sampler_descriptor_t samplerDescriptor;
fillSamplerDescriptor(samplerDescriptor, addressMode, filterMode, normalizedCoords);
hsa_access_permission_t permission = HSA_ACCESS_PERMISSION_RW;
if (HSA_STATUS_SUCCESS != hsa_ext_image_create_with_layout(
*agent, &imageDescriptor, array->data, permission,
HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR, 0, 0, &(pTexture->image)) ||
HSA_STATUS_SUCCESS !=
hsa_ext_sampler_create(*agent, &samplerDescriptor, &(pTexture->sampler))) {
return hipErrorRuntimeOther;
}
getHipTextureObject(&textureObject, pTexture->image, pTexture->sampler);
pTexture->devPtr = (void*) array;
textureHash[textureObject] = pTexture;
}
return hip_status;
}
hipError_t hipBindTextureToArray(textureReference* tex, hipArray_const_t array,
const hipChannelFormatDesc* desc) {
HIP_INIT_API(hipBindTextureToArray, tex, array, desc);
hipError_t hip_status = hipSuccess;
// TODO: hipReadModeElementType is default.
hip_status =
ihipBindTextureToArrayImpl(tls, array->textureType, hipReadModeElementType, array, *desc, tex);
return ihipLogStatus(hip_status);
}
hipError_t hipBindTextureToMipmappedArray(textureReference* tex,
hipMipmappedArray_const_t mipmappedArray,
const hipChannelFormatDesc* desc) {
HIP_INIT_API(hipBindTextureToMipmappedArray, tex, mipmappedArray, desc);
hipError_t hip_status = hipSuccess;
return ihipLogStatus(hip_status);
}
hipError_t ihipUnbindTextureImpl(const hipTextureObject_t& textureObject) {
hipError_t hip_status = hipSuccess;
TlsData* tls=tls_get_ptr();
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
hc::accelerator acc = ctx->getDevice()->_acc;
auto device = ctx->getWriteableDevice();
hsa_agent_t* agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent());
hipTexture* pTexture = textureHash[textureObject];
if (pTexture != nullptr) {
hsa_ext_image_destroy(*agent, pTexture->image);
hsa_ext_sampler_destroy(*agent, pTexture->sampler);
free(pTexture);
textureHash.erase(textureObject);
}
}
return hip_status;
}
hipError_t hipUnbindTexture(const textureReference* tex) {
HIP_INIT_API(hipUnbindTexture, tex);
hipError_t hip_status = hipSuccess;
hip_status = ihipUnbindTextureImpl(tex->textureObject);
return ihipLogStatus(hip_status);
}
hipError_t hipGetChannelDesc(hipChannelFormatDesc* desc, hipArray_const_t array) {
HIP_INIT_API(hipGetChannelDesc, desc, array);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
*desc = array->desc;
}
return ihipLogStatus(hip_status);
}
hipError_t hipGetTextureAlignmentOffset(size_t* offset, const textureReference* tex) {
HIP_INIT_API(hipGetTextureAlignmentOffset, offset, tex);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
if(offset != nullptr)
*offset = 0;
}
return ihipLogStatus(hip_status);
}
hipError_t hipGetTextureReference(const textureReference** tex, const void* symbol) {
HIP_INIT_API(hipGetTextureReference, tex, symbol);
hipError_t hip_status = hipSuccess;
auto ctx = ihipGetTlsDefaultCtx();
if (ctx) {
}
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefSetFormat(textureReference* tex, hipArray_Format fmt, int NumPackedComponents) {
HIP_INIT_API(hipTexRefSetFormat, tex, fmt, NumPackedComponents);
hipError_t hip_status = hipSuccess;
tex->format = fmt;
tex->numChannels = NumPackedComponents;
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefSetFlags(textureReference* tex, unsigned int flags) {
HIP_INIT_API(hipTexRefSetFlags, tex, flags);
hipError_t hip_status = hipSuccess;
tex->normalized = flags;
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefSetFilterMode(textureReference* tex, hipTextureFilterMode fm) {
HIP_INIT_API(hipTexRefSetFilterMode, tex, fm);
hipError_t hip_status = hipSuccess;
tex->filterMode = fm;
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefSetAddressMode(textureReference* tex, int dim, hipTextureAddressMode am) {
HIP_INIT_API(hipTexRefSetAddressMode, tex, dim, am);
hipError_t hip_status = hipSuccess;
tex->addressMode[dim] = am;
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefGetAddressMode(hipTextureAddressMode* am, textureReference tex, int dim) {
HIP_INIT_API(hipTexRefGetAddressMode,am, &tex, dim);
if ((am == nullptr) || (dim >= 3))
return ihipLogStatus(hipErrorInvalidValue);
*am = tex.addressMode[dim];
return ihipLogStatus(hipSuccess);
}
hipError_t hipTexRefSetArray(textureReference* tex, hipArray_const_t array, unsigned int flags) {
HIP_INIT_API(hipTexRefSetArray, tex, array, flags);
hipError_t hip_status = hipSuccess;
hip_status = ihipBindTextureToArrayImpl(tls, array->textureType, hipReadModeElementType, array,
array->desc, tex);
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefGetArray(hipArray_t* array, textureReference tex) {
HIP_INIT_API(hipTexRefGetArray, array, &tex);
if (array == nullptr)
return ihipLogStatus(hipErrorInvalidValue);
hipTexture* pTexture = textureHash[tex.textureObject];
if((pTexture == nullptr) || (hipResourceTypeArray != pTexture->resDesc.resType))
return ihipLogStatus(hipErrorInvalidImage);
if (pTexture->devPtr == nullptr)
return ihipLogStatus(hipErrorUnknown);
*array = reinterpret_cast<hipArray_t>(pTexture->devPtr);
return ihipLogStatus(hipSuccess);
}
hipError_t hipTexRefSetAddress(size_t* offset, textureReference* tex, hipDeviceptr_t devPtr,
size_t size) {
HIP_INIT_API(hipTexRefSetAddress, offset, tex, devPtr, size);
hipError_t hip_status = hipSuccess;
// TODO: hipReadModeElementType is default.
hip_status = ihipBindTextureImpl(tls, hipTextureType1D, hipReadModeElementType, offset, devPtr, NULL,
size, tex);
return ihipLogStatus(hip_status);
}
hipError_t hipTexRefGetAddress(hipDeviceptr_t* dev_ptr, textureReference tex) {
HIP_INIT_API(hipTexRefGetAddress,dev_ptr, &tex);
if (dev_ptr == nullptr)
return ihipLogStatus(hipErrorInvalidValue);
hipTexture* pTexture = textureHash[tex.textureObject];
if (pTexture == nullptr)
return ihipLogStatus(hipErrorInvalidImage);
if (pTexture->devPtr == nullptr)
return ihipLogStatus(hipErrorUnknown);
*dev_ptr = reinterpret_cast<hipDeviceptr_t>(pTexture->devPtr);
return ihipLogStatus(hipSuccess);
}
hipError_t hipTexRefSetAddress2D(textureReference* tex, const HIP_ARRAY_DESCRIPTOR* desc,
hipDeviceptr_t devPtr, size_t pitch) {
HIP_INIT_API(hipTexRefSetAddress2D, tex, desc, devPtr, pitch);
size_t offset;
hipError_t hip_status = hipSuccess;
// TODO: hipReadModeElementType is default.
//TODO: Fix when HSA accepts user defined pitch
if(pitch % 64) pitch =0;
hip_status = ihipBindTexture2DImpl(tls, hipTextureType2D, hipReadModeElementType, &offset, devPtr,
NULL, desc->Width, desc->Height, tex, pitch);
return ihipLogStatus(hip_status);
}
| 1 | 8,820 | Should update the user input address and filter modes and pass those in fillSamplerDescriptor ? | ROCm-Developer-Tools-HIP | cpp |
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module Faker
+ class Show < Base
+ class << self
+ def adult_musical
+ fetch('show.adult_musical')
+ end
+
+ def kids_musical
+ fetch('show.kids_musical')
+ end
+
+ def play
+ fetch('show.play')
+ end
+ end
+ end
+end | 1 | 1 | 8,932 | This object should be in `lib/music/show.rb` and you should also wrap this object in the `Faker::Music::Show`. | faker-ruby-faker | rb |
|
@@ -58,6 +58,14 @@ Puppet::Functions.create_function(:run_task) do
end || (raise Puppet::ParseError, 'Task parameters did not match')
task = task_signature.task
+ if executor.noop
+ if task.supports_noop
+ use_args['_noop'] = true
+ else
+ raise Puppet::ParseError, 'Task does not support noop'
+ end
+ end
+
# Ensure that that given targets are all Target instances
targets = [targets] unless targets.is_a?(Array)
targets = targets.flatten.map { |t| t.is_a?(String) ? Puppet::Pops::Types::TypeFactory.target.create(t) : t } | 1 | # Runs a given instance of a `Task` on the given set of targets and returns the result from each.
#
# * This function does nothing if the list of targets is empty.
# * It is possible to run on the target 'localhost'
# * A target is a String with a targets's hostname or a Target.
# * The returned value contains information about the result per target.
#
Puppet::Functions.create_function(:run_task) do
local_types do
type 'TargetOrTargets = Variant[String[1], Target, Array[TargetOrTargets]]'
end
dispatch :run_task do
param 'String[1]', :task_name
param 'TargetOrTargets', :targets
optional_param 'Hash[String[1], Any]', :task_args
end
# this is used from 'bolt task run'
dispatch :run_task_raw do
param 'String[1]', :task_name
param 'TargetOrTargets', :targets
optional_param 'Hash[String[1], Any]', :task_args
block_param
end
def run_task(task_name, targets, task_args = nil)
Puppet::Pops::Types::ExecutionResult.from_bolt(
run_task_raw(task_name, targets, task_args)
)
end
def run_task_raw(task_name, targets, task_args = nil, &block)
unless Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::TASK_OPERATION_NOT_SUPPORTED_WHEN_COMPILING, operation: 'run_task'
)
end
# TODO: use the compiler injection once PUP-8237 lands
task_signature = Puppet::Pal::ScriptCompiler.new(closure_scope.compiler).task_signature(task_name)
if task_signature.nil?
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::UNKNOWN_TASK, type_name: task_name
)
end
executor = Puppet.lookup(:bolt_executor) { nil }
unless executor && Puppet.features.bolt?
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::TASK_MISSING_BOLT, action: _('run a task')
)
end
use_args = task_args.nil? ? {} : task_args
task_signature.runnable_with?(use_args) do |mismatch|
raise Puppet::ParseError, mismatch
end || (raise Puppet::ParseError, 'Task parameters did not match')
task = task_signature.task
# Ensure that that given targets are all Target instances
targets = [targets] unless targets.is_a?(Array)
targets = targets.flatten.map { |t| t.is_a?(String) ? Puppet::Pops::Types::TypeFactory.target.create(t) : t }
if targets.empty?
call_function('debug', "Simulating run of task #{task.name} - no targets given - no action taken")
Puppet::Pops::EMPTY_HASH
else
# TODO: Awaits change in the executor, enabling it receive Target instances
hosts = targets.map(&:host)
# TODO: separate handling of default since it's platform specific
input_method = task.input_method
executor.run_task(executor.from_uris(hosts), task.executable, input_method, use_args, &block)
end
end
end
| 1 | 7,260 | I think logic will have to move to bolt since the vague discussions around bolt run plan --noop is that it would just skip any tasks that don't support_noop rather than error. This is fine until we actually elaborate that though. | puppetlabs-bolt | rb |
@@ -11,6 +11,7 @@ import (
"github.com/CoderZhi/go-ethereum/common"
"github.com/CoderZhi/go-ethereum/core/types"
+
"github.com/iotexproject/iotex-core/address"
"github.com/iotexproject/iotex-core/logger"
"github.com/iotexproject/iotex-core/pkg/hash" | 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 blockchain
import (
"math/big"
"github.com/CoderZhi/go-ethereum/common"
"github.com/CoderZhi/go-ethereum/core/types"
"github.com/iotexproject/iotex-core/address"
"github.com/iotexproject/iotex-core/logger"
"github.com/iotexproject/iotex-core/pkg/hash"
"github.com/iotexproject/iotex-core/pkg/util/byteutil"
"github.com/iotexproject/iotex-core/state"
)
// EVMStateDBAdapter represents the state db adapter for evm to access iotx blockchain
type EVMStateDBAdapter struct {
bc Blockchain
ws state.WorkingSet
logs []*Log
err error
blockHeight uint64
blockHash hash.Hash32B
executionIndex uint
executionHash hash.Hash32B
}
// NewEVMStateDBAdapter creates a new state db with iotx blockchain
func NewEVMStateDBAdapter(bc Blockchain, ws state.WorkingSet, blockHeight uint64, blockHash hash.Hash32B, executionIndex uint, executionHash hash.Hash32B) *EVMStateDBAdapter {
return &EVMStateDBAdapter{
bc,
ws,
[]*Log{},
nil,
blockHeight,
blockHash,
executionIndex,
executionHash,
}
}
func (stateDB *EVMStateDBAdapter) logError(err error) {
if stateDB.err == nil {
stateDB.err = err
}
}
// Error returns the first stored error during evm contract execution
func (stateDB *EVMStateDBAdapter) Error() error {
return stateDB.err
}
// CreateAccount creates an account in iotx blockchain
func (stateDB *EVMStateDBAdapter) CreateAccount(evmAddr common.Address) {
addr := address.New(stateDB.bc.ChainID(), evmAddr.Bytes())
_, err := stateDB.ws.LoadOrCreateAccountState(addr.IotxAddress(), big.NewInt(0))
if err != nil {
logger.Error().Err(err).Msg("CreateAccount")
// stateDB.logError(err)
return
}
logger.Debug().Hex("addrHash", evmAddr[:]).Msg("CreateAccount")
}
// SubBalance subtracts balance from account
func (stateDB *EVMStateDBAdapter) SubBalance(evmAddr common.Address, amount *big.Int) {
if amount.Cmp(big.NewInt(int64(0))) == 0 {
return
}
// stateDB.GetBalance(evmAddr)
logger.Debug().Msgf("SubBalance %v from %s", amount, evmAddr.Hex())
addr := address.New(stateDB.bc.ChainID(), evmAddr.Bytes())
state, err := stateDB.ws.CachedAccountState(addr.IotxAddress())
if err != nil {
logger.Error().Err(err).Msg("SubBalance")
stateDB.logError(err)
return
}
state.SubBalance(amount)
// stateDB.GetBalance(evmAddr)
}
// AddBalance adds balance to account
func (stateDB *EVMStateDBAdapter) AddBalance(evmAddr common.Address, amount *big.Int) {
if amount.Cmp(big.NewInt(int64(0))) == 0 {
return
}
// stateDB.GetBalance(evmAddr)
logger.Debug().Msgf("AddBalance %v to %s", amount, evmAddr.Hex())
addr := address.New(stateDB.bc.ChainID(), evmAddr.Bytes())
state, err := stateDB.ws.CachedAccountState(addr.IotxAddress())
if err != nil {
logger.Error().Err(err).Hex("addrHash", evmAddr[:]).Msg("AddBalance")
stateDB.logError(err)
return
}
state.AddBalance(amount)
// stateDB.GetBalance(evmAddr)
}
// GetBalance gets the balance of account
func (stateDB *EVMStateDBAdapter) GetBalance(evmAddr common.Address) *big.Int {
addr := address.New(stateDB.bc.ChainID(), evmAddr.Bytes())
state, err := stateDB.ws.CachedAccountState(addr.IotxAddress())
if err != nil {
logger.Error().Err(err).Msg("GetBalance")
return nil
}
logger.Debug().Msgf("Balance of %s is %v", evmAddr.Hex(), state.Balance)
return state.Balance
}
// GetNonce gets the nonce of account
func (stateDB *EVMStateDBAdapter) GetNonce(evmAddr common.Address) uint64 {
addr := address.New(stateDB.bc.ChainID(), evmAddr.Bytes())
nonce, err := stateDB.ws.Nonce(addr.IotxAddress())
if err != nil {
logger.Error().Err(err).Msg("GetNonce")
// stateDB.logError(err)
return 0
}
logger.Debug().Uint64("nonce", nonce).Msg("GetNonce")
return nonce
}
// SetNonce sets the nonce of account
func (stateDB *EVMStateDBAdapter) SetNonce(common.Address, uint64) {
logger.Error().Msg("SetNonce is not implemented")
}
// GetCodeHash gets the code hash of account
func (stateDB *EVMStateDBAdapter) GetCodeHash(evmAddr common.Address) common.Hash {
codeHash := common.Hash{}
hash, err := stateDB.ws.GetCodeHash(byteutil.BytesTo20B(evmAddr[:]))
if err != nil {
logger.Error().Err(err).Msgf("GetCodeHash")
// TODO (zhi) not all err should be logged
// stateDB.logError(err)
return codeHash
}
logger.Debug().Hex("codeHash", hash[:]).Msg("GetCodeHash")
copy(codeHash[:], hash[:])
return codeHash
}
// GetCode gets the code saved in hash
func (stateDB *EVMStateDBAdapter) GetCode(evmAddr common.Address) []byte {
code, err := stateDB.ws.GetCode(byteutil.BytesTo20B(evmAddr[:]))
if err != nil {
// TODO: we need to change the log level to error later
logger.Debug().Err(err).Msg("GetCode")
return nil
}
logger.Debug().Hex("addrHash", evmAddr[:]).Msg("GetCode")
return code
}
// SetCode sets the code saved in hash
func (stateDB *EVMStateDBAdapter) SetCode(evmAddr common.Address, code []byte) {
if err := stateDB.ws.SetCode(byteutil.BytesTo20B(evmAddr[:]), code); err != nil {
logger.Error().Err(err).Msg("SetCode")
}
logger.Debug().Hex("code", code).Hex("hash", hash.Hash256b(code)[:]).Msg("SetCode")
}
// GetCodeSize gets the code size saved in hash
func (stateDB *EVMStateDBAdapter) GetCodeSize(evmAddr common.Address) int {
code := stateDB.GetCode(evmAddr)
if code == nil {
return 0
}
logger.Debug().Hex("addrHash", evmAddr[:]).Msg("GetCodeSize")
return len(code)
}
// AddRefund adds refund
func (stateDB *EVMStateDBAdapter) AddRefund(uint64) {
logger.Error().Msg("AddRefund is not implemented")
}
// GetRefund gets refund
func (stateDB *EVMStateDBAdapter) GetRefund() uint64 {
logger.Error().Msg("GetRefund is not implemented")
return 0
}
// GetState gets state
func (stateDB *EVMStateDBAdapter) GetState(evmAddr common.Address, k common.Hash) common.Hash {
storage := common.Hash{}
v, err := stateDB.ws.GetContractState(byteutil.BytesTo20B(evmAddr[:]), byteutil.BytesTo32B(k[:]))
if err != nil {
logger.Error().Err(err).Msg("GetState")
return storage
}
logger.Debug().Hex("addrHash", evmAddr[:]).Hex("k", k[:]).Msg("GetState")
copy(storage[:], v[:])
return storage
}
// SetState sets state
func (stateDB *EVMStateDBAdapter) SetState(evmAddr common.Address, k, v common.Hash) {
if err := stateDB.ws.SetContractState(byteutil.BytesTo20B(evmAddr[:]), byteutil.BytesTo32B(k[:]), byteutil.BytesTo32B(v[:])); err != nil {
logger.Error().Err(err).Msg("SetState")
return
}
logger.Debug().Hex("addrHash", evmAddr[:]).Hex("k", k[:]).Hex("v", v[:]).Msg("SetState")
}
// Suicide kills the contract
func (stateDB *EVMStateDBAdapter) Suicide(common.Address) bool {
logger.Error().Msg("Suicide is not implemented")
return false
}
// HasSuicided returns whether the contract has been killed
func (stateDB *EVMStateDBAdapter) HasSuicided(common.Address) bool {
logger.Error().Msg("HasSuicide is not implemented")
return false
}
// Exist checks the existence of an address
func (stateDB *EVMStateDBAdapter) Exist(evmAddr common.Address) bool {
addr := address.New(stateDB.bc.ChainID(), evmAddr.Bytes())
logger.Debug().Msgf("Check existence of %s", addr.IotxAddress())
if state, err := stateDB.ws.CachedAccountState(addr.IotxAddress()); err != nil || state == nil {
logger.Debug().Msgf("account %s does not exist", addr.IotxAddress())
return false
}
return true
}
// Empty empties the contract
func (stateDB *EVMStateDBAdapter) Empty(common.Address) bool {
logger.Debug().Msg("Empty is not implemented")
return false
}
// RevertToSnapshot reverts the state factory to snapshot
func (stateDB *EVMStateDBAdapter) RevertToSnapshot(int) {
logger.Debug().Msg("RevertToSnapshot is not implemented")
}
// Snapshot returns the snapshot id
func (stateDB *EVMStateDBAdapter) Snapshot() int {
logger.Debug().Msg("Snapshot is not implemented")
return 0
}
// AddLog adds log
func (stateDB *EVMStateDBAdapter) AddLog(evmLog *types.Log) {
logger.Debug().Msgf("AddLog %+v\n", evmLog)
addr := address.New(stateDB.bc.ChainID(), evmLog.Address.Bytes())
var topics []hash.Hash32B
for _, evmTopic := range evmLog.Topics {
var topic hash.Hash32B
copy(topic[:], evmTopic.Bytes())
topics = append(topics, topic)
}
log := &Log{
addr.IotxAddress(),
topics,
evmLog.Data,
stateDB.blockHeight,
stateDB.executionHash,
stateDB.blockHash,
stateDB.executionIndex,
}
stateDB.logs = append(stateDB.logs, log)
}
// Logs returns the logs
func (stateDB *EVMStateDBAdapter) Logs() []*Log {
return stateDB.logs
}
// AddPreimage adds the preimage
func (stateDB *EVMStateDBAdapter) AddPreimage(common.Hash, []byte) {
logger.Error().Msg("AddPreimage is not implemented")
}
// ForEachStorage loops each storage
func (stateDB *EVMStateDBAdapter) ForEachStorage(common.Address, func(common.Hash, common.Hash) bool) {
logger.Error().Msg("ForEachStorage is not implemented")
}
| 1 | 13,092 | File is not `goimports`-ed | iotexproject-iotex-core | go |
@@ -35,12 +35,15 @@ class CollectionViewTest(BaseWebTest, unittest.TestCase):
headers=self.headers,
status=400)
- def test_unknown_bucket_raises_404(self):
+ def test_unknown_bucket_raises_403(self):
other_bucket = self.collections_url.replace('beers', 'sodas')
- self.app.get(other_bucket, headers=self.headers, status=404)
+ self.app.get(other_bucket, headers=self.headers, status=403)
def test_collections_are_isolated_by_bucket(self):
- other_bucket = self.collection_url.replace('beers', 'water')
+ other_bucket = self.collection_url.replace('beers', 'sodas')
+ self.app.put_json('/buckets/sodas',
+ MINIMALIST_BUCKET,
+ headers=self.headers)
self.app.get(other_bucket, headers=self.headers, status=404)
| 1 | from .support import (BaseWebTest, unittest, MINIMALIST_BUCKET,
MINIMALIST_COLLECTION, MINIMALIST_RECORD)
class CollectionViewTest(BaseWebTest, unittest.TestCase):
collections_url = '/buckets/beers/collections'
collection_url = '/buckets/beers/collections/barley'
def setUp(self):
super(CollectionViewTest, self).setUp()
self.app.put_json('/buckets/beers', MINIMALIST_BUCKET,
headers=self.headers)
resp = self.app.put_json(self.collection_url,
MINIMALIST_COLLECTION,
headers=self.headers)
self.record = resp.json['data']
def test_collection_endpoint_lists_them_all(self):
resp = self.app.get(self.collections_url, headers=self.headers)
records = resp.json['data']
self.assertEqual(len(records), 1)
self.assertEqual(records[0]['id'], 'barley')
def test_collections_do_not_support_post(self):
self.app.post(self.collections_url, headers=self.headers,
status=405)
def test_collections_can_be_put_with_simple_name(self):
self.assertEqual(self.record['id'], 'barley')
def test_collections_name_should_be_simple(self):
self.app.put_json('/buckets/beers/collections/__barley__',
MINIMALIST_COLLECTION,
headers=self.headers,
status=400)
def test_unknown_bucket_raises_404(self):
other_bucket = self.collections_url.replace('beers', 'sodas')
self.app.get(other_bucket, headers=self.headers, status=404)
def test_collections_are_isolated_by_bucket(self):
other_bucket = self.collection_url.replace('beers', 'water')
self.app.get(other_bucket, headers=self.headers, status=404)
class CollectionDeletionTest(BaseWebTest, unittest.TestCase):
collection_url = '/buckets/beers/collections/barley'
def setUp(self):
super(CollectionDeletionTest, self).setUp()
self.app.put_json('/buckets/beers', MINIMALIST_BUCKET,
headers=self.headers)
self.app.put_json(self.collection_url, MINIMALIST_COLLECTION,
headers=self.headers)
r = self.app.post_json(self.collection_url + '/records',
MINIMALIST_RECORD,
headers=self.headers)
record_id = r.json['data']['id']
self.record_url = self.collection_url + '/records/%s' % record_id
self.app.delete(self.collection_url, headers=self.headers)
def test_collections_can_be_deleted(self):
self.app.get(self.collection_url, headers=self.headers,
status=404)
def test_records_of_collection_are_deleted_too(self):
self.app.put_json(self.collection_url, MINIMALIST_COLLECTION,
headers=self.headers)
self.app.get(self.record_url, headers=self.headers, status=404)
def test_permissions_associated_are_deleted_too(self):
pass
| 1 | 7,452 | why should unknown raise a 403? | Kinto-kinto | py |
@@ -87,11 +87,11 @@ export function diff(dom, parentDom, newVNode, oldVNode, context, isSvg, excessD
c._vnode = newVNode;
// Invoke getDerivedStateFromProps
- let s = c._nextState || c.state;
+ if (c._nextState==null) {
+ c._nextState = c.state;
+ }
if (newType.getDerivedStateFromProps!=null) {
- oldState = assign({}, c.state);
- if (s===c.state) s = c._nextState = assign({}, s);
- assign(s, newType.getDerivedStateFromProps(newVNode.props, s));
+ assign(c._nextState==c.state ? (c._nextState = assign({}, c._nextState)) : c._nextState, newType.getDerivedStateFromProps(newVNode.props, c._nextState));
}
// Invoke pre-render lifecycle methods | 1 | import { EMPTY_OBJ, EMPTY_ARR } from '../constants';
import { Component, enqueueRender } from '../component';
import { coerceToVNode, Fragment } from '../create-element';
import { diffChildren } from './children';
import { diffProps } from './props';
import { assign, removeNode } from '../util';
import options from '../options';
/**
* Diff two virtual nodes and apply proper changes to the DOM
* @param {import('../internal').PreactElement | Text} dom The DOM element representing
* the virtual nodes under diff
* @param {import('../internal').PreactElement} parentDom The parent of the DOM element
* @param {import('../internal').VNode | null} newVNode The new virtual node
* @param {import('../internal').VNode | null} oldVNode The old virtual node
* @param {object} context The current context object
* @param {boolean} isSvg Whether or not this element is an SVG node
* @param {Array<import('../internal').PreactElement>} excessDomChildren
* @param {Array<import('../internal').Component>} mounts A list of newly
* mounted components
* @param {import('../internal').Component | null} ancestorComponent The direct
* parent component
*/
export function diff(dom, parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent, force) {
// If the previous type doesn't match the new type we drop the whole subtree
if (oldVNode==null || newVNode==null || oldVNode.type!==newVNode.type) {
if (oldVNode!=null) unmount(oldVNode, ancestorComponent);
if (newVNode==null) return null;
dom = null;
oldVNode = EMPTY_OBJ;
}
if (options.diff) options.diff(newVNode);
let c, p, isNew = false, oldProps, oldState, snapshot,
newType = newVNode.type;
/** @type {import('../internal').Component | null} */
let clearProcessingException;
try {
outer: if (oldVNode.type===Fragment || newType===Fragment) {
diffChildren(parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, c);
if (newVNode._children.length) {
dom = newVNode._children[0]._dom;
newVNode._lastDomChild = newVNode._children[newVNode._children.length - 1]._dom;
}
}
else if (typeof newType==='function') {
// Necessary for createContext api. Setting this property will pass
// the context value as `this.context` just for this component.
let cxType = newType.contextType;
let provider = cxType && context[cxType._id];
let cctx = cxType != null ? (provider ? provider.props.value : cxType._defaultValue) : context;
// Get component and set it to `c`
if (oldVNode._component) {
c = newVNode._component = oldVNode._component;
clearProcessingException = c._processingException;
}
else {
isNew = true;
// Instantiate the new component
if (newType.prototype && newType.prototype.render) {
newVNode._component = c = new newType(newVNode.props, cctx); // eslint-disable-line new-cap
}
else {
newVNode._component = c = new Component(newVNode.props, cctx);
c.constructor = newType;
c.render = doRender;
}
c._ancestorComponent = ancestorComponent;
if (provider) provider.sub(c);
c.props = newVNode.props;
if (!c.state) c.state = {};
c.context = cctx;
c._context = context;
c._dirty = true;
c._renderCallbacks = [];
}
c._vnode = newVNode;
// Invoke getDerivedStateFromProps
let s = c._nextState || c.state;
if (newType.getDerivedStateFromProps!=null) {
oldState = assign({}, c.state);
if (s===c.state) s = c._nextState = assign({}, s);
assign(s, newType.getDerivedStateFromProps(newVNode.props, s));
}
// Invoke pre-render lifecycle methods
if (isNew) {
if (newType.getDerivedStateFromProps==null && c.componentWillMount!=null) c.componentWillMount();
if (c.componentDidMount!=null) mounts.push(c);
}
else {
if (newType.getDerivedStateFromProps==null && force==null && c.componentWillReceiveProps!=null) {
c.componentWillReceiveProps(newVNode.props, cctx);
s = c._nextState || c.state;
}
if (!force && c.shouldComponentUpdate!=null && c.shouldComponentUpdate(newVNode.props, s, cctx)===false) {
c.props = newVNode.props;
c.state = s;
c._dirty = false;
break outer;
}
if (c.componentWillUpdate!=null) {
c.componentWillUpdate(newVNode.props, s, cctx);
}
}
oldProps = c.props;
if (!oldState) oldState = c.state;
c.context = cctx;
c.props = newVNode.props;
c.state = s;
if (options.render) options.render(newVNode);
let prev = c._prevVNode;
let vnode = c._prevVNode = coerceToVNode(c.render(c.props, c.state, c.context));
c._dirty = false;
if (c.getChildContext!=null) {
context = assign(assign({}, context), c.getChildContext());
}
if (!isNew && c.getSnapshotBeforeUpdate!=null) {
snapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);
}
c.base = dom = diff(dom, parentDom, vnode, prev, context, isSvg, excessDomChildren, mounts, c, null);
if (vnode!=null) {
// If this component returns a Fragment (or another component that
// returns a Fragment), then _lastDomChild will be non-null,
// informing `diffChildren` to diff this component's VNode like a Fragemnt
newVNode._lastDomChild = vnode._lastDomChild;
}
c._parentDom = parentDom;
if (newVNode.ref) applyRef(newVNode.ref, c, ancestorComponent);
}
else {
dom = diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent);
if (newVNode.ref && (oldVNode.ref !== newVNode.ref)) {
applyRef(newVNode.ref, dom, ancestorComponent);
}
}
newVNode._dom = dom;
if (c!=null) {
while (p=c._renderCallbacks.pop()) p.call(c);
// Don't call componentDidUpdate on mount or when we bailed out via
// `shouldComponentUpdate`
if (!isNew && oldProps!=null && c.componentDidUpdate!=null) {
c.componentDidUpdate(oldProps, oldState, snapshot);
}
}
if (clearProcessingException) {
c._processingException = null;
}
if (options.diffed) options.diffed(newVNode);
}
catch (e) {
catchErrorInComponent(e, ancestorComponent);
}
return dom;
}
export function commitRoot(mounts, root) {
let c;
while ((c = mounts.pop())) {
try {
c.componentDidMount();
}
catch (e) {
catchErrorInComponent(e, c._ancestorComponent);
}
}
if (options.commit) options.commit(root);
}
/**
* Diff two virtual nodes representing DOM element
* @param {import('../internal').PreactElement} dom The DOM element representing
* the virtual nodes being diffed
* @param {import('../internal').VNode} newVNode The new virtual node
* @param {import('../internal').VNode} oldVNode The old virtual node
* @param {object} context The current context object
* @param {boolean} isSvg Whether or not this DOM node is an SVG node
* @param {*} excessDomChildren
* @param {Array<import('../internal').Component>} mounts An array of newly
* mounted components
* @param {import('../internal').Component} ancestorComponent The parent
* component to the ones being diffed
* @returns {import('../internal').PreactElement}
*/
function diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent) {
let d = dom;
// Tracks entering and exiting SVG namespace when descending through the tree.
isSvg = newVNode.type==='svg' || isSvg;
if (dom==null && excessDomChildren!=null) {
for (let i=0; i<excessDomChildren.length; i++) {
const child = excessDomChildren[i];
if (child!=null && (newVNode.type===null ? child.nodeType===3 : child.localName===newVNode.type)) {
dom = child;
excessDomChildren[i] = null;
break;
}
}
}
if (dom==null) {
dom = newVNode.type===null ? document.createTextNode(newVNode.text) : isSvg ? document.createElementNS('http://www.w3.org/2000/svg', newVNode.type) : document.createElement(newVNode.type);
// we created a new parent, so none of the previously attached children can be reused:
excessDomChildren = null;
}
newVNode._dom = dom;
if (newVNode.type===null) {
if ((d===null || dom===d) && newVNode.text!==oldVNode.text) {
dom.data = newVNode.text;
}
}
else {
if (excessDomChildren!=null && dom.childNodes!=null) {
excessDomChildren = EMPTY_ARR.slice.call(dom.childNodes);
}
if (newVNode!==oldVNode) {
let oldProps = oldVNode.props;
let newProps = newVNode.props;
// if we're hydrating, use the element's attributes as its current props:
if (oldProps==null) {
oldProps = {};
if (excessDomChildren!=null) {
let name;
for (let i=0; i<dom.attributes.length; i++) {
name = dom.attributes[i].name;
oldProps[name=='class' && newProps.className ? 'className' : name] = dom.attributes[i].value;
}
}
}
let oldHtml = oldProps.dangerouslySetInnerHTML;
let newHtml = newProps.dangerouslySetInnerHTML;
if (newHtml || oldHtml) {
// Avoid re-applying the same '__html' if it did not changed between re-render
if (!newHtml || !oldHtml || newHtml.__html!=oldHtml.__html) {
dom.innerHTML = newHtml && newHtml.__html || '';
}
}
if (newProps.multiple) {
dom.multiple = newProps.multiple;
}
diffChildren(dom, newVNode, oldVNode, context, newVNode.type==='foreignObject' ? false : isSvg, excessDomChildren, mounts, ancestorComponent);
diffProps(dom, newProps, oldProps, isSvg);
}
}
return dom;
}
/**
* Invoke or update a ref, depending on whether it is a function or object ref.
* @param {object|function} [ref=null]
* @param {any} [value]
*/
export function applyRef(ref, value, ancestorComponent) {
try {
if (typeof ref=='function') ref(value);
else ref.current = value;
}
catch (e) {
catchErrorInComponent(e, ancestorComponent);
}
}
/**
* Unmount a virtual node from the tree and apply DOM changes
* @param {import('../internal').VNode} vnode The virtual node to unmount
* @param {import('../internal').Component} ancestorComponent The parent
* component to this virtual node
* @param {boolean} skipRemove Flag that indicates that a parent node of the
* current element is already detached from the DOM.
*/
export function unmount(vnode, ancestorComponent, skipRemove) {
let r;
if (options.unmount) options.unmount(vnode);
if (r = vnode.ref) {
applyRef(r, null, ancestorComponent);
}
if (!skipRemove && vnode._lastDomChild==null && (skipRemove = ((r = vnode._dom)!=null))) removeNode(r);
vnode._dom = vnode._lastDomChild = null;
if ((r = vnode._component)!=null) {
if (r.componentWillUnmount) {
try {
r.componentWillUnmount();
}
catch (e) {
catchErrorInComponent(e, ancestorComponent);
}
}
r.base = r._parentDom = null;
if (r = r._prevVNode) unmount(r, ancestorComponent, skipRemove);
}
else if (r = vnode._children) {
for (let i = 0; i < r.length; i++) {
unmount(r[i], ancestorComponent, skipRemove);
}
}
}
/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
return this.constructor(props, context);
}
/**
* Find the closest error boundary to a thrown error and call it
* @param {object} error The thrown value
* @param {import('../internal').Component} component The first ancestor
* component check for error boundary behaviors
*/
function catchErrorInComponent(error, component) {
for (; component; component = component._ancestorComponent) {
if (!component._processingException) {
try {
if (component.constructor.getDerivedStateFromError!=null) {
component.setState(component.constructor.getDerivedStateFromError(error));
}
else if (component.componentDidCatch!=null) {
component.componentDidCatch(error);
}
else {
continue;
}
return enqueueRender(component._processingException = component);
}
catch (e) {
error = e;
}
}
}
throw error;
}
| 1 | 12,883 | The true clause of your condition, can't this just be c._nextState since `assign({}, c._nextState)` is equal to returning c._nextState, or am I misunderstanding something here? | preactjs-preact | js |
@@ -36,6 +36,8 @@ flags.DEFINE_string('groups_service_account_key_file', None,
'runnning locally.')
flags.DEFINE_integer('max_admin_api_calls_per_day', 150000,
'Admin SDK queries per day.')
+flags.DEFINE_integer('max_results_admin_api', 500,
++ 'maxResult param for the Admin SDK list() method')
class AdminDirectoryClient(_base_client.BaseClient): | 1 | # Copyright 2017 Google 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.
"""Wrapper for Admin Directory API client."""
import gflags as flags
from googleapiclient.errors import HttpError
from httplib2 import HttpLib2Error
from oauth2client.service_account import ServiceAccountCredentials
from ratelimiter import RateLimiter
from google.cloud.security.common.gcp_api import _base_client
from google.cloud.security.common.gcp_api import errors as api_errors
FLAGS = flags.FLAGS
flags.DEFINE_string('domain_super_admin_email', None,
'An email address of a super-admin in the GSuite domain. '
'REQUIRED: if inventory_groups is enabled.')
flags.DEFINE_string('groups_service_account_key_file', None,
'The key file with credentials for the service account. '
'REQUIRED: If inventory_groups is enabled and '
'runnning locally.')
flags.DEFINE_integer('max_admin_api_calls_per_day', 150000,
'Admin SDK queries per day.')
class AdminDirectoryClient(_base_client.BaseClient):
"""GSuite Admin Directory API Client."""
API_NAME = 'admin'
DEFAULT_QUOTA_TIMESPAN_PER_SECONDS = 86400 # pylint: disable=invalid-name
REQUIRED_SCOPES = frozenset([
'https://www.googleapis.com/auth/admin.directory.group.readonly'
])
def __init__(self):
super(AdminDirectoryClient, self).__init__(
credentials=self._build_credentials(),
api_name=self.API_NAME)
self.rate_limiter = RateLimiter(
FLAGS.max_admin_api_calls_per_day,
self.DEFAULT_QUOTA_TIMESPAN_PER_SECONDS)
def _build_credentials(self):
"""Build credentials required for accessing the directory API.
Returns:
Credentials as built by oauth2client.
Raises:
api_errors.ApiExecutionError
"""
try:
credentials = ServiceAccountCredentials.from_json_keyfile_name(
FLAGS.groups_service_account_key_file,
scopes=self.REQUIRED_SCOPES)
except (ValueError, KeyError, TypeError) as e:
raise api_errors.ApiExecutionError(
'Error building admin api credential: %s', e)
return credentials.create_delegated(
FLAGS.domain_super_admin_email)
def get_rate_limiter(self):
"""Return an appriopriate rate limiter."""
return RateLimiter(FLAGS.max_admin_api_calls_per_day,
self.DEFAULT_QUOTA_TIMESPAN_PER_SECONDS)
def get_group_members(self, group_key):
"""Get all the members for specified groups.
Args:
group_key: Its unique id assigned by the Admin API.
Returns:
A list of member objects from the API.
Raises:
api_errors.ApiExecutionError
"""
members_stub = self.service.members()
request = members_stub.list(groupKey=group_key)
results_by_member = []
# TODO: Investigate yielding results to handle large group lists.
while request is not None:
try:
with self.rate_limiter:
response = self._execute(request)
results_by_member.extend(response.get('members', []))
request = members_stub.list_next(request, response)
except (HttpError, HttpLib2Error) as e:
raise api_errors.ApiExecutionError(members_stub, e)
return results_by_member
def get_groups(self, customer_id='my_customer'):
"""Get all the groups for a given customer_id.
A note on customer_id='my_customer'.
This is a magic string instead of using the real
customer id. See:
https://developers.google.com/admin-sdk/directory/v1/guides/manage-groups#get_all_domain_groups
Args:
customer_id: The customer id to scope the request to
Returns:
A list of group objects returned from the API.
Raises:
api_errors.ApiExecutionError
"""
groups_stub = self.service.groups()
request = groups_stub.list(customer=customer_id)
results_by_group = []
# TODO: Investigate yielding results to handle large group lists.
while request is not None:
try:
with self.rate_limiter:
response = self._execute(request)
results_by_group.extend(response.get('groups', []))
request = groups_stub.list_next(request, response)
except (HttpError, HttpLib2Error) as e:
raise api_errors.ApiExecutionError(groups_stub, e)
return results_by_group
| 1 | 25,694 | nit: align the leftmost quotes | forseti-security-forseti-security | py |
@@ -98,6 +98,11 @@ type AgentConfig struct {
// APIPort is the port for the antrea-agent APIServer to serve on.
// Defaults to 10350.
APIPort int `yaml:"apiPort,omitempty"`
+
+ // ClusterMembershipPort is the server port used by the antrea-agent to run a gossip-based cluster membership protocol. Currently it's used only when the Egress feature is enabled.
+ // Defaults to 10351.
+ ClusterMembershipPort int `yaml:"clusterPort,omitempty"`
+
// Enable metrics exposure via Prometheus. Initializes Prometheus metrics listener
// Defaults to true.
EnablePrometheusMetrics bool `yaml:"enablePrometheusMetrics,omitempty"` | 1 | // Copyright 2019 Antrea 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 (
componentbaseconfig "k8s.io/component-base/config"
)
type AgentConfig struct {
// featureGates is a map of feature names to bools that enable or disable experimental features.
FeatureGates map[string]bool `yaml:"featureGates,omitempty"`
CNISocket string `yaml:"cniSocket,omitempty"`
// clientConnection specifies the kubeconfig file and client connection settings for the agent
// to communicate with the apiserver.
ClientConnection componentbaseconfig.ClientConnectionConfiguration `yaml:"clientConnection"`
// AntreaClientConnection specifies the kubeconfig file and client connection settings for the
// agent to communicate with the Antrea Controller apiserver.
AntreaClientConnection componentbaseconfig.ClientConnectionConfiguration `yaml:"antreaClientConnection"`
// Name of the OpenVSwitch bridge antrea-agent will create and use.
// Make sure it doesn't conflict with your existing OpenVSwitch bridges.
// Defaults to br-int.
OVSBridge string `yaml:"ovsBridge,omitempty"`
// Datapath type to use for the OpenVSwitch bridge created by Antrea. Supported values are:
// - system
// - netdev
// 'system' is the default value and corresponds to the kernel datapath. Use 'netdev' to run
// OVS in userspace mode. Userspace mode requires the tun device driver to be available.
OVSDatapathType string `yaml:"ovsDatapathType,omitempty"`
// Runtime data directory used by Open vSwitch.
// Default value:
// - On Linux platform: /var/run/openvswitch
// - On Windows platform: C:\openvswitch\var\run\openvswitch
OVSRunDir string `yaml:"ovsRunDir,omitempty"`
// Name of the interface antrea-agent will create and use for host <--> pod communication.
// Make sure it doesn't conflict with your existing interfaces.
// Defaults to antrea-gw0.
HostGateway string `yaml:"hostGateway,omitempty"`
// Determines how traffic is encapsulated. It has the following options:
// encap(default): Inter-node Pod traffic is always encapsulated and Pod to external network
// traffic is SNAT'd.
// noEncap: Inter-node Pod traffic is not encapsulated; Pod to external network traffic is
// SNAT'd if noSNAT is not set to true. Underlying network must be capable of
// supporting Pod traffic across IP subnets.
// hybrid: noEncap if source and destination Nodes are on the same subnet, otherwise encap.
// networkPolicyOnly: Antrea enforces NetworkPolicy only, and utilizes CNI chaining and delegates Pod
// IPAM and connectivity to the primary CNI.
TrafficEncapMode string `yaml:"trafficEncapMode,omitempty"`
// Whether or not to SNAT (using the Node IP) the egress traffic from a Pod to the external network.
// This option is for the noEncap traffic mode only, and the default value is false. In the noEncap
// mode, if the cluster's Pod CIDR is reachable from the external network, then the Pod traffic to
// the external network needs not be SNAT'd. In the networkPolicyOnly mode, antrea-agent never
// performs SNAT and this option will be ignored; for other modes it must be set to false.
NoSNAT bool `yaml:"noSNAT,omitempty"`
// Tunnel protocols used for encapsulating traffic across Nodes. Supported values:
// - geneve (default)
// - vxlan
// - gre
// - stt
TunnelType string `yaml:"tunnelType,omitempty"`
// Default MTU to use for the host gateway interface and the network interface of each Pod.
// If omitted, antrea-agent will discover the MTU of the Node's primary interface and
// also adjust MTU to accommodate for tunnel encapsulation overhead (if applicable).
DefaultMTU int `yaml:"defaultMTU,omitempty"`
// Mount location of the /proc directory. The default is "/host", which is appropriate when
// antrea-agent is run as part of the Antrea DaemonSet (and the host's /proc directory is mounted
// as /host/proc in the antrea-agent container). When running antrea-agent as a process,
// hostProcPathPrefix should be set to "/" in the YAML config.
HostProcPathPrefix string `yaml:"hostProcPathPrefix,omitempty"`
// ClusterIP CIDR range for Services. It's required when AntreaProxy is not enabled, and should be
// set to the same value as the one specified by --service-cluster-ip-range for kube-apiserver. When
// AntreaProxy is enabled, this parameter is not needed and will be ignored if provided.
// Default is 10.96.0.0/12
ServiceCIDR string `yaml:"serviceCIDR,omitempty"`
// ClusterIP CIDR range for IPv6 Services. It's required when using kube-proxy to provide IPv6 Service in a Dual-Stack
// cluster or an IPv6 only cluster. The value should be the same as the configuration for kube-apiserver specified by
// --service-cluster-ip-range. When AntreaProxy is enabled, this parameter is not needed.
// No default value for this field.
ServiceCIDRv6 string `yaml:"serviceCIDRv6,omitempty"`
// Whether or not to enable IPSec (ESP) encryption for Pod traffic across Nodes. IPSec encryption
// is supported only for the GRE tunnel type. Antrea uses Preshared Key (PSK) for IKE
// authentication. When IPSec tunnel is enabled, the PSK value must be passed to Antrea Agent
// through an environment variable: ANTREA_IPSEC_PSK.
// Defaults to false.
EnableIPSecTunnel bool `yaml:"enableIPSecTunnel,omitempty"`
// APIPort is the port for the antrea-agent APIServer to serve on.
// Defaults to 10350.
APIPort int `yaml:"apiPort,omitempty"`
// Enable metrics exposure via Prometheus. Initializes Prometheus metrics listener
// Defaults to true.
EnablePrometheusMetrics bool `yaml:"enablePrometheusMetrics,omitempty"`
// Provide the IPFIX collector address as a string with format <HOST>:[<PORT>][:<PROTO>].
// HOST can either be the DNS name or the IP of the Flow Collector. For example,
// "flow-aggregator.flow-aggregator.svc" can be provided as DNS name to connect
// to the Antrea Flow Aggregator service. If IP, it can be either IPv4 or IPv6.
// However, IPv6 address should be wrapped with [].
// If PORT is empty, we default to 4739, the standard IPFIX port.
// If no PROTO is given, we consider "tcp" as default. We support "tcp" and
// "udp" L4 transport protocols.
// Defaults to "flow-aggregator.flow-aggregator.svc:4739:tcp".
FlowCollectorAddr string `yaml:"flowCollectorAddr,omitempty"`
// Provide flow poll interval in format "0s". This determines how often flow
// exporter dumps connections in conntrack module. Flow poll interval should
// be greater than or equal to 1s(one second).
// Defaults to "5s". Valid time units are "ns", "us" (or "µs"), "ms", "s",
// "m", "h".
FlowPollInterval string `yaml:"flowPollInterval,omitempty"`
// Provide the active flow export timeout, which is the timeout after which
// a flow record is sent to the collector for active flows. Thus, for flows
// with a continuous stream of packets, a flow record will be exported to the
// collector once the elapsed time since the last export event is equal to the
// value of this timeout.
// Defaults to "30s". Valid time units are "ns", "us" (or "µs"), "ms", "s",
// "m", "h".
ActiveFlowExportTimeout string `yaml:"activeFlowExportTimeout,omitempty"`
// Provide the idle flow export timeout, which is the timeout after which a
// flow record is sent to the collector for idle flows. A flow is considered
// idle if no packet matching this flow has been observed since the last export
// event.
// Defaults to "15s". Valid time units are "ns", "us" (or "µs"), "ms", "s",
// "m", "h".
IdleFlowExportTimeout string `yaml:"idleFlowExportTimeout,omitempty"`
// Provide the port range used by NodePortLocal. When the NodePortLocal feature is enabled, a port from that range will be assigned
// whenever a Pod's container defines a specific port to be exposed (each container can define a list of ports as pod.spec.containers[].ports),
// and all Node traffic directed to that port will be forwarded to the Pod.
NPLPortRange string `yaml:"nplPortRange,omitempty"`
// Provide the address of Kubernetes apiserver, to override any value provided in kubeconfig or InClusterConfig.
// Defaults to "". It must be a host string, a host:port pair, or a URL to the base of the apiserver.
KubeAPIServerOverride string `yaml:"kubeAPIServerOverride,omitempty"`
// Cipher suites to use.
TLSCipherSuites string `yaml:"tlsCipherSuites,omitempty"`
// TLS min version.
TLSMinVersion string `yaml:"tlsMinVersion,omitempty"`
}
| 1 | 37,518 | Probably "server port" -> "TCP port" | antrea-io-antrea | go |
@@ -91,7 +91,11 @@ public class Lucene80Codec extends Codec {
* flushed/merged segments.
*/
public Lucene80Codec(Mode mode) {
- super("Lucene80");
+ this("Lucene80", mode);
+ }
+
+ protected Lucene80Codec(String name, Mode mode) {
+ super(name);
this.storedFieldsFormat = new Lucene50StoredFieldsFormat(Objects.requireNonNull(mode));
this.defaultFormat = new Lucene50PostingsFormat();
} | 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.codecs.lucene80;
import java.util.Objects;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.CompoundFormat;
import org.apache.lucene.codecs.DocValuesFormat;
import org.apache.lucene.codecs.FieldInfosFormat;
import org.apache.lucene.codecs.FilterCodec;
import org.apache.lucene.codecs.LiveDocsFormat;
import org.apache.lucene.codecs.NormsFormat;
import org.apache.lucene.codecs.PointsFormat;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.SegmentInfoFormat;
import org.apache.lucene.codecs.StoredFieldsFormat;
import org.apache.lucene.codecs.TermVectorsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50CompoundFormat;
import org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat.Mode;
import org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat;
import org.apache.lucene.codecs.lucene60.Lucene60FieldInfosFormat;
import org.apache.lucene.codecs.lucene60.Lucene60PointsFormat;
import org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat;
import org.apache.lucene.codecs.perfield.PerFieldDocValuesFormat;
import org.apache.lucene.codecs.perfield.PerFieldPostingsFormat;
/**
* Implements the Lucene 8.0 index format, with configurable per-field postings
* and docvalues formats.
* <p>
* If you want to reuse functionality of this codec in another codec, extend
* {@link FilterCodec}.
*
* @see org.apache.lucene.codecs.lucene80 package documentation for file format details.
*
* @lucene.experimental
*/
public class Lucene80Codec extends Codec {
private final TermVectorsFormat vectorsFormat = new Lucene50TermVectorsFormat();
private final FieldInfosFormat fieldInfosFormat = new Lucene60FieldInfosFormat();
private final SegmentInfoFormat segmentInfosFormat = new Lucene70SegmentInfoFormat();
private final LiveDocsFormat liveDocsFormat = new Lucene50LiveDocsFormat();
private final CompoundFormat compoundFormat = new Lucene50CompoundFormat();
private final PostingsFormat defaultFormat;
private final PostingsFormat postingsFormat = new PerFieldPostingsFormat() {
@Override
public PostingsFormat getPostingsFormatForField(String field) {
return Lucene80Codec.this.getPostingsFormatForField(field);
}
};
private final DocValuesFormat docValuesFormat = new PerFieldDocValuesFormat() {
@Override
public DocValuesFormat getDocValuesFormatForField(String field) {
return Lucene80Codec.this.getDocValuesFormatForField(field);
}
};
private final StoredFieldsFormat storedFieldsFormat;
/**
* Instantiates a new codec.
*/
public Lucene80Codec() {
this(Mode.BEST_SPEED);
}
/**
* Instantiates a new codec, specifying the stored fields compression
* mode to use.
* @param mode stored fields compression mode to use for newly
* flushed/merged segments.
*/
public Lucene80Codec(Mode mode) {
super("Lucene80");
this.storedFieldsFormat = new Lucene50StoredFieldsFormat(Objects.requireNonNull(mode));
this.defaultFormat = new Lucene50PostingsFormat();
}
@Override
public final StoredFieldsFormat storedFieldsFormat() {
return storedFieldsFormat;
}
@Override
public final TermVectorsFormat termVectorsFormat() {
return vectorsFormat;
}
@Override
public final PostingsFormat postingsFormat() {
return postingsFormat;
}
@Override
public final FieldInfosFormat fieldInfosFormat() {
return fieldInfosFormat;
}
@Override
public final SegmentInfoFormat segmentInfoFormat() {
return segmentInfosFormat;
}
@Override
public final LiveDocsFormat liveDocsFormat() {
return liveDocsFormat;
}
@Override
public final CompoundFormat compoundFormat() {
return compoundFormat;
}
@Override
public final PointsFormat pointsFormat() {
return new Lucene60PointsFormat();
}
/** Returns the postings format that should be used for writing
* new segments of <code>field</code>.
*
* The default implementation always returns "Lucene50".
* <p>
* <b>WARNING:</b> if you subclass, you are responsible for index
* backwards compatibility: future version of Lucene are only
* guaranteed to be able to read the default implementation.
*/
public PostingsFormat getPostingsFormatForField(String field) {
return defaultFormat;
}
/** Returns the docvalues format that should be used for writing
* new segments of <code>field</code>.
*
* The default implementation always returns "Lucene80".
* <p>
* <b>WARNING:</b> if you subclass, you are responsible for index
* backwards compatibility: future version of Lucene are only
* guaranteed to be able to read the default implementation.
*/
public DocValuesFormat getDocValuesFormatForField(String field) {
return defaultDVFormat;
}
@Override
public final DocValuesFormat docValuesFormat() {
return docValuesFormat;
}
private final DocValuesFormat defaultDVFormat = DocValuesFormat.forName("Lucene80");
private final NormsFormat normsFormat = new Lucene80NormsFormat();
@Override
public final NormsFormat normsFormat() {
return normsFormat;
}
}
| 1 | 28,865 | can you use FilterCodec instead? | apache-lucene-solr | java |
@@ -407,6 +407,19 @@ class Setting extends BaseModel {
tagHeaderIsExpanded: { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
folderHeaderIsExpanded: { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
editor: { value: '', type: Setting.TYPE_STRING, subType: 'file_path_and_args', public: true, appTypes: ['cli', 'desktop'], label: () => _('Text editor command'), description: () => _('The editor command (may include arguments) that will be used to open a note. If none is provided it will try to auto-detect the default editor.') },
+ 'export.pdfPageSize': { value: 'A4', type: Setting.TYPE_STRING, isEnum: true, public: true, appTypes: ['desktop'], label: () => _('Page size for PDF export'), options: () => {
+ return {
+ 'A4': _('A4'),
+ 'Letter': _('Letter'),
+ };
+ }},
+ 'export.pdfPageOrientation': { value: false, type: Setting.TYPE_BOOL, isEnum: true, public: true, appTypes: ['desktop'], label: () => _('Page orientation for PDF export'), options: () => {
+ return {
+ false: _('Portrait'),
+ true: _('Landscape'),
+ };
+ }},
+
'net.customCertificates': {
value: '', | 1 | const BaseModel = require('lib/BaseModel.js');
const { Database } = require('lib/database.js');
const SyncTargetRegistry = require('lib/SyncTargetRegistry.js');
const { time } = require('lib/time-utils.js');
const { sprintf } = require('sprintf-js');
const ObjectUtils = require('lib/ObjectUtils');
const { toTitleCase } = require('lib/string-utils.js');
const { rtrimSlashes } = require('lib/path-utils.js');
const { _, supportedLocalesToLanguages, defaultLocale } = require('lib/locale.js');
const { shim } = require('lib/shim');
class Setting extends BaseModel {
static tableName() {
return 'settings';
}
static modelType() {
return BaseModel.TYPE_SETTING;
}
static metadata() {
if (this.metadata_) return this.metadata_;
const platform = shim.platformName();
const mobilePlatform = shim.mobilePlatform();
const emptyDirWarning = _('Attention: If you change this location, make sure you copy all your content to it before syncing, otherwise all files will be removed! See the FAQ for more details: %s', 'https://joplinapp.org/faq/');
// A "public" setting means that it will show up in the various config screens (or config command for the CLI tool), however
// if if private a setting might still be handled and modified by the app. For instance, the settings related to sorting notes are not
// public for the mobile and desktop apps because they are handled separately in menus.
this.metadata_ = {
'clientId': {
value: '',
type: Setting.TYPE_STRING,
public: false,
},
'sync.target': {
value: SyncTargetRegistry.nameToId('dropbox'),
type: Setting.TYPE_INT,
isEnum: true,
public: true,
section: 'sync',
label: () => _('Synchronisation target'),
description: appType => {
return appType !== 'cli' ? null : _('The target to synchonise to. Each sync target may have additional parameters which are named as `sync.NUM.NAME` (all documented below).');
},
options: () => {
return SyncTargetRegistry.idAndLabelPlainObject();
},
},
'sync.2.path': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
try {
return settings['sync.target'] == SyncTargetRegistry.nameToId('filesystem');
} catch (error) {
return false;
}
},
filter: value => {
return value ? rtrimSlashes(value) : '';
},
public: true,
label: () => _('Directory to synchronise with (absolute path)'),
description: () => emptyDirWarning,
},
'sync.5.path': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud');
},
public: true,
label: () => _('Nextcloud WebDAV URL'),
description: () => emptyDirWarning,
},
'sync.5.username': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud');
},
public: true,
label: () => _('Nextcloud username'),
},
'sync.5.password': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud');
},
public: true,
label: () => _('Nextcloud password'),
secure: true,
},
'sync.6.path': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav');
},
public: true,
label: () => _('WebDAV URL'),
description: () => emptyDirWarning,
},
'sync.6.username': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav');
},
public: true,
label: () => _('WebDAV username'),
},
'sync.6.password': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav');
},
public: true,
label: () => _('WebDAV password'),
secure: true,
},
'sync.3.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.4.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.7.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.1.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.2.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.3.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.4.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.5.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.6.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.7.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.resourceDownloadMode': {
value: 'always',
type: Setting.TYPE_STRING,
section: 'sync',
public: true,
isEnum: true,
appTypes: ['mobile', 'desktop'],
label: () => _('Attachment download behaviour'),
description: () => _('In "Manual" mode, attachments are downloaded only when you click on them. In "Auto", they are downloaded when you open the note. In "Always", all the attachments are downloaded whether you open the note or not.'),
options: () => {
return {
always: _('Always'),
manual: _('Manual'),
auto: _('Auto'),
};
},
},
'sync.maxConcurrentConnections': { value: 5, type: Setting.TYPE_INT, public: true, section: 'sync', label: () => _('Max concurrent connections'), minimum: 1, maximum: 20, step: 1 },
activeFolderId: { value: '', type: Setting.TYPE_STRING, public: false },
firstStart: { value: true, type: Setting.TYPE_BOOL, public: false },
locale: {
value: defaultLocale(),
type: Setting.TYPE_STRING,
isEnum: true,
public: true,
label: () => _('Language'),
options: () => {
return ObjectUtils.sortByValue(supportedLocalesToLanguages({ includeStats: true }));
},
},
dateFormat: {
value: Setting.DATE_FORMAT_1,
type: Setting.TYPE_STRING,
isEnum: true,
public: true,
label: () => _('Date format'),
options: () => {
let options = {};
const now = new Date('2017-01-30T12:00:00').getTime();
options[Setting.DATE_FORMAT_1] = time.formatMsToLocal(now, Setting.DATE_FORMAT_1);
options[Setting.DATE_FORMAT_2] = time.formatMsToLocal(now, Setting.DATE_FORMAT_2);
options[Setting.DATE_FORMAT_3] = time.formatMsToLocal(now, Setting.DATE_FORMAT_3);
options[Setting.DATE_FORMAT_4] = time.formatMsToLocal(now, Setting.DATE_FORMAT_4);
options[Setting.DATE_FORMAT_5] = time.formatMsToLocal(now, Setting.DATE_FORMAT_5);
options[Setting.DATE_FORMAT_6] = time.formatMsToLocal(now, Setting.DATE_FORMAT_6);
return options;
},
},
timeFormat: {
value: Setting.TIME_FORMAT_1,
type: Setting.TYPE_STRING,
isEnum: true,
public: true,
label: () => _('Time format'),
options: () => {
let options = {};
const now = new Date('2017-01-30T20:30:00').getTime();
options[Setting.TIME_FORMAT_1] = time.formatMsToLocal(now, Setting.TIME_FORMAT_1);
options[Setting.TIME_FORMAT_2] = time.formatMsToLocal(now, Setting.TIME_FORMAT_2);
return options;
},
},
theme: {
value: Setting.THEME_LIGHT,
type: Setting.TYPE_INT,
public: true,
appTypes: ['mobile', 'desktop'],
isEnum: true,
label: () => _('Theme'),
section: 'appearance',
options: () => {
let output = {};
output[Setting.THEME_LIGHT] = _('Light');
output[Setting.THEME_DARK] = _('Dark');
if (platform !== 'mobile') {
output[Setting.THEME_DRACULA] = _('Dracula');
output[Setting.THEME_SOLARIZED_LIGHT] = _('Solarised Light');
output[Setting.THEME_SOLARIZED_DARK] = _('Solarised Dark');
}
return output;
},
},
uncompletedTodosOnTop: { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, appTypes: ['cli'], label: () => _('Uncompleted to-dos on top') },
showCompletedTodos: { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, appTypes: ['cli'], label: () => _('Show completed to-dos') },
'notes.sortOrder.field': {
value: 'user_updated_time',
type: Setting.TYPE_STRING,
section: 'note',
isEnum: true,
public: true,
appTypes: ['cli'],
label: () => _('Sort notes by'),
options: () => {
const Note = require('lib/models/Note');
const noteSortFields = ['user_updated_time', 'user_created_time', 'title'];
const options = {};
for (let i = 0; i < noteSortFields.length; i++) {
options[noteSortFields[i]] = toTitleCase(Note.fieldToLabel(noteSortFields[i]));
}
return options;
},
},
'notes.sortOrder.reverse': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, label: () => _('Reverse sort order'), appTypes: ['cli'] },
'folders.sortOrder.field': {
value: 'title',
type: Setting.TYPE_STRING,
isEnum: true,
public: true,
appTypes: ['cli'],
label: () => _('Sort notebooks by'),
options: () => {
const Folder = require('lib/models/Folder');
const folderSortFields = ['title', 'last_note_user_updated_time'];
const options = {};
for (let i = 0; i < folderSortFields.length; i++) {
options[folderSortFields[i]] = toTitleCase(Folder.fieldToLabel(folderSortFields[i]));
}
return options;
},
},
'folders.sortOrder.reverse': { value: false, type: Setting.TYPE_BOOL, public: true, label: () => _('Reverse sort order'), appTypes: ['cli'] },
trackLocation: { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, label: () => _('Save geo-location with notes') },
newTodoFocus: {
value: 'title',
type: Setting.TYPE_STRING,
section: 'note',
isEnum: true,
public: true,
appTypes: ['desktop'],
label: () => _('When creating a new to-do:'),
options: () => {
return {
title: _('Focus title'),
body: _('Focus body'),
};
},
},
newNoteFocus: {
value: 'body',
type: Setting.TYPE_STRING,
section: 'note',
isEnum: true,
public: true,
appTypes: ['desktop'],
label: () => _('When creating a new note:'),
options: () => {
return {
title: _('Focus title'),
body: _('Focus body'),
};
},
},
'markdown.softbreaks': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable soft breaks') },
'markdown.plugin.katex': { value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable math expressions') },
'markdown.plugin.mark': { value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ==mark== syntax') },
'markdown.plugin.footnote': { value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable footnotes') },
'markdown.plugin.toc': { value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable table of contents extension') },
'markdown.plugin.sub': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ~sub~ syntax') },
'markdown.plugin.sup': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ^sup^ syntax') },
'markdown.plugin.deflist': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable deflist syntax') },
'markdown.plugin.abbr': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable abbreviation syntax') },
'markdown.plugin.emoji': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable markdown emoji') },
'markdown.plugin.insert': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ++insert++ syntax') },
'markdown.plugin.multitable': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable multimarkdown table extension') },
'markdown.plugin.fountain': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable Fountain syntax support') },
// Tray icon (called AppIndicator) doesn't work in Ubuntu
// http://www.webupd8.org/2017/04/fix-appindicator-not-working-for.html
// Might be fixed in Electron 18.x but no non-beta release yet. So for now
// by default we disable it on Linux.
showTrayIcon: {
value: platform !== 'linux',
type: Setting.TYPE_BOOL,
section: 'application',
public: true,
appTypes: ['desktop'],
label: () => _('Show tray icon'),
description: () => {
return platform === 'linux' ? _('Note: Does not work in all desktop environments.') : _('This will allow Joplin to run in the background. It is recommended to enable this setting so that your notes are constantly being synchronised, thus reducing the number of conflicts.');
},
},
startMinimized: { value: false, type: Setting.TYPE_BOOL, section: 'application', public: true, appTypes: ['desktop'], label: () => _('Start application minimised in the tray icon') },
collapsedFolderIds: { value: [], type: Setting.TYPE_ARRAY, public: false },
'db.ftsEnabled': { value: -1, type: Setting.TYPE_INT, public: false },
'encryption.enabled': { value: false, type: Setting.TYPE_BOOL, public: false },
'encryption.activeMasterKeyId': { value: '', type: Setting.TYPE_STRING, public: false },
'encryption.passwordCache': { value: {}, type: Setting.TYPE_OBJECT, public: false, secure: true },
'style.zoom': { value: 100, type: Setting.TYPE_INT, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Global zoom percentage'), minimum: 50, maximum: 500, step: 10 },
'style.editor.fontSize': { value: 13, type: Setting.TYPE_INT, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Editor font size'), minimum: 4, maximum: 50, step: 1 },
'style.editor.fontFamily':
(mobilePlatform) ?
({
value: Setting.FONT_DEFAULT,
type: Setting.TYPE_STRING,
isEnum: true,
public: true,
label: () => _('Editor font'),
appTypes: ['mobile'],
section: 'appearance',
options: () => {
// IMPORTANT: The font mapping must match the one in global-styles.js::editorFont()
if (mobilePlatform === 'ios') {
return {
[Setting.FONT_DEFAULT]: 'Default',
[Setting.FONT_MENLO]: 'Menlo',
[Setting.FONT_COURIER_NEW]: 'Courier New',
[Setting.FONT_AVENIR]: 'Avenir',
};
}
return {
[Setting.FONT_DEFAULT]: 'Default',
[Setting.FONT_MONOSPACE]: 'Monospace',
};
},
}) : {
value: '',
type: Setting.TYPE_STRING,
public: true,
appTypes: ['desktop'],
section: 'appearance',
label: () => _('Editor font family'),
description: () =>
_('This must be *monospace* font or it will not work properly. If the font ' +
'is incorrect or empty, it will default to a generic monospace font.'),
},
'style.sidebar.width': { value: 150, minimum: 80, maximum: 400, type: Setting.TYPE_INT, public: false, appTypes: ['desktop'] },
'style.noteList.width': { value: 150, minimum: 80, maximum: 400, type: Setting.TYPE_INT, public: false, appTypes: ['desktop'] },
autoUpdateEnabled: { value: true, type: Setting.TYPE_BOOL, section: 'application', public: true, appTypes: ['desktop'], label: () => _('Automatically update the application') },
'autoUpdate.includePreReleases': { value: false, type: Setting.TYPE_BOOL, section: 'application', public: true, appTypes: ['desktop'], label: () => _('Get pre-releases when checking for updates'), description: () => _('See the pre-release page for more details: %s', 'https://joplinapp.org/prereleases') },
'clipperServer.autoStart': { value: false, type: Setting.TYPE_BOOL, public: false },
'sync.interval': {
value: 300,
type: Setting.TYPE_INT,
section: 'sync',
isEnum: true,
public: true,
label: () => _('Synchronisation interval'),
options: () => {
return {
0: _('Disabled'),
300: _('%d minutes', 5),
600: _('%d minutes', 10),
1800: _('%d minutes', 30),
3600: _('%d hour', 1),
43200: _('%d hours', 12),
86400: _('%d hours', 24),
};
},
},
noteVisiblePanes: { value: ['editor', 'viewer'], type: Setting.TYPE_ARRAY, public: false, appTypes: ['desktop'] },
sidebarVisibility: { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
tagHeaderIsExpanded: { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
folderHeaderIsExpanded: { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
editor: { value: '', type: Setting.TYPE_STRING, subType: 'file_path_and_args', public: true, appTypes: ['cli', 'desktop'], label: () => _('Text editor command'), description: () => _('The editor command (may include arguments) that will be used to open a note. If none is provided it will try to auto-detect the default editor.') },
'net.customCertificates': {
value: '',
type: Setting.TYPE_STRING,
section: 'sync',
show: settings => {
return [SyncTargetRegistry.nameToId('nextcloud'), SyncTargetRegistry.nameToId('webdav')].indexOf(settings['sync.target']) >= 0;
},
public: true,
appTypes: ['desktop', 'cli'],
label: () => _('Custom TLS certificates'),
description: () => _('Comma-separated list of paths to directories to load the certificates from, or path to individual cert files. For example: /my/cert_dir, /other/custom.pem. Note that if you make changes to the TLS settings, you must save your changes before clicking on "Check synchronisation configuration".'),
},
'net.ignoreTlsErrors': {
value: false,
type: Setting.TYPE_BOOL,
section: 'sync',
show: settings => {
return [SyncTargetRegistry.nameToId('nextcloud'), SyncTargetRegistry.nameToId('webdav')].indexOf(settings['sync.target']) >= 0;
},
public: true,
appTypes: ['desktop', 'cli'],
label: () => _('Ignore TLS certificate errors'),
},
'sync.wipeOutFailSafe': { value: true, type: Setting.TYPE_BOOL, public: true, section: 'sync', label: () => _('Fail-safe: Do not wipe out local data when sync target is empty (often the result of a misconfiguration or bug)') },
'api.token': { value: null, type: Setting.TYPE_STRING, public: false },
'api.port': { value: null, type: Setting.TYPE_INT, public: true, appTypes: ['cli'], description: () => _('Specify the port that should be used by the API server. If not set, a default will be used.') },
'resourceService.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false },
'searchEngine.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false },
'revisionService.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false },
'searchEngine.initialIndexingDone': { value: false, type: Setting.TYPE_BOOL, public: false },
'revisionService.enabled': { section: 'revisionService', value: true, type: Setting.TYPE_BOOL, public: true, label: () => _('Enable note history') },
'revisionService.ttlDays': {
section: 'revisionService',
value: 90,
type: Setting.TYPE_INT,
public: true,
minimum: 1,
maximum: 365 * 2,
step: 1,
unitLabel: (value = null) => {
return value === null ? _('days') : _('%d days', value);
},
label: () => _('Keep note history for'),
},
'revisionService.intervalBetweenRevisions': { section: 'revisionService', value: 1000 * 60 * 10, type: Setting.TYPE_INT, public: false },
'revisionService.oldNoteInterval': { section: 'revisionService', value: 1000 * 60 * 60 * 24 * 7, type: Setting.TYPE_INT, public: false },
'welcome.wasBuilt': { value: false, type: Setting.TYPE_BOOL, public: false },
'welcome.enabled': { value: true, type: Setting.TYPE_BOOL, public: false },
};
return this.metadata_;
}
static settingMetadata(key) {
const metadata = this.metadata();
if (!(key in metadata)) throw new Error(`Unknown key: ${key}`);
let output = Object.assign({}, metadata[key]);
output.key = key;
return output;
}
static keyExists(key) {
return key in this.metadata();
}
static keyDescription(key, appType = null) {
const md = this.settingMetadata(key);
if (!md.description) return null;
return md.description(appType);
}
static keys(publicOnly = false, appType = null) {
if (!this.keys_) {
const metadata = this.metadata();
this.keys_ = [];
for (let n in metadata) {
if (!metadata.hasOwnProperty(n)) continue;
this.keys_.push(n);
}
}
if (appType || publicOnly) {
let output = [];
for (let i = 0; i < this.keys_.length; i++) {
const md = this.settingMetadata(this.keys_[i]);
if (publicOnly && !md.public) continue;
if (appType && md.appTypes && md.appTypes.indexOf(appType) < 0) continue;
output.push(md.key);
}
return output;
} else {
return this.keys_;
}
}
static isPublic(key) {
return this.keys(true).indexOf(key) >= 0;
}
static load() {
this.cancelScheduleSave();
this.cache_ = [];
return this.modelSelectAll('SELECT * FROM settings').then(rows => {
this.cache_ = [];
for (let i = 0; i < rows.length; i++) {
let c = rows[i];
if (!this.keyExists(c.key)) continue;
c.value = this.formatValue(c.key, c.value);
c.value = this.filterValue(c.key, c.value);
this.cache_.push(c);
}
this.dispatchUpdateAll();
});
}
static toPlainObject() {
const keys = this.keys();
let keyToValues = {};
for (let i = 0; i < keys.length; i++) {
keyToValues[keys[i]] = this.value(keys[i]);
}
return keyToValues;
}
static dispatchUpdateAll() {
this.dispatch({
type: 'SETTING_UPDATE_ALL',
settings: this.toPlainObject(),
});
}
static setConstant(key, value) {
if (!(key in this.constants_)) throw new Error(`Unknown constant key: ${key}`);
this.constants_[key] = value;
}
static setValue(key, value) {
if (!this.cache_) throw new Error('Settings have not been initialized!');
value = this.formatValue(key, value);
value = this.filterValue(key, value);
for (let i = 0; i < this.cache_.length; i++) {
let c = this.cache_[i];
if (c.key == key) {
const md = this.settingMetadata(key);
if (md.isEnum === true) {
if (!this.isAllowedEnumOption(key, value)) {
throw new Error(_('Invalid option value: "%s". Possible values are: %s.', value, this.enumOptionsDoc(key)));
}
}
if (c.value === value) return;
// Don't log this to prevent sensitive info (passwords, auth tokens...) to end up in logs
// this.logger().info('Setting: ' + key + ' = ' + c.value + ' => ' + value);
if ('minimum' in md && value < md.minimum) value = md.minimum;
if ('maximum' in md && value > md.maximum) value = md.maximum;
c.value = value;
this.dispatch({
type: 'SETTING_UPDATE_ONE',
key: key,
value: c.value,
});
this.scheduleSave();
return;
}
}
this.cache_.push({
key: key,
value: this.formatValue(key, value),
});
this.dispatch({
type: 'SETTING_UPDATE_ONE',
key: key,
value: this.formatValue(key, value),
});
this.scheduleSave();
}
static setObjectKey(settingKey, objectKey, value) {
let o = this.value(settingKey);
if (typeof o !== 'object') o = {};
o[objectKey] = value;
this.setValue(settingKey, o);
}
static deleteObjectKey(settingKey, objectKey) {
const o = this.value(settingKey);
if (typeof o !== 'object') return;
delete o[objectKey];
this.setValue(settingKey, o);
}
static valueToString(key, value) {
const md = this.settingMetadata(key);
value = this.formatValue(key, value);
if (md.type == Setting.TYPE_INT) return value.toFixed(0);
if (md.type == Setting.TYPE_BOOL) return value ? '1' : '0';
if (md.type == Setting.TYPE_ARRAY) return value ? JSON.stringify(value) : '[]';
if (md.type == Setting.TYPE_OBJECT) return value ? JSON.stringify(value) : '{}';
if (md.type == Setting.TYPE_STRING) return value ? `${value}` : '';
throw new Error(`Unhandled value type: ${md.type}`);
}
static filterValue(key, value) {
const md = this.settingMetadata(key);
return md.filter ? md.filter(value) : value;
}
static formatValue(key, value) {
const md = this.settingMetadata(key);
if (md.type == Setting.TYPE_INT) return !value ? 0 : Math.floor(Number(value));
if (md.type == Setting.TYPE_BOOL) {
if (typeof value === 'string') {
value = value.toLowerCase();
if (value === 'true') return true;
if (value === 'false') return false;
value = Number(value);
}
return !!value;
}
if (md.type === Setting.TYPE_ARRAY) {
if (!value) return [];
if (Array.isArray(value)) return value;
if (typeof value === 'string') return JSON.parse(value);
return [];
}
if (md.type === Setting.TYPE_OBJECT) {
if (!value) return {};
if (typeof value === 'object') return value;
if (typeof value === 'string') return JSON.parse(value);
return {};
}
if (md.type === Setting.TYPE_STRING) {
if (!value) return '';
return `${value}`;
}
throw new Error(`Unhandled value type: ${md.type}`);
}
static value(key) {
// Need to copy arrays and objects since in setValue(), the old value and new one is compared
// with strict equality and the value is updated only if changed. However if the caller acquire
// and object and change a key, the objects will be detected as equal. By returning a copy
// we avoid this problem.
function copyIfNeeded(value) {
if (value === null || value === undefined) return value;
if (Array.isArray(value)) return value.slice();
if (typeof value === 'object') return Object.assign({}, value);
return value;
}
if (key in this.constants_) {
const v = this.constants_[key];
const output = typeof v === 'function' ? v() : v;
if (output == 'SET_ME') throw new Error(`Setting constant has not been set: ${key}`);
return output;
}
if (!this.cache_) throw new Error('Settings have not been initialized!');
for (let i = 0; i < this.cache_.length; i++) {
if (this.cache_[i].key == key) {
return copyIfNeeded(this.cache_[i].value);
}
}
const md = this.settingMetadata(key);
return copyIfNeeded(md.value);
}
static isEnum(key) {
const md = this.settingMetadata(key);
return md.isEnum === true;
}
static enumOptionValues(key) {
const options = this.enumOptions(key);
let output = [];
for (let n in options) {
if (!options.hasOwnProperty(n)) continue;
output.push(n);
}
return output;
}
static enumOptionLabel(key, value) {
const options = this.enumOptions(key);
for (let n in options) {
if (n == value) return options[n];
}
return '';
}
static enumOptions(key) {
const metadata = this.metadata();
if (!metadata[key]) throw new Error(`Unknown key: ${key}`);
if (!metadata[key].options) throw new Error(`No options for: ${key}`);
return metadata[key].options();
}
static enumOptionsDoc(key, templateString = null) {
if (templateString === null) templateString = '%s: %s';
const options = this.enumOptions(key);
let output = [];
for (let n in options) {
if (!options.hasOwnProperty(n)) continue;
output.push(sprintf(templateString, n, options[n]));
}
return output.join(', ');
}
static isAllowedEnumOption(key, value) {
const options = this.enumOptions(key);
return !!options[value];
}
// For example, if settings is:
// { sync.5.path: 'http://example', sync.5.username: 'testing' }
// and baseKey is 'sync.5', the function will return
// { path: 'http://example', username: 'testing' }
static subValues(baseKey, settings) {
let output = {};
for (let key in settings) {
if (!settings.hasOwnProperty(key)) continue;
if (key.indexOf(baseKey) === 0) {
const subKey = key.substr(baseKey.length + 1);
output[subKey] = settings[key];
}
}
return output;
}
static async saveAll() {
if (!this.saveTimeoutId_) return Promise.resolve();
this.logger().info('Saving settings...');
clearTimeout(this.saveTimeoutId_);
this.saveTimeoutId_ = null;
let queries = [];
queries.push('DELETE FROM settings');
for (let i = 0; i < this.cache_.length; i++) {
let s = Object.assign({}, this.cache_[i]);
s.value = this.valueToString(s.key, s.value);
queries.push(Database.insertQuery(this.tableName(), s));
}
await BaseModel.db().transactionExecBatch(queries);
this.logger().info('Settings have been saved.');
}
static scheduleSave() {
if (!Setting.autoSaveEnabled) return;
if (this.saveTimeoutId_) clearTimeout(this.saveTimeoutId_);
this.saveTimeoutId_ = setTimeout(() => {
this.saveAll();
}, 500);
}
static cancelScheduleSave() {
if (this.saveTimeoutId_) clearTimeout(this.saveTimeoutId_);
this.saveTimeoutId_ = null;
}
static publicSettings(appType) {
if (!appType) throw new Error('appType is required');
const metadata = this.metadata();
let output = {};
for (let key in metadata) {
if (!metadata.hasOwnProperty(key)) continue;
let s = Object.assign({}, metadata[key]);
if (!s.public) continue;
if (s.appTypes && s.appTypes.indexOf(appType) < 0) continue;
s.value = this.value(key);
output[key] = s;
}
return output;
}
static typeToString(typeId) {
if (typeId === Setting.TYPE_INT) return 'int';
if (typeId === Setting.TYPE_STRING) return 'string';
if (typeId === Setting.TYPE_BOOL) return 'bool';
if (typeId === Setting.TYPE_ARRAY) return 'array';
if (typeId === Setting.TYPE_OBJECT) return 'object';
}
static groupMetadatasBySections(metadatas) {
let sections = [];
const generalSection = { name: 'general', metadatas: [] };
const nameToSections = {};
nameToSections['general'] = generalSection;
sections.push(generalSection);
for (let i = 0; i < metadatas.length; i++) {
const md = metadatas[i];
if (!md.section) {
generalSection.metadatas.push(md);
} else {
if (!nameToSections[md.section]) {
nameToSections[md.section] = { name: md.section, metadatas: [] };
sections.push(nameToSections[md.section]);
}
nameToSections[md.section].metadatas.push(md);
}
}
return sections;
}
static sectionNameToLabel(name) {
if (name === 'general') return _('General');
if (name === 'sync') return _('Synchronisation');
if (name === 'appearance') return _('Appearance');
if (name === 'note') return _('Note');
if (name === 'plugins') return _('Plugins');
if (name === 'application') return _('Application');
if (name === 'revisionService') return _('Note History');
if (name === 'encryption') return _('Encryption');
if (name === 'server') return _('Web Clipper');
return name;
}
static sectionNameToIcon(name) {
if (name === 'general') return 'fa-sliders';
if (name === 'sync') return 'fa-refresh';
if (name === 'appearance') return 'fa-pencil';
if (name === 'note') return 'fa-file-text-o';
if (name === 'plugins') return 'fa-puzzle-piece';
if (name === 'application') return 'fa-cog';
if (name === 'revisionService') return 'fa-archive-org';
if (name === 'encryption') return 'fa-key-modern';
if (name === 'server') return 'fa-hand-scissors-o';
return name;
}
static appTypeToLabel(name) {
// Not translated for now because only used on Welcome notes (which are not translated)
if (name === 'cli') return 'CLI';
return name[0].toUpperCase() + name.substr(1).toLowerCase();
}
}
Setting.TYPE_INT = 1;
Setting.TYPE_STRING = 2;
Setting.TYPE_BOOL = 3;
Setting.TYPE_ARRAY = 4;
Setting.TYPE_OBJECT = 5;
Setting.THEME_LIGHT = 1;
Setting.THEME_DARK = 2;
Setting.THEME_SOLARIZED_LIGHT = 3;
Setting.THEME_SOLARIZED_DARK = 4;
Setting.THEME_DRACULA = 5;
Setting.FONT_DEFAULT = 0;
Setting.FONT_MENLO = 1;
Setting.FONT_COURIER_NEW = 2;
Setting.FONT_AVENIR = 3;
Setting.FONT_MONOSPACE = 4;
Setting.DATE_FORMAT_1 = 'DD/MM/YYYY';
Setting.DATE_FORMAT_2 = 'DD/MM/YY';
Setting.DATE_FORMAT_3 = 'MM/DD/YYYY';
Setting.DATE_FORMAT_4 = 'MM/DD/YY';
Setting.DATE_FORMAT_5 = 'YYYY-MM-DD';
Setting.DATE_FORMAT_6 = 'DD.MM.YYYY';
Setting.TIME_FORMAT_1 = 'HH:mm';
Setting.TIME_FORMAT_2 = 'h:mm A';
// Contains constants that are set by the application and
// cannot be modified by the user:
Setting.constants_ = {
env: 'SET_ME',
isDemo: false,
appName: 'joplin',
appId: 'SET_ME', // Each app should set this identifier
appType: 'SET_ME', // 'cli' or 'mobile'
resourceDirName: '',
resourceDir: '',
profileDir: '',
templateDir: '',
tempDir: '',
openDevTools: false,
syncVersion: 1,
};
Setting.autoSaveEnabled = true;
module.exports = Setting;
| 1 | 10,525 | I know there's only two values but I find it a bit confusing that it's true/false. Could you change it to a string enum with values "portrait" and "landscape"? Then when calling printToPdf you can just do `landscape: Setting.value('export.pdfPageOrientation') === 'landscape'` | laurent22-joplin | js |
@@ -12,3 +12,11 @@ var dbSchemaVersion = Migration{
return CommitProgress(db, nil, true)
},
}
+
+var dbSchemaVersion2 = Migration{
+ Name: "db_schema_version2",
+ Up: func(db ethdb.Database, tmpdir string, progress []byte, CommitProgress etl.LoadCommitHandler) (err error) {
+ // This migration is no-op, but it forces the migration mechanism to apply it and thus write the DB schema version info
+ return CommitProgress(db, nil, true)
+ },
+} | 1 | package migrations
import (
"github.com/ledgerwatch/erigon/common/etl"
"github.com/ledgerwatch/erigon/ethdb"
)
var dbSchemaVersion = Migration{
Name: "db_schema_version",
Up: func(db ethdb.Database, tmpdir string, progress []byte, CommitProgress etl.LoadCommitHandler) (err error) {
// This migration is no-op, but it forces the migration mechanism to apply it and thus write the DB schema version info
return CommitProgress(db, nil, true)
},
}
| 1 | 22,209 | I think this migration should fail for MDBX if it uses old table names | ledgerwatch-erigon | go |
@@ -224,7 +224,7 @@ module Beaker
# @raise [ArgumentError] if a hosts file is generated, but it can't
# be read by the HostsFileParser
def parse_hosts_options
- if File.exists?(@options[:hosts_file])
+ if @options[:hosts_file].nil? || File.exists?(@options[:hosts_file])
#read the hosts file that contains the node configuration and hypervisor info
return Beaker::Options::HostsFileParser.parse_hosts_file(@options[:hosts_file])
end | 1 | require 'yaml'
module Beaker
module Options
#An Object that parses, merges and normalizes all supported Beaker options and arguments
class Parser
GITREPO = 'git://github.com/puppetlabs'
#These options can have the form of arg1,arg2 or [arg] or just arg,
#should default to []
LONG_OPTS = [:helper, :load_path, :tests, :pre_suite, :post_suite, :install, :pre_cleanup, :modules]
#These options expand out into an array of .rb files
RB_FILE_OPTS = [:tests, :pre_suite, :post_suite, :pre_cleanup]
PARSE_ERROR = Psych::SyntaxError
#The OptionsHash of all parsed options
attr_accessor :options
# Returns the git repository used for git installations
# @return [String] The git repository
def repo
GITREPO
end
# Returns a description of Beaker's supported arguments
# @return [String] The usage String
def usage
@command_line_parser.usage
end
# Normalizes argument into an Array. Argument can either be converted into an array of a single value,
# or can become an array of multiple values by splitting arg over ','. If argument is already an
# array that array is returned untouched.
# @example
# split_arg([1, 2, 3]) == [1, 2, 3]
# split_arg(1) == [1]
# split_arg("1,2") == ["1", "2"]
# split_arg(nil) == []
# @param [Array, String] arg Either an array or a string to be split into an array
# @return [Array] An array of the form arg, [arg], or arg.split(',')
def split_arg arg
arry = []
if arg.is_a?(Array)
arry += arg
elsif arg =~ /,/
arry += arg.split(',')
else
arry << arg
end
arry
end
# Generates a list of files based upon a given path or list of paths.
#
# Looks recursively for .rb files in paths.
#
# @param [Array] paths Array of file paths to search for .rb files
# @return [Array] An Array of fully qualified paths to .rb files
# @raise [ArgumentError] Raises if no .rb files are found in searched directory or if
# no .rb files are found overall
def file_list(paths)
files = []
if !paths.empty?
paths.each do |root|
@validator.validate_path(root)
path_files = []
if File.file?(root)
path_files << root
elsif File.directory?(root) #expand and explore
path_files = Dir.glob(File.join(root, '**/*.rb'))
.select { |f| File.file?(f) }
.sort_by { |file| [file.count('/'), file] }
end
@validator.validate_files(path_files, root)
files += path_files
end
end
@validator.validate_files(files, paths.to_s)
files
end
# resolves all file symlinks that require it. This modifies @options.
#
# @note doing it here allows us to not need duplicate logic, which we
# would need if we were doing it in the parser (--hosts & --config)
#
# @return nil
# @api public
def resolve_symlinks!
if @options[:hosts_file] && !@options[:hosts_file_generated]
@options[:hosts_file] = File.realpath(@options[:hosts_file])
end
end
#Converts array of paths into array of fully qualified git repo URLS with expanded keywords
#
#Supports the following keywords
# PUPPET
# FACTER
# HIERA
# HIERA-PUPPET
#@example
# opts = ["PUPPET/3.1"]
# parse_git_repos(opts) == ["#{GITREPO}/puppet.git#3.1"]
#@param [Array] git_opts An array of paths
#@return [Array] An array of fully qualified git repo URLs with expanded keywords
def parse_git_repos(git_opts)
git_opts.map! { |opt|
case opt
when /^PUPPET\//
opt = "#{repo}/puppet.git##{opt.split('/', 2)[1]}"
when /^FACTER\//
opt = "#{repo}/facter.git##{opt.split('/', 2)[1]}"
when /^HIERA\//
opt = "#{repo}/hiera.git##{opt.split('/', 2)[1]}"
when /^HIERA-PUPPET\//
opt = "#{repo}/hiera-puppet.git##{opt.split('/', 2)[1]}"
end
opt
}
git_opts
end
#Add the 'default' role to the host determined to be the default. If a host already has the role default then
#do nothing. If more than a single host has the role 'default', raise error.
#Default host determined to be 1) the only host in a single host configuration, 2) the host with the role 'master'
#defined.
#@param [Hash] hosts A hash of hosts, each identified by a String name. Each named host will have an Array of roles
def set_default_host!(hosts)
default = []
master = []
default_host_name = nil
#look through the hosts and find any hosts with role 'default' and any hosts with role 'master'
hosts.each_key do |name|
host = hosts[name]
if host[:roles].include?('default')
default << name
elsif host[:roles].include?('master')
master << name
end
end
# default_set? will throw an error if length > 1
# and return false if no default is set.
if [email protected]_set?(default)
#no default set, let's make one
if not master.empty? and master.length == 1
default_host_name = master[0]
elsif hosts.length == 1
default_host_name = hosts.keys[0]
end
if default_host_name
hosts[default_host_name][:roles] << 'default'
end
end
end
#Constructor for Parser
#
def initialize
@command_line_parser = Beaker::Options::CommandLineParser.new
@presets = Beaker::Options::Presets.new
@validator = Beaker::Options::Validator.new
end
# Parses ARGV or provided arguments array, file options, hosts options and combines with environment variables and
# preset defaults to generate a Hash representing the Beaker options for a given test run
#
# Order of priority is as follows:
# 1. environment variables are given top priority
# 2. ARGV or provided arguments array
# 3. the 'CONFIG' section of the hosts file
# 4. options file values
# 5. default or preset values are given the lowest priority
#
# @param [Array] args ARGV or a provided arguments array
# @raise [ArgumentError] Raises error on bad input
def parse_args(args = ARGV)
@options = @presets.presets
cmd_line_options = @command_line_parser.parse(args)
cmd_line_options[:command_line] = ([$0] + args).join(' ')
file_options = Beaker::Options::OptionsFileParser.parse_options_file(cmd_line_options[:options_file])
# merge together command line and file_options
# overwrite file options with command line options
cmd_line_and_file_options = file_options.merge(cmd_line_options)
# merge command line and file options with defaults
# overwrite defaults with command line and file options
@options = @options.merge(cmd_line_and_file_options)
if not @options[:help] and not @options[:beaker_version_print]
hosts_options = parse_hosts_options
# merge in host file vars
# overwrite options (default, file options, command line) with host file options
@options = @options.merge(hosts_options)
# re-merge the command line options
# overwrite options (default, file options, hosts file ) with command line arguments
@options = @options.merge(cmd_line_options)
# merge in env vars
# overwrite options (default, file options, command line, hosts file) with env
env_vars = @presets.env_vars
@options = @options.merge(env_vars)
normalize_args
end
@options
end
# Parse hosts options from host files into a host options hash. Falls back
# to trying as a beaker-hostgenerator string if reading the hosts file
# doesn't work
#
# @return [Hash] Host options, containing all host-specific details
# @raise [ArgumentError] if a hosts file is generated, but it can't
# be read by the HostsFileParser
def parse_hosts_options
if File.exists?(@options[:hosts_file])
#read the hosts file that contains the node configuration and hypervisor info
return Beaker::Options::HostsFileParser.parse_hosts_file(@options[:hosts_file])
end
dne_message = "\nHosts file '#{@options[:hosts_file]}' does not exist."
dne_message << "\nTrying as beaker-hostgenerator input.\n\n"
$stdout.puts dne_message
require 'beaker-hostgenerator'
hosts_file_content = begin
bhg_cli = BeakerHostGenerator::CLI.new( [ @options[:hosts_file] ] )
bhg_cli.execute
rescue BeakerHostGenerator::Exceptions::Error,
BeakerHostGenerator::Exceptions::InvalidNodeSpecError => error
error_message = "\nbeaker-hostgenerator was not able to use this value as input."
error_message << "\nExiting with an Error.\n\n"
$stderr.puts error_message
raise error
end
@options[:hosts_file_generated] = true
Beaker::Options::HostsFileParser.parse_hosts_string( hosts_file_content )
end
#Validate all merged options values for correctness
#
#Currently checks:
# - each host has a valid platform
# - if a keyfile is provided then use it
# - paths provided to --test, --pre-suite, --post-suite provided lists of .rb files for testing
# - --fail-mode is one of 'fast', 'stop' or nil
# - if using blimpy hypervisor an EC2 YAML file exists
# - if using the aix, solaris, or vcloud hypervisors a .fog file exists
# - that one and only one master is defined per set of hosts
# - that solaris/windows/aix hosts are agent only for PE tests OR
# - sets the default host based upon machine definitions
# - if an ssh user has been defined make it the host user
#
#@raise [ArgumentError] Raise if argument/options values are invalid
def normalize_args
@options['HOSTS'].each_key do |name|
@validator.validate_platform(@options['HOSTS'][name], name)
@options['HOSTS'][name]['platform'] = Platform.new(@options['HOSTS'][name]['platform'])
end
#use the keyfile if present
if @options.has_key?(:keyfile)
@options[:ssh][:keys] = [@options[:keyfile]]
end
#split out arguments - these arguments can have the form of arg1,arg2 or [arg] or just arg
#will end up being normalized into an array
LONG_OPTS.each do |opt|
if @options.has_key?(opt)
@options[opt] = split_arg(@options[opt])
if RB_FILE_OPTS.include?(opt) && (not @options[opt] == [])
@options[opt] = file_list(@options[opt])
end
if opt == :install
@options[:install] = parse_git_repos(@options[:install])
end
else
@options[opt] = []
end
end
@validator.validate_fail_mode(@options[:fail_mode])
@validator.validate_preserve_hosts(@options[:preserve_hosts])
#check for config files necessary for different hypervisors
hypervisors = get_hypervisors(@options[:HOSTS])
hypervisors.each do |visor|
check_hypervisor_config(visor)
end
#check that roles of hosts make sense
# - must be one and only one master
master = 0
roles = get_roles(@options[:HOSTS])
roles.each do |role_array|
master += 1 if role_array.include?('master')
@validator.validate_frictionless_roles(role_array)
end
@validator.validate_master_count(master)
#check that windows/el-4 boxes are only agents (solaris can be a master in foss cases)
@options[:HOSTS].each_key do |name|
host = @options[:HOSTS][name]
if host[:platform] =~ /windows|el-4/
test_host_roles(name, host)
end
#check to see if a custom user account has been provided, if so use it
if host[:ssh] && host[:ssh][:user]
host[:user] = host[:ssh][:user]
end
# merge host tags for this host with the global/preset host tags
host[:host_tags] = @options[:host_tags].merge(host[:host_tags] || {})
end
normalize_tags!
@validator.validate_tags(@options[:tag_includes], @options[:tag_excludes])
resolve_symlinks!
#set the default role
set_default_host!(@options[:HOSTS])
end
# Get an array containing lists of roles by parsing each host in hosts.
#
# @param [Array<Array<String>>] hosts beaker hosts
# @return [Array] roles [['master', 'database'], ['agent'], ...]
def get_roles(hosts)
roles = []
hosts.each_key do |name|
roles << hosts[name][:roles]
end
roles
end
# Get a unique list of hypervisors from list of host.
#
# @param [Array] hosts beaker hosts
# @return [Array] unique list of hypervisors
def get_hypervisors(hosts)
hypervisors = []
hosts.each_key { |name| hypervisors << hosts[name][:hypervisor].to_s }
hypervisors.uniq
end
# Validate the config file for visor exists.
#
# @param [String] visor Hypervisor name
# @return [nil] no return
# @raise [ArgumentError] Raises error if config file does not exist or is not valid YAML
def check_hypervisor_config(visor)
if ['blimpy'].include?(visor)
@validator.check_yaml_file(@options[:ec2_yaml], "required by #{visor}")
end
if %w(aix solaris vcloud).include?(visor)
@validator.check_yaml_file(@options[:dot_fog], "required by #{visor}")
end
end
# Normalize include and exclude tags. This modifies @options.
#
def normalize_tags!
@options[:tag_includes] ||= ''
@options[:tag_excludes] ||= ''
@options[:tag_includes] = @options[:tag_includes].split(',') if @options[:tag_includes].respond_to?(:split)
@options[:tag_excludes] = @options[:tag_excludes].split(',') if @options[:tag_excludes].respond_to?(:split)
@options[:tag_includes].map!(&:downcase)
@options[:tag_excludes].map!(&:downcase)
end
private
# @api private
def test_host_roles(host_name, host_hash)
exclude_roles = %w(master database dashboard)
host_roles = host_hash[:roles]
unless (host_roles & exclude_roles).empty?
@validator.parser_error "#{host_hash[:platform].to_s} box '#{host_name}' may not have roles: #{exclude_roles.join(', ')}."
end
end
end
end
end
| 1 | 13,926 | Should this be negated? `!@options[:hosts_file].nil?` Otherwise it'll enter the `if` statement and `nil` will be passed to `HostsFileParser.parse_hosts_file`, which I'm assuming is bad. | voxpupuli-beaker | rb |
@@ -91,6 +91,14 @@ namespace NLog
/// Loads NLog config created by the method <paramref name="configBuilder"/>
/// </summary>
public static ISetupBuilder LoadConfiguration(this ISetupBuilder setupBuilder, Action<ISetupLoadConfigurationBuilder> configBuilder)
+ {
+ return LoadConfiguration(setupBuilder, true, configBuilder);
+ }
+
+ /// <summary>
+ /// Loads NLog config created by the method <paramref name="configBuilder"/>
+ /// </summary>
+ public static ISetupBuilder LoadConfiguration(this ISetupBuilder setupBuilder, bool applyOnReload, Action<ISetupLoadConfigurationBuilder> configBuilder)
{
var config = setupBuilder.LogFactory._config;
var setupConfig = new SetupLoadConfigurationBuilder(setupBuilder.LogFactory, config); | 1 | //
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// 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 Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Runtime.CompilerServices;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Extension methods to setup LogFactory options
/// </summary>
public static class SetupBuilderExtensions
{
/// <summary>
/// Gets the logger with the full name of the current class, so namespace and class name.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(this ISetupBuilder setupBuilder)
{
return setupBuilder.LogFactory.GetLogger(StackTraceUsageUtils.GetClassFullName());
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
public static Logger GetLogger(this ISetupBuilder setupBuilder, string name)
{
return setupBuilder.LogFactory.GetLogger(name);
}
/// <summary>
/// Configures loading of NLog extensions for Targets and LayoutRenderers
/// </summary>
public static ISetupBuilder SetupExtensions(this ISetupBuilder setupBuilder, Action<ISetupExtensionsBuilder> extensionsBuilder)
{
extensionsBuilder(new SetupExtensionsBuilder(setupBuilder.LogFactory));
return setupBuilder;
}
/// <summary>
/// Configures the output of NLog <see cref="Common.InternalLogger"/> for diagnostics / troubleshooting
/// </summary>
public static ISetupBuilder SetupInternalLogger(this ISetupBuilder setupBuilder, Action<ISetupInternalLoggerBuilder> internalLoggerBuilder)
{
internalLoggerBuilder(new SetupInternalLoggerBuilder(setupBuilder.LogFactory));
return setupBuilder;
}
/// <summary>
/// Configures serialization and transformation of LogEvents
/// </summary>
public static ISetupBuilder SetupSerialization(this ISetupBuilder setupBuilder, Action<ISetupSerializationBuilder> serializationBuilder)
{
serializationBuilder(new SetupSerializationBuilder(setupBuilder.LogFactory));
return setupBuilder;
}
/// <summary>
/// Loads NLog config created by the method <paramref name="configBuilder"/>
/// </summary>
public static ISetupBuilder LoadConfiguration(this ISetupBuilder setupBuilder, Action<ISetupLoadConfigurationBuilder> configBuilder)
{
var config = setupBuilder.LogFactory._config;
var setupConfig = new SetupLoadConfigurationBuilder(setupBuilder.LogFactory, config);
configBuilder(setupConfig);
var newConfig = setupConfig._configuration;
bool configHasChanged = !ReferenceEquals(config, setupBuilder.LogFactory._config);
if (ReferenceEquals(newConfig, setupBuilder.LogFactory._config))
{
setupBuilder.LogFactory.ReconfigExistingLoggers();
}
else if (!configHasChanged || !ReferenceEquals(config, newConfig))
{
setupBuilder.LogFactory.Configuration = newConfig;
}
return setupBuilder;
}
/// <summary>
/// Loads NLog config provided in <paramref name="loggingConfiguration"/>
/// </summary>
public static ISetupBuilder LoadConfiguration(this ISetupBuilder setupBuilder, LoggingConfiguration loggingConfiguration)
{
setupBuilder.LogFactory.Configuration = loggingConfiguration;
return setupBuilder;
}
/// <summary>
/// Loads NLog config from filename <paramref name="configFile"/> if provided, else fallback to scanning for NLog.config
/// </summary>
public static ISetupBuilder LoadConfigurationFromFile(this ISetupBuilder setupBuilder, string configFile = null, bool optional = true)
{
setupBuilder.LogFactory.LoadConfiguration(configFile, optional);
return setupBuilder;
}
/// <summary>
/// Loads NLog config from XML in <paramref name="configXml"/>
/// </summary>
public static ISetupBuilder LoadConfigurationFromXml(this ISetupBuilder setupBuilder, string configXml)
{
setupBuilder.LogFactory.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml, setupBuilder.LogFactory);
return setupBuilder;
}
}
}
| 1 | 21,340 | I'm doubting if adding a bool here is a good idea. Maybe it should be an option object? Otherwise it's hard to extend. But an option object is a bit strange in a fluent API? What do you think @snakefoot ? | NLog-NLog | .cs |
@@ -410,7 +410,7 @@ public class MultiPhraseQuery extends Query {
* <p>
* Note: positions are merged during freq()
*/
- static class UnionPostingsEnum extends PostingsEnum {
+ public static class UnionPostingsEnum extends PostingsEnum {
/** queue ordered by docid */
final DocsQueue docsQueue;
/** cost of this enum: sum of its subs */ | 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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.SlowImpactsEnum;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermState;
import org.apache.lucene.index.TermStates;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.search.similarities.Similarity.SimScorer;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.PriorityQueue;
/**
* A generalized version of {@link PhraseQuery}, with the possibility of
* adding more than one term at the same position that are treated as a disjunction (OR).
* To use this class to search for the phrase "Microsoft app*" first create a Builder and use
* {@link Builder#add(Term)} on the term "microsoft" (assuming lowercase analysis), then
* find all terms that have "app" as prefix using {@link LeafReader#terms(String)},
* seeking to "app" then iterating and collecting terms until there is no longer
* that prefix, and finally use {@link Builder#add(Term[])} to add them.
* {@link Builder#build()} returns the fully constructed (and immutable) MultiPhraseQuery.
*/
public class MultiPhraseQuery extends Query {
/** A builder for multi-phrase queries */
public static class Builder {
private String field; // becomes non-null on first add() then is unmodified
private final ArrayList<Term[]> termArrays;
private final ArrayList<Integer> positions;
private int slop;
/** Default constructor. */
public Builder() {
this.field = null;
this.termArrays = new ArrayList<>();
this.positions = new ArrayList<>();
this.slop = 0;
}
/** Copy constructor: this will create a builder that has the same
* configuration as the provided builder. */
public Builder(MultiPhraseQuery multiPhraseQuery) {
this.field = multiPhraseQuery.field;
int length = multiPhraseQuery.termArrays.length;
this.termArrays = new ArrayList<>(length);
this.positions = new ArrayList<>(length);
for (int i = 0 ; i < length ; ++i) {
this.termArrays.add(multiPhraseQuery.termArrays[i]);
this.positions.add(multiPhraseQuery.positions[i]);
}
this.slop = multiPhraseQuery.slop;
}
/** Sets the phrase slop for this query.
* @see PhraseQuery#getSlop()
*/
public Builder setSlop(int s) {
if (s < 0) {
throw new IllegalArgumentException("slop value cannot be negative");
}
slop = s;
return this;
}
/** Add a single term at the next position in the phrase.
*/
public Builder add(Term term) { return add(new Term[]{term}); }
/** Add multiple terms at the next position in the phrase. Any of the terms
* may match (a disjunction).
* The array is not copied or mutated, the caller should consider it
* immutable subsequent to calling this method.
*/
public Builder add(Term[] terms) {
int position = 0;
if (positions.size() > 0)
position = positions.get(positions.size() - 1) + 1;
return add(terms, position);
}
/**
* Allows to specify the relative position of terms within the phrase.
* The array is not copied or mutated, the caller should consider it
* immutable subsequent to calling this method.
*/
public Builder add(Term[] terms, int position) {
Objects.requireNonNull(terms, "Term array must not be null");
if (termArrays.size() == 0)
field = terms[0].field();
for (Term term : terms) {
if (!term.field().equals(field)) {
throw new IllegalArgumentException(
"All phrase terms must be in the same field (" + field + "): " + term);
}
}
termArrays.add(terms);
positions.add(position);
return this;
}
/** Builds a {@link MultiPhraseQuery}. */
public MultiPhraseQuery build() {
int[] positionsArray = new int[this.positions.size()];
for (int i = 0; i < this.positions.size(); ++i) {
positionsArray[i] = this.positions.get(i);
}
Term[][] termArraysArray = termArrays.toArray(new Term[termArrays.size()][]);
return new MultiPhraseQuery(field, termArraysArray, positionsArray, slop);
}
}
private final String field;
private final Term[][] termArrays;
private final int[] positions;
private final int slop;
private MultiPhraseQuery(String field, Term[][] termArrays, int[] positions, int slop) {
// No argument checks here since they are provided by the MultiPhraseQuery.Builder
this.field = field;
this.termArrays = termArrays;
this.positions = positions;
this.slop = slop;
}
/** Sets the phrase slop for this query.
* @see PhraseQuery#getSlop()
*/
public int getSlop() { return slop; }
/**
* Returns the arrays of arrays of terms in the multi-phrase.
* Do not modify!
*/
public Term[][] getTermArrays() {
return termArrays;
}
/**
* Returns the relative positions of terms in this phrase.
* Do not modify!
*/
public int[] getPositions() {
return positions;
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (termArrays.length == 0) {
return new MatchNoDocsQuery("empty MultiPhraseQuery");
} else if (termArrays.length == 1) { // optimize one-term case
Term[] terms = termArrays[0];
BooleanQuery.Builder builder = new BooleanQuery.Builder();
for (Term term : terms) {
builder.add(new TermQuery(term), BooleanClause.Occur.SHOULD);
}
return builder.build();
} else {
return super.rewrite(reader);
}
}
@Override
public void visit(QueryVisitor visitor) {
if (visitor.acceptField(field) == false) {
return;
}
QueryVisitor v = visitor.getSubVisitor(BooleanClause.Occur.MUST, this);
for (Term[] terms : termArrays) {
QueryVisitor sv = v.getSubVisitor(BooleanClause.Occur.SHOULD, this);
sv.consumeTerms(this, terms);
}
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
final Map<Term,TermStates> termStates = new HashMap<>();
return new PhraseWeight(this, field, searcher, scoreMode) {
@Override
protected Similarity.SimScorer getStats(IndexSearcher searcher) throws IOException {
final IndexReaderContext context = searcher.getTopReaderContext();
// compute idf
ArrayList<TermStatistics> allTermStats = new ArrayList<>();
for(final Term[] terms: termArrays) {
for (Term term: terms) {
TermStates ts = termStates.get(term);
if (ts == null) {
ts = TermStates.build(context, term, scoreMode.needsScores());
termStates.put(term, ts);
}
if (scoreMode.needsScores() && ts.docFreq() > 0) {
allTermStats.add(searcher.termStatistics(term, ts.docFreq(), ts.totalTermFreq()));
}
}
}
if (allTermStats.isEmpty()) {
return null; // none of the terms were found, we won't use sim at all
} else {
return similarity.scorer(
boost,
searcher.collectionStatistics(field),
allTermStats.toArray(new TermStatistics[allTermStats.size()]));
}
}
@Override
protected PhraseMatcher getPhraseMatcher(LeafReaderContext context, SimScorer scorer, boolean exposeOffsets) throws IOException {
assert termArrays.length != 0;
final LeafReader reader = context.reader();
PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[termArrays.length];
final Terms fieldTerms = reader.terms(field);
if (fieldTerms == null) {
return null;
}
// TODO: move this check to createWeight to happen earlier to the user?
if (fieldTerms.hasPositions() == false) {
throw new IllegalStateException("field \"" + field + "\" was indexed without position data;" +
" cannot run MultiPhraseQuery (phrase=" + getQuery() + ")");
}
// Reuse single TermsEnum below:
final TermsEnum termsEnum = fieldTerms.iterator();
float totalMatchCost = 0;
for (int pos=0; pos<postingsFreqs.length; pos++) {
Term[] terms = termArrays[pos];
List<PostingsEnum> postings = new ArrayList<>();
for (Term term : terms) {
TermState termState = termStates.get(term).get(context);
if (termState != null) {
termsEnum.seekExact(term.bytes(), termState);
postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS));
totalMatchCost += PhraseQuery.termPositionsCost(termsEnum);
}
}
if (postings.isEmpty()) {
return null;
}
final PostingsEnum postingsEnum;
if (postings.size() == 1) {
postingsEnum = postings.get(0);
} else {
postingsEnum = exposeOffsets ? new UnionFullPostingsEnum(postings) : new UnionPostingsEnum(postings);
}
postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, new SlowImpactsEnum(postingsEnum), positions[pos], terms);
}
// sort by increasing docFreq order
if (slop == 0) {
ArrayUtil.timSort(postingsFreqs);
return new ExactPhraseMatcher(postingsFreqs, scoreMode, scorer, totalMatchCost);
}
else {
return new SloppyPhraseMatcher(postingsFreqs, slop, scoreMode, scorer, totalMatchCost, exposeOffsets);
}
}
};
}
/** Prints a user-readable version of this query. */
@Override
public final String toString(String f) {
StringBuilder buffer = new StringBuilder();
if (field == null || !field.equals(f)) {
buffer.append(field);
buffer.append(":");
}
buffer.append("\"");
int lastPos = -1;
for (int i = 0 ; i < termArrays.length ; ++i) {
Term[] terms = termArrays[i];
int position = positions[i];
if (i != 0) {
buffer.append(" ");
for (int j=1; j<(position-lastPos); j++) {
buffer.append("? ");
}
}
if (terms.length > 1) {
buffer.append("(");
for (int j = 0; j < terms.length; j++) {
buffer.append(terms[j].text());
if (j < terms.length-1)
buffer.append(" ");
}
buffer.append(")");
} else {
buffer.append(terms[0].text());
}
lastPos = position;
}
buffer.append("\"");
if (slop != 0) {
buffer.append("~");
buffer.append(slop);
}
return buffer.toString();
}
/** Returns true if <code>o</code> is equal to this. */
@Override
public boolean equals(Object other) {
return sameClassAs(other) &&
equalsTo(getClass().cast(other));
}
private boolean equalsTo(MultiPhraseQuery other) {
return this.slop == other.slop &&
termArraysEquals(this.termArrays, other.termArrays) && /* terms equal implies field equal */
Arrays.equals(this.positions, other.positions);
}
/** Returns a hash code value for this object.*/
@Override
public int hashCode() {
return classHash()
^ slop
^ termArraysHashCode() // terms equal implies field equal
^ Arrays.hashCode(positions);
}
// Breakout calculation of the termArrays hashcode
private int termArraysHashCode() {
int hashCode = 1;
for (final Term[] termArray: termArrays) {
hashCode = 31 * hashCode
+ (termArray == null ? 0 : Arrays.hashCode(termArray));
}
return hashCode;
}
// Breakout calculation of the termArrays equals
private boolean termArraysEquals(Term[][] termArrays1, Term[][] termArrays2) {
if (termArrays1.length != termArrays2.length) {
return false;
}
for (int i = 0 ; i < termArrays1.length ; ++i) {
Term[] termArray1 = termArrays1[i];
Term[] termArray2 = termArrays2[i];
if (!(termArray1 == null ? termArray2 == null : Arrays.equals(termArray1,
termArray2))) {
return false;
}
}
return true;
}
/**
* Takes the logical union of multiple PostingsEnum iterators.
* <p>
* Note: positions are merged during freq()
*/
static class UnionPostingsEnum extends PostingsEnum {
/** queue ordered by docid */
final DocsQueue docsQueue;
/** cost of this enum: sum of its subs */
final long cost;
/** queue ordered by position for current doc */
final PositionsQueue posQueue = new PositionsQueue();
/** current doc posQueue is working */
int posQueueDoc = -2;
/** list of subs (unordered) */
final PostingsEnum[] subs;
UnionPostingsEnum(Collection<PostingsEnum> subs) {
docsQueue = new DocsQueue(subs.size());
long cost = 0;
for (PostingsEnum sub : subs) {
docsQueue.add(sub);
cost += sub.cost();
}
this.cost = cost;
this.subs = subs.toArray(new PostingsEnum[subs.size()]);
}
@Override
public int freq() throws IOException {
int doc = docID();
if (doc != posQueueDoc) {
posQueue.clear();
for (PostingsEnum sub : subs) {
if (sub.docID() == doc) {
int freq = sub.freq();
for (int i = 0; i < freq; i++) {
posQueue.add(sub.nextPosition());
}
}
}
posQueue.sort();
posQueueDoc = doc;
}
return posQueue.size();
}
@Override
public int nextPosition() throws IOException {
return posQueue.next();
}
@Override
public int docID() {
return docsQueue.top().docID();
}
@Override
public int nextDoc() throws IOException {
PostingsEnum top = docsQueue.top();
int doc = top.docID();
do {
top.nextDoc();
top = docsQueue.updateTop();
} while (top.docID() == doc);
return top.docID();
}
@Override
public int advance(int target) throws IOException {
PostingsEnum top = docsQueue.top();
do {
top.advance(target);
top = docsQueue.updateTop();
} while (top.docID() < target);
return top.docID();
}
@Override
public long cost() {
return cost;
}
@Override
public int startOffset() throws IOException {
return -1; // offsets are unsupported
}
@Override
public int endOffset() throws IOException {
return -1; // offsets are unsupported
}
@Override
public BytesRef getPayload() throws IOException {
return null; // payloads are unsupported
}
/**
* disjunction of postings ordered by docid.
*/
static class DocsQueue extends PriorityQueue<PostingsEnum> {
DocsQueue(int size) {
super(size);
}
@Override
public final boolean lessThan(PostingsEnum a, PostingsEnum b) {
return a.docID() < b.docID();
}
}
/**
* queue of terms for a single document. its a sorted array of
* all the positions from all the postings
*/
static class PositionsQueue {
private int arraySize = 16;
private int index = 0;
private int size = 0;
private int[] array = new int[arraySize];
void add(int i) {
if (size == arraySize)
growArray();
array[size++] = i;
}
int next() {
return array[index++];
}
void sort() {
Arrays.sort(array, index, size);
}
void clear() {
index = 0;
size = 0;
}
int size() {
return size;
}
private void growArray() {
int[] newArray = new int[arraySize * 2];
System.arraycopy(array, 0, newArray, 0, arraySize);
array = newArray;
arraySize *= 2;
}
}
}
static class PostingsAndPosition {
final PostingsEnum pe;
int pos;
int upto;
PostingsAndPosition(PostingsEnum pe) {
this.pe = pe;
}
}
// Slower version of UnionPostingsEnum that delegates offsets and positions, for
// use by MatchesIterator
static class UnionFullPostingsEnum extends UnionPostingsEnum {
int freq = -1;
boolean started = false;
final PriorityQueue<PostingsAndPosition> posQueue;
final Collection<PostingsAndPosition> subs;
UnionFullPostingsEnum(List<PostingsEnum> subs) {
super(subs);
this.posQueue = new PriorityQueue<PostingsAndPosition>(subs.size()) {
@Override
protected boolean lessThan(PostingsAndPosition a, PostingsAndPosition b) {
return a.pos < b.pos;
}
};
this.subs = new ArrayList<>();
for (PostingsEnum pe : subs) {
this.subs.add(new PostingsAndPosition(pe));
}
}
@Override
public int freq() throws IOException {
int doc = docID();
if (doc == posQueueDoc) {
return freq;
}
freq = 0;
started = false;
posQueue.clear();
for (PostingsAndPosition pp : subs) {
if (pp.pe.docID() == doc) {
pp.pos = pp.pe.nextPosition();
pp.upto = pp.pe.freq();
posQueue.add(pp);
freq += pp.upto;
}
}
return freq;
}
@Override
public int nextPosition() throws IOException {
if (started == false) {
started = true;
return posQueue.top().pos;
}
if (posQueue.top().upto == 1) {
posQueue.pop();
return posQueue.top().pos;
}
posQueue.top().pos = posQueue.top().pe.nextPosition();
posQueue.top().upto--;
posQueue.updateTop();
return posQueue.top().pos;
}
@Override
public int startOffset() throws IOException {
return posQueue.top().pe.startOffset();
}
@Override
public int endOffset() throws IOException {
return posQueue.top().pe.endOffset();
}
@Override
public BytesRef getPayload() throws IOException {
return posQueue.top().pe.getPayload();
}
}
}
| 1 | 38,034 | This is used in o.a.l.sandbox.search.PhraseWildcardQuery. | apache-lucene-solr | java |
@@ -42,6 +42,7 @@ type stateDB struct {
dao db.KVStore // the underlying DB for account/contract storage
timerFactory *prometheustimer.TimerFactory
workingsets *lru.Cache // lru cache for workingsets
+ protocolView protocol.Dock
}
// StateDBOption sets stateDB construction parameter | 1 | // Copyright (c) 2020 IoTeX Foundation
// 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 factory
import (
"context"
"fmt"
"strconv"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/iotexproject/go-pkgs/hash"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/action/protocol"
"github.com/iotexproject/iotex-core/action/protocol/execution/evm"
"github.com/iotexproject/iotex-core/blockchain/block"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/db"
"github.com/iotexproject/iotex-core/db/batch"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/pkg/prometheustimer"
"github.com/iotexproject/iotex-core/pkg/util/byteutil"
"github.com/iotexproject/iotex-core/state"
)
// stateDB implements StateFactory interface, tracks changes to account/contract and batch-commits to DB
type stateDB struct {
mutex sync.RWMutex
currentChainHeight uint64
cfg config.Config
registry *protocol.Registry
dao db.KVStore // the underlying DB for account/contract storage
timerFactory *prometheustimer.TimerFactory
workingsets *lru.Cache // lru cache for workingsets
}
// StateDBOption sets stateDB construction parameter
type StateDBOption func(*stateDB, config.Config) error
// PrecreatedStateDBOption uses pre-created state db
func PrecreatedStateDBOption(kv db.KVStore) StateDBOption {
return func(sdb *stateDB, cfg config.Config) error {
if kv == nil {
return errors.New("Invalid state db")
}
sdb.dao = kv
return nil
}
}
// DefaultStateDBOption creates default state db from config
func DefaultStateDBOption() StateDBOption {
return func(sdb *stateDB, cfg config.Config) error {
dbPath := cfg.Chain.TrieDBPath
if len(dbPath) == 0 {
return errors.New("Invalid empty trie db path")
}
cfg.DB.DbPath = dbPath // TODO: remove this after moving TrieDBPath from cfg.Chain to cfg.DB
sdb.dao = db.NewBoltDB(cfg.DB)
return nil
}
}
// InMemStateDBOption creates in memory state db
func InMemStateDBOption() StateDBOption {
return func(sdb *stateDB, cfg config.Config) error {
sdb.dao = db.NewMemKVStore()
return nil
}
}
// RegistryStateDBOption sets the registry in state db
func RegistryStateDBOption(reg *protocol.Registry) StateDBOption {
return func(sdb *stateDB, cfg config.Config) error {
sdb.registry = reg
return nil
}
}
// NewStateDB creates a new state db
func NewStateDB(cfg config.Config, opts ...StateDBOption) (Factory, error) {
sdb := stateDB{
cfg: cfg,
currentChainHeight: 0,
registry: protocol.NewRegistry(),
}
for _, opt := range opts {
if err := opt(&sdb, cfg); err != nil {
log.S().Errorf("Failed to execute state factory creation option %p: %v", opt, err)
return nil, err
}
}
timerFactory, err := prometheustimer.New(
"iotex_statefactory_perf",
"Performance of state factory module",
[]string{"topic", "chainID"},
[]string{"default", strconv.FormatUint(uint64(cfg.Chain.ID), 10)},
)
if err != nil {
log.L().Error("Failed to generate prometheus timer factory.", zap.Error(err))
}
sdb.timerFactory = timerFactory
if sdb.workingsets, err = lru.New(int(cfg.Chain.WorkingSetCacheSize)); err != nil {
return nil, errors.Wrap(err, "failed to generate lru cache for workingsets")
}
return &sdb, nil
}
func (sdb *stateDB) Start(ctx context.Context) error {
ctx = protocol.WithRegistry(ctx, sdb.registry)
if err := sdb.dao.Start(ctx); err != nil {
return err
}
// check factory height
h, err := sdb.dao.Get(AccountKVNamespace, []byte(CurrentHeightKey))
switch errors.Cause(err) {
case nil:
sdb.currentChainHeight = byteutil.BytesToUint64(h)
if err := sdb.registry.StartAll(ctx); err != nil {
return err
}
case db.ErrNotExist:
if err = sdb.dao.Put(AccountKVNamespace, []byte(CurrentHeightKey), byteutil.Uint64ToBytes(0)); err != nil {
return errors.Wrap(err, "failed to init statedb's height")
}
if err := sdb.registry.StartAll(ctx); err != nil {
return err
}
ctx = protocol.WithBlockCtx(
ctx,
protocol.BlockCtx{
BlockHeight: 0,
BlockTimeStamp: time.Unix(sdb.cfg.Genesis.Timestamp, 0),
Producer: sdb.cfg.ProducerAddress(),
GasLimit: sdb.cfg.Genesis.BlockGasLimit,
})
// init the state factory
if err = sdb.createGenesisStates(ctx); err != nil {
return errors.Wrap(err, "failed to create genesis states")
}
default:
return err
}
return nil
}
func (sdb *stateDB) Stop(ctx context.Context) error {
sdb.mutex.Lock()
defer sdb.mutex.Unlock()
sdb.workingsets.Purge()
return sdb.dao.Stop(ctx)
}
// Height returns factory's height
func (sdb *stateDB) Height() (uint64, error) {
sdb.mutex.RLock()
defer sdb.mutex.RUnlock()
height, err := sdb.dao.Get(AccountKVNamespace, []byte(CurrentHeightKey))
if err != nil {
return 0, errors.Wrap(err, "failed to get factory's height from underlying DB")
}
return byteutil.BytesToUint64(height), nil
}
func (sdb *stateDB) newWorkingSet(ctx context.Context, height uint64) (*workingSet, error) {
flusher, err := db.NewKVStoreFlusher(sdb.dao, batch.NewCachedBatch(), sdb.flusherOptions(ctx, height)...)
if err != nil {
return nil, err
}
return &workingSet{
height: height,
finalized: false,
dock: protocol.NewDock(),
getStateFunc: func(ns string, key []byte, s interface{}) error {
data, err := flusher.KVStoreWithBuffer().Get(ns, key)
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
return errors.Wrapf(state.ErrStateNotExist, "failed to get state of ns = %x and key = %x", ns, key)
}
return err
}
return state.Deserialize(s, data)
},
putStateFunc: func(ns string, key []byte, s interface{}) error {
ss, err := state.Serialize(s)
if err != nil {
return errors.Wrapf(err, "failed to convert account %v to bytes", s)
}
flusher.KVStoreWithBuffer().MustPut(ns, key, ss)
return nil
},
delStateFunc: func(ns string, key []byte) error {
flusher.KVStoreWithBuffer().MustDelete(ns, key)
return nil
},
statesFunc: func(opts ...protocol.StateOption) (uint64, state.Iterator, error) {
return sdb.States(opts...)
},
digestFunc: func() hash.Hash256 {
return hash.Hash256b(flusher.SerializeQueue())
},
finalizeFunc: func(h uint64) error {
// Persist current chain Height
flusher.KVStoreWithBuffer().MustPut(
AccountKVNamespace,
[]byte(CurrentHeightKey),
byteutil.Uint64ToBytes(height),
)
return nil
},
commitFunc: func(h uint64) error {
if err := flusher.Flush(); err != nil {
return err
}
sdb.currentChainHeight = h
return nil
},
snapshotFunc: flusher.KVStoreWithBuffer().Snapshot,
revertFunc: flusher.KVStoreWithBuffer().Revert,
dbFunc: func() db.KVStore {
return flusher.KVStoreWithBuffer()
},
}, nil
}
func (sdb *stateDB) Register(p protocol.Protocol) error {
return p.Register(sdb.registry)
}
func (sdb *stateDB) Validate(ctx context.Context, blk *block.Block) error {
ctx = protocol.WithRegistry(ctx, sdb.registry)
key := generateWorkingSetCacheKey(blk.Header, blk.Header.ProducerAddress())
ws, isExist, err := sdb.getFromWorkingSets(ctx, key)
if err != nil {
return err
}
if isExist {
return nil
}
if err = ws.ValidateBlock(ctx, blk); err != nil {
return errors.Wrap(err, "failed to validate block with workingset in statedb")
}
sdb.putIntoWorkingSets(key, ws)
return nil
}
// NewBlockBuilder returns block builder which hasn't been signed yet
func (sdb *stateDB) NewBlockBuilder(
ctx context.Context,
actionMap map[string][]action.SealedEnvelope,
sign func(action.Envelope) (action.SealedEnvelope, error),
) (*block.Builder, error) {
sdb.mutex.Lock()
ctx = protocol.WithRegistry(ctx, sdb.registry)
ws, err := sdb.newWorkingSet(ctx, sdb.currentChainHeight+1)
sdb.mutex.Unlock()
if err != nil {
return nil, err
}
postSystemActions := make([]action.SealedEnvelope, 0)
for _, p := range sdb.registry.All() {
if psac, ok := p.(protocol.PostSystemActionsCreator); ok {
elps, err := psac.CreatePostSystemActions(ctx, ws)
if err != nil {
return nil, err
}
for _, elp := range elps {
se, err := sign(elp)
if err != nil {
return nil, err
}
postSystemActions = append(postSystemActions, se)
}
}
}
blkBuilder, err := ws.CreateBuilder(ctx, actionMap, postSystemActions, sdb.cfg.Chain.AllowedBlockGasResidue)
if err != nil {
return nil, err
}
blkCtx := protocol.MustGetBlockCtx(ctx)
key := generateWorkingSetCacheKey(blkBuilder.GetCurrentBlockHeader(), blkCtx.Producer.String())
sdb.putIntoWorkingSets(key, ws)
return blkBuilder, nil
}
// SimulateExecution simulates a running of smart contract operation, this is done off the network since it does not
// cause any state change
func (sdb *stateDB) SimulateExecution(
ctx context.Context,
caller address.Address,
ex *action.Execution,
getBlockHash evm.GetBlockHash,
) ([]byte, *action.Receipt, error) {
sdb.mutex.Lock()
ws, err := sdb.newWorkingSet(ctx, sdb.currentChainHeight+1)
sdb.mutex.Unlock()
if err != nil {
return nil, nil, err
}
return evm.SimulateExecution(ctx, ws, caller, ex, getBlockHash)
}
// PutBlock persists all changes in RunActions() into the DB
func (sdb *stateDB) PutBlock(ctx context.Context, blk *block.Block) error {
sdb.mutex.Lock()
timer := sdb.timerFactory.NewTimer("Commit")
sdb.mutex.Unlock()
defer timer.End()
producer, err := address.FromBytes(blk.PublicKey().Hash())
if err != nil {
return err
}
bcCtx := protocol.MustGetBlockchainCtx(ctx)
ctx = protocol.WithBlockCtx(
protocol.WithRegistry(ctx, sdb.registry),
protocol.BlockCtx{
BlockHeight: blk.Height(),
BlockTimeStamp: blk.Timestamp(),
GasLimit: bcCtx.Genesis.BlockGasLimit,
Producer: producer,
},
)
key := generateWorkingSetCacheKey(blk.Header, blk.Header.ProducerAddress())
ws, isExist, err := sdb.getFromWorkingSets(ctx, key)
if err != nil {
return err
}
if !isExist {
_, err = ws.Process(ctx, blk.RunnableActions().Actions())
if err != nil {
log.L().Panic("Failed to update state.", zap.Error(err))
return err
}
}
sdb.mutex.Lock()
defer sdb.mutex.Unlock()
h, _ := ws.Height()
if sdb.currentChainHeight+1 != h {
// another working set with correct version already committed, do nothing
return fmt.Errorf(
"current state height %d + 1 doesn't match working set height %d",
sdb.currentChainHeight, h,
)
}
return ws.Commit(ctx)
}
func (sdb *stateDB) DeleteTipBlock(_ *block.Block) error {
return errors.Wrap(ErrNotSupported, "cannot delete tip block from state db")
}
// State returns a confirmed state in the state factory
func (sdb *stateDB) State(s interface{}, opts ...protocol.StateOption) (uint64, error) {
sdb.mutex.Lock()
defer sdb.mutex.Unlock()
cfg, err := processOptions(opts...)
if err != nil {
return 0, err
}
return sdb.currentChainHeight, sdb.state(cfg.Namespace, cfg.Key, s)
}
// State returns a set of states in the state factory
func (sdb *stateDB) States(opts ...protocol.StateOption) (uint64, state.Iterator, error) {
sdb.mutex.RLock()
defer sdb.mutex.RUnlock()
cfg, err := processOptions(opts...)
if err != nil {
return 0, nil, err
}
if cfg.Key != nil {
return sdb.currentChainHeight, nil, errors.Wrap(ErrNotSupported, "Read states with key option has not been implemented yet")
}
if cfg.Cond == nil {
cfg.Cond = func(k, v []byte) bool {
return true
}
}
_, values, err := sdb.dao.Filter(cfg.Namespace, cfg.Cond, cfg.MinKey, cfg.MaxKey)
if err != nil {
if errors.Cause(err) == db.ErrNotExist || errors.Cause(err) == db.ErrBucketNotExist {
return sdb.currentChainHeight, nil, errors.Wrapf(state.ErrStateNotExist, "failed to get states of ns = %x", cfg.Namespace)
}
return sdb.currentChainHeight, nil, err
}
return sdb.currentChainHeight, state.NewIterator(values), nil
}
// StateAtHeight returns a confirmed state at height -- archive mode
func (sdb *stateDB) StateAtHeight(height uint64, s interface{}, opts ...protocol.StateOption) error {
return ErrNotSupported
}
// StatesAtHeight returns a set states in the state factory at height -- archive mode
func (sdb *stateDB) StatesAtHeight(height uint64, opts ...protocol.StateOption) (state.Iterator, error) {
return nil, errors.Wrap(ErrNotSupported, "state db does not support archive mode")
}
//======================================
// private trie constructor functions
//======================================
func (sdb *stateDB) flusherOptions(ctx context.Context, height uint64) []db.KVStoreFlusherOption {
bcCtx := protocol.MustGetBlockchainCtx(ctx)
hu := config.NewHeightUpgrade(&bcCtx.Genesis)
preEaster := hu.IsPre(config.Easter, height)
opts := []db.KVStoreFlusherOption{
db.SerializeOption(func(wi *batch.WriteInfo) []byte {
if preEaster {
return wi.SerializeWithoutWriteType()
}
return wi.Serialize()
}),
}
if !preEaster {
return opts
}
return append(
opts,
db.SerializeFilterOption(func(wi *batch.WriteInfo) bool {
return wi.Namespace() == evm.CodeKVNameSpace
}),
)
}
func (sdb *stateDB) state(ns string, addr []byte, s interface{}) error {
data, err := sdb.dao.Get(ns, addr)
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
return errors.Wrapf(state.ErrStateNotExist, "state of %x doesn't exist", addr)
}
return errors.Wrapf(err, "error when getting the state of %x", addr)
}
if err := state.Deserialize(s, data); err != nil {
return errors.Wrapf(err, "error when deserializing state data into %T", s)
}
return nil
}
func (sdb *stateDB) createGenesisStates(ctx context.Context) error {
ws, err := sdb.newWorkingSet(ctx, 0)
if err != nil {
return err
}
if err := ws.CreateGenesisStates(ctx); err != nil {
return err
}
return ws.Commit(ctx)
}
// getFromWorkingSets returns (workingset, true) if it exists in a cache, otherwise generates new workingset and return (ws, false)
func (sdb *stateDB) getFromWorkingSets(ctx context.Context, key hash.Hash256) (*workingSet, bool, error) {
sdb.mutex.RLock()
defer sdb.mutex.RUnlock()
if data, ok := sdb.workingsets.Get(key); ok {
if ws, ok := data.(*workingSet); ok {
// if it is already validated, return workingset
return ws, true, nil
}
return nil, false, errors.New("type assertion failed to be WorkingSet")
}
tx, err := sdb.newWorkingSet(ctx, sdb.currentChainHeight+1)
return tx, false, err
}
func (sdb *stateDB) putIntoWorkingSets(key hash.Hash256, ws *workingSet) {
sdb.mutex.Lock()
defer sdb.mutex.Unlock()
sdb.workingsets.Add(key, ws)
return
}
| 1 | 21,515 | view should be loaded on start for both statedb and factory | iotexproject-iotex-core | go |
@@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Http
private ConnectionFilterContext _filterContext;
private LibuvStream _libuvStream;
private FilteredStreamAdapter _filteredStreamAdapter;
- private Task _readInputContinuation;
+ private Task _readInputTask;
private readonly SocketInput _rawSocketInput;
private readonly SocketOutput _rawSocketOutput; | 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.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Filter;
using Microsoft.AspNetCore.Server.Kestrel.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Networking;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.Kestrel.Http
{
public class Connection : ConnectionContext, IConnectionControl
{
// Base32 encoding - in ascii sort order for easy text based sorting
private static readonly string _encode32Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
private static readonly Action<UvStreamHandle, int, object> _readCallback =
(handle, status, state) => ReadCallback(handle, status, state);
private static readonly Func<UvStreamHandle, int, object, Libuv.uv_buf_t> _allocCallback =
(handle, suggestedsize, state) => AllocCallback(handle, suggestedsize, state);
// Seed the _lastConnectionId for this application instance with
// the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001
// for a roughly increasing _requestId over restarts
private static long _lastConnectionId = DateTime.UtcNow.Ticks;
private readonly UvStreamHandle _socket;
private Frame _frame;
private ConnectionFilterContext _filterContext;
private LibuvStream _libuvStream;
private FilteredStreamAdapter _filteredStreamAdapter;
private Task _readInputContinuation;
private readonly SocketInput _rawSocketInput;
private readonly SocketOutput _rawSocketOutput;
private readonly object _stateLock = new object();
private ConnectionState _connectionState;
private TaskCompletionSource<object> _socketClosedTcs;
public Connection(ListenerContext context, UvStreamHandle socket) : base(context)
{
_socket = socket;
socket.Connection = this;
ConnectionControl = this;
ConnectionId = GenerateConnectionId(Interlocked.Increment(ref _lastConnectionId));
_rawSocketInput = new SocketInput(Memory, ThreadPool);
_rawSocketOutput = new SocketOutput(Thread, _socket, Memory, this, ConnectionId, Log, ThreadPool, WriteReqPool);
}
// Internal for testing
internal Connection()
{
}
public void Start()
{
Log.ConnectionStart(ConnectionId);
// Start socket prior to applying the ConnectionFilter
_socket.ReadStart(_allocCallback, _readCallback, this);
var tcpHandle = _socket as UvTcpHandle;
if (tcpHandle != null)
{
RemoteEndPoint = tcpHandle.GetPeerIPEndPoint();
LocalEndPoint = tcpHandle.GetSockIPEndPoint();
}
// Don't initialize _frame until SocketInput and SocketOutput are set to their final values.
if (ServerOptions.ConnectionFilter == null)
{
lock (_stateLock)
{
if (_connectionState != ConnectionState.CreatingFrame)
{
throw new InvalidOperationException("Invalid connection state: " + _connectionState);
}
_connectionState = ConnectionState.Open;
SocketInput = _rawSocketInput;
SocketOutput = _rawSocketOutput;
_frame = CreateFrame();
_frame.Start();
}
}
else
{
_libuvStream = new LibuvStream(_rawSocketInput, _rawSocketOutput);
_filterContext = new ConnectionFilterContext
{
Connection = _libuvStream,
Address = ServerAddress
};
try
{
ServerOptions.ConnectionFilter.OnConnectionAsync(_filterContext).ContinueWith((task, state) =>
{
var connection = (Connection)state;
if (task.IsFaulted)
{
connection.Log.LogError(0, task.Exception, "ConnectionFilter.OnConnection");
connection.ConnectionControl.End(ProduceEndType.SocketDisconnect);
}
else if (task.IsCanceled)
{
connection.Log.LogError("ConnectionFilter.OnConnection Canceled");
connection.ConnectionControl.End(ProduceEndType.SocketDisconnect);
}
else
{
connection.ApplyConnectionFilter();
}
}, this);
}
catch (Exception ex)
{
Log.LogError(0, ex, "ConnectionFilter.OnConnection");
ConnectionControl.End(ProduceEndType.SocketDisconnect);
}
}
}
public Task StopAsync()
{
lock (_stateLock)
{
switch (_connectionState)
{
case ConnectionState.SocketClosed:
return TaskUtilities.CompletedTask;
case ConnectionState.CreatingFrame:
_connectionState = ConnectionState.ToDisconnect;
break;
case ConnectionState.Open:
_frame.Stop();
SocketInput.CompleteAwaiting();
break;
}
_socketClosedTcs = new TaskCompletionSource<object>();
return _socketClosedTcs.Task;
}
}
public virtual void Abort()
{
// Frame.Abort calls user code while this method is always
// called from a libuv thread.
ThreadPool.Run(() =>
{
var connection = this;
lock (connection._stateLock)
{
if (connection._connectionState == ConnectionState.CreatingFrame)
{
connection._connectionState = ConnectionState.ToDisconnect;
}
else
{
connection._frame?.Abort();
}
}
});
}
// Called on Libuv thread
public virtual void OnSocketClosed()
{
if (_filteredStreamAdapter != null)
{
_filteredStreamAdapter.Abort();
_rawSocketInput.IncomingFin();
_readInputContinuation.ContinueWith((task, state) =>
{
((Connection)state)._filterContext.Connection.Dispose();
((Connection)state)._filteredStreamAdapter.Dispose();
((Connection)state)._rawSocketInput.Dispose();
}, this);
}
else
{
_rawSocketInput.Dispose();
}
lock (_stateLock)
{
_connectionState = ConnectionState.SocketClosed;
if (_socketClosedTcs != null)
{
// This is always waited on synchronously, so it's safe to
// call on the libuv thread.
_socketClosedTcs.TrySetResult(null);
}
}
}
private void ApplyConnectionFilter()
{
lock (_stateLock)
{
if (_connectionState == ConnectionState.CreatingFrame)
{
_connectionState = ConnectionState.Open;
if (_filterContext.Connection != _libuvStream)
{
_filteredStreamAdapter = new FilteredStreamAdapter(ConnectionId, _filterContext.Connection, Memory, Log, ThreadPool);
SocketInput = _filteredStreamAdapter.SocketInput;
SocketOutput = _filteredStreamAdapter.SocketOutput;
_readInputContinuation = _filteredStreamAdapter.ReadInputAsync();
}
else
{
SocketInput = _rawSocketInput;
SocketOutput = _rawSocketOutput;
}
PrepareRequest = _filterContext.PrepareRequest;
_frame = CreateFrame();
_frame.Start();
}
else
{
ConnectionControl.End(ProduceEndType.SocketDisconnect);
}
}
}
private static Libuv.uv_buf_t AllocCallback(UvStreamHandle handle, int suggestedSize, object state)
{
return ((Connection)state).OnAlloc(handle, suggestedSize);
}
private Libuv.uv_buf_t OnAlloc(UvStreamHandle handle, int suggestedSize)
{
var result = _rawSocketInput.IncomingStart();
return handle.Libuv.buf_init(
result.Pin() + result.End,
result.Data.Offset + result.Data.Count - result.End);
}
private static void ReadCallback(UvStreamHandle handle, int status, object state)
{
((Connection)state).OnRead(handle, status);
}
private void OnRead(UvStreamHandle handle, int status)
{
if (status == 0)
{
// A zero status does not indicate an error or connection end. It indicates
// there is no data to be read right now.
// See the note at http://docs.libuv.org/en/v1.x/stream.html#c.uv_read_cb.
// We need to clean up whatever was allocated by OnAlloc.
_rawSocketInput.IncomingDeferred();
return;
}
var normalRead = status > 0;
var normalDone = status == Constants.ECONNRESET || status == Constants.EOF;
var errorDone = !(normalDone || normalRead);
var readCount = normalRead ? status : 0;
if (normalRead)
{
Log.ConnectionRead(ConnectionId, readCount);
}
else
{
_socket.ReadStop();
Log.ConnectionReadFin(ConnectionId);
}
Exception error = null;
if (errorDone)
{
handle.Libuv.Check(status, out error);
}
_rawSocketInput.IncomingComplete(readCount, error);
if (errorDone)
{
Abort();
}
}
private Frame CreateFrame()
{
return FrameFactory(this);
}
void IConnectionControl.Pause()
{
Log.ConnectionPause(ConnectionId);
_socket.ReadStop();
}
void IConnectionControl.Resume()
{
Log.ConnectionResume(ConnectionId);
_socket.ReadStart(_allocCallback, _readCallback, this);
}
void IConnectionControl.End(ProduceEndType endType)
{
lock (_stateLock)
{
switch (endType)
{
case ProduceEndType.ConnectionKeepAlive:
if (_connectionState != ConnectionState.Open)
{
return;
}
Log.ConnectionKeepAlive(ConnectionId);
break;
case ProduceEndType.SocketShutdown:
case ProduceEndType.SocketDisconnect:
if (_connectionState == ConnectionState.Disconnecting ||
_connectionState == ConnectionState.SocketClosed)
{
return;
}
_connectionState = ConnectionState.Disconnecting;
Log.ConnectionDisconnect(ConnectionId);
_rawSocketOutput.End(endType);
break;
}
}
}
private static unsafe string GenerateConnectionId(long id)
{
// The following routine is ~310% faster than calling long.ToString() on x64
// and ~600% faster than calling long.ToString() on x86 in tight loops of 1 million+ iterations
// See: https://github.com/aspnet/Hosting/pull/385
// stackalloc to allocate array on stack rather than heap
char* charBuffer = stackalloc char[13];
charBuffer[0] = _encode32Chars[(int)(id >> 60) & 31];
charBuffer[1] = _encode32Chars[(int)(id >> 55) & 31];
charBuffer[2] = _encode32Chars[(int)(id >> 50) & 31];
charBuffer[3] = _encode32Chars[(int)(id >> 45) & 31];
charBuffer[4] = _encode32Chars[(int)(id >> 40) & 31];
charBuffer[5] = _encode32Chars[(int)(id >> 35) & 31];
charBuffer[6] = _encode32Chars[(int)(id >> 30) & 31];
charBuffer[7] = _encode32Chars[(int)(id >> 25) & 31];
charBuffer[8] = _encode32Chars[(int)(id >> 20) & 31];
charBuffer[9] = _encode32Chars[(int)(id >> 15) & 31];
charBuffer[10] = _encode32Chars[(int)(id >> 10) & 31];
charBuffer[11] = _encode32Chars[(int)(id >> 5) & 31];
charBuffer[12] = _encode32Chars[(int)id & 31];
// string ctor overload that takes char*
return new string(charBuffer, 0, 13);
}
private enum ConnectionState
{
CreatingFrame,
ToDisconnect,
Open,
Disconnecting,
SocketClosed
}
}
}
| 1 | 8,623 | Why rename? Just curious... | aspnet-KestrelHttpServer | .cs |
@@ -309,12 +309,14 @@ public class VideoplayerActivity extends MediaplayerActivity {
public void onStartTrackingTouch(SeekBar seekBar) {
super.onStartTrackingTouch(seekBar);
videoControlsHider.stop();
+ controls.setVisibility(View.GONE);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
super.onStopTrackingTouch(seekBar);
setupVideoControlsToggler();
+ controls.setVisibility(View.VISIBLE);
}
@Override | 1 | package de.danoeh.antennapod.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.view.WindowCompat;
import androidx.appcompat.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicBoolean;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.feed.MediaType;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.playback.PlaybackService;
import de.danoeh.antennapod.core.service.playback.PlayerStatus;
import de.danoeh.antennapod.core.util.gui.PictureInPictureUtil;
import de.danoeh.antennapod.core.util.playback.Playable;
import de.danoeh.antennapod.view.AspectRatioVideoView;
/**
* Activity for playing video files.
*/
public class VideoplayerActivity extends MediaplayerActivity {
private static final String TAG = "VideoplayerActivity";
/**
* True if video controls are currently visible.
*/
private boolean videoControlsShowing = true;
private boolean videoSurfaceCreated = false;
private boolean destroyingDueToReload = false;
private VideoControlsHider videoControlsHider = new VideoControlsHider(this);
private final AtomicBoolean isSetup = new AtomicBoolean(false);
private LinearLayout controls;
private LinearLayout videoOverlay;
private AspectRatioVideoView videoview;
private ProgressBar progressIndicator;
private FrameLayout videoframe;
@Override
protected void chooseTheme() {
setTheme(R.style.Theme_AntennaPod_VideoPlayer);
}
@SuppressLint("AppCompatMethod")
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY); // has to be called before setting layout content
super.onCreate(savedInstanceState);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0x80000000));
}
@Override
protected void onResume() {
super.onResume();
if (TextUtils.equals(getIntent().getAction(), Intent.ACTION_VIEW)) {
playExternalMedia(getIntent(), MediaType.VIDEO);
} else if (PlaybackService.isCasting()) {
Intent intent = PlaybackService.getPlayerActivityIntent(this);
if (!intent.getComponent().getClassName().equals(VideoplayerActivity.class.getName())) {
destroyingDueToReload = true;
finish();
startActivity(intent);
}
}
}
@Override
protected void onStop() {
super.onStop();
if (!PictureInPictureUtil.isInPictureInPictureMode(this)) {
videoControlsHider.stop();
}
}
@Override
public void onUserLeaveHint() {
if (!PictureInPictureUtil.isInPictureInPictureMode(this) && UserPreferences.getVideoBackgroundBehavior()
== UserPreferences.VideoBackgroundBehavior.PICTURE_IN_PICTURE) {
compatEnterPictureInPicture();
}
}
@Override
protected void onPause() {
if (!PictureInPictureUtil.isInPictureInPictureMode(this)) {
if (controller != null && controller.getStatus() == PlayerStatus.PLAYING) {
controller.pause();
}
}
super.onPause();
}
@Override
protected void onDestroy() {
videoControlsHider.stop();
videoControlsHider = null;
super.onDestroy();
}
@Override
protected boolean loadMediaInfo() {
if (!super.loadMediaInfo() || controller == null) {
return false;
}
Playable media = controller.getMedia();
if (media != null) {
getSupportActionBar().setSubtitle(media.getEpisodeTitle());
getSupportActionBar().setTitle(media.getFeedTitle());
return true;
}
return false;
}
@Override
protected void setupGUI() {
if (isSetup.getAndSet(true)) {
return;
}
super.setupGUI();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
controls = findViewById(R.id.controls);
videoOverlay = findViewById(R.id.overlay);
videoview = findViewById(R.id.videoview);
videoframe = findViewById(R.id.videoframe);
progressIndicator = findViewById(R.id.progressIndicator);
videoview.getHolder().addCallback(surfaceHolderCallback);
videoframe.setOnTouchListener(onVideoviewTouched);
videoOverlay.setOnTouchListener((view, motionEvent) -> true); // To suppress touches directly below the slider
videoview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
videoOverlay.setFitsSystemWindows(true);
setupVideoControlsToggler();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
videoframe.getViewTreeObserver().addOnGlobalLayoutListener(() ->
videoview.setAvailableSize(videoframe.getWidth(), videoframe.getHeight()));
}
@Override
protected void onAwaitingVideoSurface() {
setupVideoAspectRatio();
if (videoSurfaceCreated && controller != null) {
Log.d(TAG, "Videosurface already created, setting videosurface now");
controller.setVideoSurface(videoview.getHolder());
}
}
@Override
protected void postStatusMsg(int resId, boolean showToast) {
if (resId == R.string.player_preparing_msg) {
progressIndicator.setVisibility(View.VISIBLE);
} else {
progressIndicator.setVisibility(View.INVISIBLE);
}
}
@Override
protected void clearStatusMsg() {
progressIndicator.setVisibility(View.INVISIBLE);
}
private final View.OnTouchListener onVideoviewTouched = (v, event) -> {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (PictureInPictureUtil.isInPictureInPictureMode(this)) {
return true;
}
videoControlsHider.stop();
toggleVideoControlsVisibility();
if (videoControlsShowing) {
setupVideoControlsToggler();
}
return true;
} else {
return false;
}
};
@SuppressLint("NewApi")
private void setupVideoControlsToggler() {
videoControlsHider.stop();
videoControlsHider.start();
}
private void setupVideoAspectRatio() {
if (videoSurfaceCreated && controller != null) {
Pair<Integer, Integer> videoSize = controller.getVideoSize();
if (videoSize != null && videoSize.first > 0 && videoSize.second > 0) {
Log.d(TAG, "Width,height of video: " + videoSize.first + ", " + videoSize.second);
videoview.setVideoSize(videoSize.first, videoSize.second);
} else {
Log.e(TAG, "Could not determine video size");
}
}
}
private void toggleVideoControlsVisibility() {
if (videoControlsShowing) {
getSupportActionBar().hide();
hideVideoControls();
} else {
getSupportActionBar().show();
showVideoControls();
}
videoControlsShowing = !videoControlsShowing;
}
@Override
protected void onRewind() {
super.onRewind();
setupVideoControlsToggler();
}
@Override
protected void onPlayPause() {
super.onPlayPause();
setupVideoControlsToggler();
}
@Override
protected void onFastForward() {
super.onFastForward();
setupVideoControlsToggler();
}
private final SurfaceHolder.Callback surfaceHolderCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
holder.setFixedSize(width, height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "Videoview holder created");
videoSurfaceCreated = true;
if (controller != null && controller.getStatus() == PlayerStatus.PLAYING) {
if (controller.serviceAvailable()) {
controller.setVideoSurface(holder);
} else {
Log.e(TAG, "Couldn't attach surface to mediaplayer - reference to service was null");
}
}
setupVideoAspectRatio();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "Videosurface was destroyed");
videoSurfaceCreated = false;
if (controller != null && !destroyingDueToReload
&& UserPreferences.getVideoBackgroundBehavior()
!= UserPreferences.VideoBackgroundBehavior.CONTINUE_PLAYING) {
controller.notifyVideoSurfaceAbandoned();
}
}
};
@Override
protected void onReloadNotification(int notificationCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && PictureInPictureUtil.isInPictureInPictureMode(this)) {
if (notificationCode == PlaybackService.EXTRA_CODE_AUDIO
|| notificationCode == PlaybackService.EXTRA_CODE_CAST) {
finish();
}
return;
}
if (notificationCode == PlaybackService.EXTRA_CODE_AUDIO) {
Log.d(TAG, "ReloadNotification received, switching to Audioplayer now");
destroyingDueToReload = true;
finish();
startActivity(new Intent(this, AudioplayerActivity.class));
} else if (notificationCode == PlaybackService.EXTRA_CODE_CAST) {
Log.d(TAG, "ReloadNotification received, switching to Castplayer now");
destroyingDueToReload = true;
finish();
startActivity(new Intent(this, CastplayerActivity.class));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
super.onStartTrackingTouch(seekBar);
videoControlsHider.stop();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
super.onStopTrackingTouch(seekBar);
setupVideoControlsToggler();
}
@Override
protected void onBufferStart() {
progressIndicator.setVisibility(View.VISIBLE);
}
@Override
protected void onBufferEnd() {
progressIndicator.setVisibility(View.INVISIBLE);
}
@SuppressLint("NewApi")
private void showVideoControls() {
videoOverlay.setVisibility(View.VISIBLE);
controls.setVisibility(View.VISIBLE);
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
if (animation != null) {
videoOverlay.startAnimation(animation);
controls.startAnimation(animation);
}
videoview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
@SuppressLint("NewApi")
private void hideVideoControls(boolean showAnimation) {
if (showAnimation) {
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
if (animation != null) {
videoOverlay.startAnimation(animation);
controls.startAnimation(animation);
}
}
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
videoOverlay.setFitsSystemWindows(true);
videoOverlay.setVisibility(View.GONE);
controls.setVisibility(View.GONE);
}
private void hideVideoControls() {
hideVideoControls(true);
}
@Override
protected int getContentViewResourceId() {
return R.layout.videoplayer_activity;
}
@Override
protected void setScreenOn(boolean enable) {
super.setScreenOn(enable);
if (enable) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (PictureInPictureUtil.supportsPictureInPicture(this)) {
menu.findItem(R.id.player_go_to_picture_in_picture).setVisible(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.player_go_to_picture_in_picture) {
compatEnterPictureInPicture();
return true;
}
return super.onOptionsItemSelected(item);
}
private void compatEnterPictureInPicture() {
if (PictureInPictureUtil.supportsPictureInPicture(this) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
getSupportActionBar().hide();
hideVideoControls(false);
enterPictureInPictureMode();
}
}
private static class VideoControlsHider extends Handler {
private static final int DELAY = 2500;
private WeakReference<VideoplayerActivity> activity;
VideoControlsHider(VideoplayerActivity activity) {
this.activity = new WeakReference<>(activity);
}
private final Runnable hideVideoControls = () -> {
VideoplayerActivity vpa = activity != null ? activity.get() : null;
if (vpa == null) {
return;
}
if (vpa.videoControlsShowing) {
Log.d(TAG, "Hiding video controls");
ActionBar actionBar = vpa.getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
vpa.hideVideoControls();
vpa.videoControlsShowing = false;
}
};
public void start() {
this.postDelayed(hideVideoControls, DELAY);
}
void stop() {
this.removeCallbacks(hideVideoControls);
}
}
}
| 1 | 15,883 | Is this needed? I think it calls the super function that already does that. | AntennaPod-AntennaPod | java |
@@ -538,7 +538,9 @@ class BBoxHead(BaseModule):
labels = labels.view(1, 1, -1).expand_as(scores)
labels = labels.reshape(batch_size, -1)
scores = scores.reshape(batch_size, -1)
- bboxes = bboxes.reshape(batch_size, -1, 4)
+ if self.reg_class_agnostic:
+ bboxes = bboxes.reshape(batch_size, -1, 4)
+ bboxes = bboxes.repeat(1, self.num_classes, 1)
max_size = torch.max(img_shape)
# Offset bboxes of each class so that bboxes of different labels | 1 | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.runner import BaseModule, auto_fp16, force_fp32
from torch.nn.modules.utils import _pair
from mmdet.core import build_bbox_coder, multi_apply, multiclass_nms
from mmdet.models.builder import HEADS, build_loss
from mmdet.models.losses import accuracy
from mmdet.models.utils import build_linear_layer
@HEADS.register_module()
class BBoxHead(BaseModule):
"""Simplest RoI head, with only two fc layers for classification and
regression respectively."""
def __init__(self,
with_avg_pool=False,
with_cls=True,
with_reg=True,
roi_feat_size=7,
in_channels=256,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
clip_border=True,
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2]),
reg_class_agnostic=False,
reg_decoded_bbox=False,
reg_predictor_cfg=dict(type='Linear'),
cls_predictor_cfg=dict(type='Linear'),
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(
type='SmoothL1Loss', beta=1.0, loss_weight=1.0),
init_cfg=None):
super(BBoxHead, self).__init__(init_cfg)
assert with_cls or with_reg
self.with_avg_pool = with_avg_pool
self.with_cls = with_cls
self.with_reg = with_reg
self.roi_feat_size = _pair(roi_feat_size)
self.roi_feat_area = self.roi_feat_size[0] * self.roi_feat_size[1]
self.in_channels = in_channels
self.num_classes = num_classes
self.reg_class_agnostic = reg_class_agnostic
self.reg_decoded_bbox = reg_decoded_bbox
self.reg_predictor_cfg = reg_predictor_cfg
self.cls_predictor_cfg = cls_predictor_cfg
self.fp16_enabled = False
self.bbox_coder = build_bbox_coder(bbox_coder)
self.loss_cls = build_loss(loss_cls)
self.loss_bbox = build_loss(loss_bbox)
in_channels = self.in_channels
if self.with_avg_pool:
self.avg_pool = nn.AvgPool2d(self.roi_feat_size)
else:
in_channels *= self.roi_feat_area
if self.with_cls:
# need to add background class
if self.custom_cls_channels:
cls_channels = self.loss_cls.get_cls_channels(self.num_classes)
else:
cls_channels = num_classes + 1
self.fc_cls = build_linear_layer(
self.cls_predictor_cfg,
in_features=in_channels,
out_features=cls_channels)
if self.with_reg:
out_dim_reg = 4 if reg_class_agnostic else 4 * num_classes
self.fc_reg = build_linear_layer(
self.reg_predictor_cfg,
in_features=in_channels,
out_features=out_dim_reg)
self.debug_imgs = None
if init_cfg is None:
self.init_cfg = []
if self.with_cls:
self.init_cfg += [
dict(
type='Normal', std=0.01, override=dict(name='fc_cls'))
]
if self.with_reg:
self.init_cfg += [
dict(
type='Normal', std=0.001, override=dict(name='fc_reg'))
]
@property
def custom_cls_channels(self):
return getattr(self.loss_cls, 'custom_cls_channels', False)
@property
def custom_activation(self):
return getattr(self.loss_cls, 'custom_activation', False)
@property
def custom_accuracy(self):
return getattr(self.loss_cls, 'custom_accuracy', False)
@auto_fp16()
def forward(self, x):
if self.with_avg_pool:
x = self.avg_pool(x)
x = x.view(x.size(0), -1)
cls_score = self.fc_cls(x) if self.with_cls else None
bbox_pred = self.fc_reg(x) if self.with_reg else None
return cls_score, bbox_pred
def _get_target_single(self, pos_bboxes, neg_bboxes, pos_gt_bboxes,
pos_gt_labels, cfg):
"""Calculate the ground truth for proposals in the single image
according to the sampling results.
Args:
pos_bboxes (Tensor): Contains all the positive boxes,
has shape (num_pos, 4), the last dimension 4
represents [tl_x, tl_y, br_x, br_y].
neg_bboxes (Tensor): Contains all the negative boxes,
has shape (num_neg, 4), the last dimension 4
represents [tl_x, tl_y, br_x, br_y].
pos_gt_bboxes (Tensor): Contains all the gt_boxes,
has shape (num_gt, 4), the last dimension 4
represents [tl_x, tl_y, br_x, br_y].
pos_gt_labels (Tensor): Contains all the gt_labels,
has shape (num_gt).
cfg (obj:`ConfigDict`): `train_cfg` of R-CNN.
Returns:
Tuple[Tensor]: Ground truth for proposals
in a single image. Containing the following Tensors:
- labels(Tensor): Gt_labels for all proposals, has
shape (num_proposals,).
- label_weights(Tensor): Labels_weights for all
proposals, has shape (num_proposals,).
- bbox_targets(Tensor):Regression target for all
proposals, has shape (num_proposals, 4), the
last dimension 4 represents [tl_x, tl_y, br_x, br_y].
- bbox_weights(Tensor):Regression weights for all
proposals, has shape (num_proposals, 4).
"""
num_pos = pos_bboxes.size(0)
num_neg = neg_bboxes.size(0)
num_samples = num_pos + num_neg
# original implementation uses new_zeros since BG are set to be 0
# now use empty & fill because BG cat_id = num_classes,
# FG cat_id = [0, num_classes-1]
labels = pos_bboxes.new_full((num_samples, ),
self.num_classes,
dtype=torch.long)
label_weights = pos_bboxes.new_zeros(num_samples)
bbox_targets = pos_bboxes.new_zeros(num_samples, 4)
bbox_weights = pos_bboxes.new_zeros(num_samples, 4)
if num_pos > 0:
labels[:num_pos] = pos_gt_labels
pos_weight = 1.0 if cfg.pos_weight <= 0 else cfg.pos_weight
label_weights[:num_pos] = pos_weight
if not self.reg_decoded_bbox:
pos_bbox_targets = self.bbox_coder.encode(
pos_bboxes, pos_gt_bboxes)
else:
# When the regression loss (e.g. `IouLoss`, `GIouLoss`)
# is applied directly on the decoded bounding boxes, both
# the predicted boxes and regression targets should be with
# absolute coordinate format.
pos_bbox_targets = pos_gt_bboxes
bbox_targets[:num_pos, :] = pos_bbox_targets
bbox_weights[:num_pos, :] = 1
if num_neg > 0:
label_weights[-num_neg:] = 1.0
return labels, label_weights, bbox_targets, bbox_weights
def get_targets(self,
sampling_results,
gt_bboxes,
gt_labels,
rcnn_train_cfg,
concat=True):
"""Calculate the ground truth for all samples in a batch according to
the sampling_results.
Almost the same as the implementation in bbox_head, we passed
additional parameters pos_inds_list and neg_inds_list to
`_get_target_single` function.
Args:
sampling_results (List[obj:SamplingResults]): Assign results of
all images in a batch after sampling.
gt_bboxes (list[Tensor]): Gt_bboxes of all images in a batch,
each tensor has shape (num_gt, 4), the last dimension 4
represents [tl_x, tl_y, br_x, br_y].
gt_labels (list[Tensor]): Gt_labels of all images in a batch,
each tensor has shape (num_gt,).
rcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.
concat (bool): Whether to concatenate the results of all
the images in a single batch.
Returns:
Tuple[Tensor]: Ground truth for proposals in a single image.
Containing the following list of Tensors:
- labels (list[Tensor],Tensor): Gt_labels for all
proposals in a batch, each tensor in list has
shape (num_proposals,) when `concat=False`, otherwise
just a single tensor has shape (num_all_proposals,).
- label_weights (list[Tensor]): Labels_weights for
all proposals in a batch, each tensor in list has
shape (num_proposals,) when `concat=False`, otherwise
just a single tensor has shape (num_all_proposals,).
- bbox_targets (list[Tensor],Tensor): Regression target
for all proposals in a batch, each tensor in list
has shape (num_proposals, 4) when `concat=False`,
otherwise just a single tensor has shape
(num_all_proposals, 4), the last dimension 4 represents
[tl_x, tl_y, br_x, br_y].
- bbox_weights (list[tensor],Tensor): Regression weights for
all proposals in a batch, each tensor in list has shape
(num_proposals, 4) when `concat=False`, otherwise just a
single tensor has shape (num_all_proposals, 4).
"""
pos_bboxes_list = [res.pos_bboxes for res in sampling_results]
neg_bboxes_list = [res.neg_bboxes for res in sampling_results]
pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]
pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]
labels, label_weights, bbox_targets, bbox_weights = multi_apply(
self._get_target_single,
pos_bboxes_list,
neg_bboxes_list,
pos_gt_bboxes_list,
pos_gt_labels_list,
cfg=rcnn_train_cfg)
if concat:
labels = torch.cat(labels, 0)
label_weights = torch.cat(label_weights, 0)
bbox_targets = torch.cat(bbox_targets, 0)
bbox_weights = torch.cat(bbox_weights, 0)
return labels, label_weights, bbox_targets, bbox_weights
@force_fp32(apply_to=('cls_score', 'bbox_pred'))
def loss(self,
cls_score,
bbox_pred,
rois,
labels,
label_weights,
bbox_targets,
bbox_weights,
reduction_override=None):
losses = dict()
if cls_score is not None:
avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.)
if cls_score.numel() > 0:
loss_cls_ = self.loss_cls(
cls_score,
labels,
label_weights,
avg_factor=avg_factor,
reduction_override=reduction_override)
if isinstance(loss_cls_, dict):
losses.update(loss_cls_)
else:
losses['loss_cls'] = loss_cls_
if self.custom_activation:
acc_ = self.loss_cls.get_accuracy(cls_score, labels)
losses.update(acc_)
else:
losses['acc'] = accuracy(cls_score, labels)
if bbox_pred is not None:
bg_class_ind = self.num_classes
# 0~self.num_classes-1 are FG, self.num_classes is BG
pos_inds = (labels >= 0) & (labels < bg_class_ind)
# do not perform bounding box regression for BG anymore.
if pos_inds.any():
if self.reg_decoded_bbox:
# When the regression loss (e.g. `IouLoss`,
# `GIouLoss`, `DIouLoss`) is applied directly on
# the decoded bounding boxes, it decodes the
# already encoded coordinates to absolute format.
bbox_pred = self.bbox_coder.decode(rois[:, 1:], bbox_pred)
if self.reg_class_agnostic:
pos_bbox_pred = bbox_pred.view(
bbox_pred.size(0), 4)[pos_inds.type(torch.bool)]
else:
pos_bbox_pred = bbox_pred.view(
bbox_pred.size(0), -1,
4)[pos_inds.type(torch.bool),
labels[pos_inds.type(torch.bool)]]
losses['loss_bbox'] = self.loss_bbox(
pos_bbox_pred,
bbox_targets[pos_inds.type(torch.bool)],
bbox_weights[pos_inds.type(torch.bool)],
avg_factor=bbox_targets.size(0),
reduction_override=reduction_override)
else:
losses['loss_bbox'] = bbox_pred[pos_inds].sum()
return losses
@force_fp32(apply_to=('cls_score', 'bbox_pred'))
def get_bboxes(self,
rois,
cls_score,
bbox_pred,
img_shape,
scale_factor,
rescale=False,
cfg=None):
"""Transform network output for a batch into bbox predictions.
Args:
rois (Tensor): Boxes to be transformed. Has shape (num_boxes, 5).
last dimension 5 arrange as (batch_index, x1, y1, x2, y2).
cls_score (Tensor): Box scores, has shape
(num_boxes, num_classes + 1).
bbox_pred (Tensor, optional): Box energies / deltas.
has shape (num_boxes, num_classes * 4).
img_shape (Sequence[int], optional): Maximum bounds for boxes,
specifies (H, W, C) or (H, W).
scale_factor (ndarray): Scale factor of the
image arrange as (w_scale, h_scale, w_scale, h_scale).
rescale (bool): If True, return boxes in original image space.
Default: False.
cfg (obj:`ConfigDict`): `test_cfg` of Bbox Head. Default: None
Returns:
tuple[Tensor, Tensor]:
Fisrt tensor is `det_bboxes`, has the shape
(num_boxes, 5) and last
dimension 5 represent (tl_x, tl_y, br_x, br_y, score).
Second tensor is the labels with shape (num_boxes, ).
"""
# some loss (Seesaw loss..) may have custom activation
if self.custom_cls_channels:
scores = self.loss_cls.get_activation(cls_score)
else:
scores = F.softmax(
cls_score, dim=-1) if cls_score is not None else None
# bbox_pred would be None in some detector when with_reg is False,
# e.g. Grid R-CNN.
if bbox_pred is not None:
bboxes = self.bbox_coder.decode(
rois[..., 1:], bbox_pred, max_shape=img_shape)
else:
bboxes = rois[:, 1:].clone()
if img_shape is not None:
bboxes[:, [0, 2]].clamp_(min=0, max=img_shape[1])
bboxes[:, [1, 3]].clamp_(min=0, max=img_shape[0])
if rescale and bboxes.size(0) > 0:
scale_factor = bboxes.new_tensor(scale_factor)
bboxes = (bboxes.view(bboxes.size(0), -1, 4) / scale_factor).view(
bboxes.size()[0], -1)
if cfg is None:
return bboxes, scores
else:
det_bboxes, det_labels = multiclass_nms(bboxes, scores,
cfg.score_thr, cfg.nms,
cfg.max_per_img)
return det_bboxes, det_labels
@force_fp32(apply_to=('bbox_preds', ))
def refine_bboxes(self, rois, labels, bbox_preds, pos_is_gts, img_metas):
"""Refine bboxes during training.
Args:
rois (Tensor): Shape (n*bs, 5), where n is image number per GPU,
and bs is the sampled RoIs per image. The first column is
the image id and the next 4 columns are x1, y1, x2, y2.
labels (Tensor): Shape (n*bs, ).
bbox_preds (Tensor): Shape (n*bs, 4) or (n*bs, 4*#class).
pos_is_gts (list[Tensor]): Flags indicating if each positive bbox
is a gt bbox.
img_metas (list[dict]): Meta info of each image.
Returns:
list[Tensor]: Refined bboxes of each image in a mini-batch.
Example:
>>> # xdoctest: +REQUIRES(module:kwarray)
>>> import kwarray
>>> import numpy as np
>>> from mmdet.core.bbox.demodata import random_boxes
>>> self = BBoxHead(reg_class_agnostic=True)
>>> n_roi = 2
>>> n_img = 4
>>> scale = 512
>>> rng = np.random.RandomState(0)
>>> img_metas = [{'img_shape': (scale, scale)}
... for _ in range(n_img)]
>>> # Create rois in the expected format
>>> roi_boxes = random_boxes(n_roi, scale=scale, rng=rng)
>>> img_ids = torch.randint(0, n_img, (n_roi,))
>>> img_ids = img_ids.float()
>>> rois = torch.cat([img_ids[:, None], roi_boxes], dim=1)
>>> # Create other args
>>> labels = torch.randint(0, 2, (n_roi,)).long()
>>> bbox_preds = random_boxes(n_roi, scale=scale, rng=rng)
>>> # For each image, pretend random positive boxes are gts
>>> is_label_pos = (labels.numpy() > 0).astype(np.int)
>>> lbl_per_img = kwarray.group_items(is_label_pos,
... img_ids.numpy())
>>> pos_per_img = [sum(lbl_per_img.get(gid, []))
... for gid in range(n_img)]
>>> pos_is_gts = [
>>> torch.randint(0, 2, (npos,)).byte().sort(
>>> descending=True)[0]
>>> for npos in pos_per_img
>>> ]
>>> bboxes_list = self.refine_bboxes(rois, labels, bbox_preds,
>>> pos_is_gts, img_metas)
>>> print(bboxes_list)
"""
img_ids = rois[:, 0].long().unique(sorted=True)
assert img_ids.numel() <= len(img_metas)
bboxes_list = []
for i in range(len(img_metas)):
inds = torch.nonzero(
rois[:, 0] == i, as_tuple=False).squeeze(dim=1)
num_rois = inds.numel()
bboxes_ = rois[inds, 1:]
label_ = labels[inds]
bbox_pred_ = bbox_preds[inds]
img_meta_ = img_metas[i]
pos_is_gts_ = pos_is_gts[i]
bboxes = self.regress_by_class(bboxes_, label_, bbox_pred_,
img_meta_)
# filter gt bboxes
pos_keep = 1 - pos_is_gts_
keep_inds = pos_is_gts_.new_ones(num_rois)
keep_inds[:len(pos_is_gts_)] = pos_keep
bboxes_list.append(bboxes[keep_inds.type(torch.bool)])
return bboxes_list
@force_fp32(apply_to=('bbox_pred', ))
def regress_by_class(self, rois, label, bbox_pred, img_meta):
"""Regress the bbox for the predicted class. Used in Cascade R-CNN.
Args:
rois (Tensor): shape (n, 4) or (n, 5)
label (Tensor): shape (n, )
bbox_pred (Tensor): shape (n, 4*(#class)) or (n, 4)
img_meta (dict): Image meta info.
Returns:
Tensor: Regressed bboxes, the same shape as input rois.
"""
assert rois.size(1) == 4 or rois.size(1) == 5, repr(rois.shape)
if not self.reg_class_agnostic:
label = label * 4
inds = torch.stack((label, label + 1, label + 2, label + 3), 1)
bbox_pred = torch.gather(bbox_pred, 1, inds)
assert bbox_pred.size(1) == 4
if rois.size(1) == 4:
new_rois = self.bbox_coder.decode(
rois, bbox_pred, max_shape=img_meta['img_shape'])
else:
bboxes = self.bbox_coder.decode(
rois[:, 1:], bbox_pred, max_shape=img_meta['img_shape'])
new_rois = torch.cat((rois[:, [0]], bboxes), dim=1)
return new_rois
def onnx_export(self,
rois,
cls_score,
bbox_pred,
img_shape,
cfg=None,
**kwargs):
"""Transform network output for a batch into bbox predictions.
Args:
rois (Tensor): Boxes to be transformed.
Has shape (B, num_boxes, 5)
cls_score (Tensor): Box scores. has shape
(B, num_boxes, num_classes + 1), 1 represent the background.
bbox_pred (Tensor, optional): Box energies / deltas for,
has shape (B, num_boxes, num_classes * 4) when.
img_shape (torch.Tensor): Shape of image.
cfg (obj:`ConfigDict`): `test_cfg` of Bbox Head. Default: None
Returns:
tuple[Tensor, Tensor]: dets of shape [N, num_det, 5]
and class labels of shape [N, num_det].
"""
assert rois.ndim == 3, 'Only support export two stage ' \
'model to ONNX ' \
'with batch dimension. '
if self.custom_cls_channels:
scores = self.loss_cls.get_activation(cls_score)
else:
scores = F.softmax(
cls_score, dim=-1) if cls_score is not None else None
if bbox_pred is not None:
bboxes = self.bbox_coder.decode(
rois[..., 1:], bbox_pred, max_shape=img_shape)
else:
bboxes = rois[..., 1:].clone()
if img_shape is not None:
max_shape = bboxes.new_tensor(img_shape)[..., :2]
min_xy = bboxes.new_tensor(0)
max_xy = torch.cat(
[max_shape] * 2, dim=-1).flip(-1).unsqueeze(-2)
bboxes = torch.where(bboxes < min_xy, min_xy, bboxes)
bboxes = torch.where(bboxes > max_xy, max_xy, bboxes)
# Replace multiclass_nms with ONNX::NonMaxSuppression in deployment
from mmdet.core.export import add_dummy_nms_for_onnx
batch_size = scores.shape[0]
# ignore background class
scores = scores[..., :self.num_classes]
labels = torch.arange(
self.num_classes, dtype=torch.long).to(scores.device)
labels = labels.view(1, 1, -1).expand_as(scores)
labels = labels.reshape(batch_size, -1)
scores = scores.reshape(batch_size, -1)
bboxes = bboxes.reshape(batch_size, -1, 4)
max_size = torch.max(img_shape)
# Offset bboxes of each class so that bboxes of different labels
# do not overlap.
offsets = (labels * max_size + 1).unsqueeze(2)
bboxes_for_nms = bboxes + offsets
max_output_boxes_per_class = cfg.nms.get('max_output_boxes_per_class',
cfg.max_per_img)
iou_threshold = cfg.nms.get('iou_threshold', 0.5)
score_threshold = cfg.score_thr
nms_pre = cfg.get('deploy_nms_pre', -1)
batch_dets, labels = add_dummy_nms_for_onnx(
bboxes_for_nms,
scores.unsqueeze(2),
max_output_boxes_per_class,
iou_threshold,
score_threshold,
pre_top_k=nms_pre,
after_top_k=cfg.max_per_img,
labels=labels)
# Offset the bboxes back after dummy nms.
offsets = (labels * max_size + 1).unsqueeze(2)
# Indexing + inplace operation fails with dynamic shape in ONNX
# original style: batch_dets[..., :4] -= offsets
bboxes, scores = batch_dets[..., 0:4], batch_dets[..., 4:5]
bboxes -= offsets
batch_dets = torch.cat([bboxes, scores], dim=2)
return batch_dets, labels
| 1 | 24,237 | This might slow down the inference time, are we sure we need to do that? | open-mmlab-mmdetection | py |
@@ -23,11 +23,9 @@ import (
)
func Example() {
- // This example is used in https://gocloud.dev/howto/sql/#aws
-
- // import _ "gocloud.dev/mysql/awsmysql"
-
- // Variables set up elsewhere:
+ // PRAGMA(gocloud.dev): Package this example for gocloud.dev.
+ // PRAGMA(gocloud.dev): Add a blank import: _ "gocloud.dev/mysql/awsmysql"
+ // PRAGMA(gocloud.dev): Skip until next blank line.
ctx := context.Background()
// Replace these with your actual settings. | 1 | // Copyright 2018 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 awsmysql_test
import (
"context"
"log"
"gocloud.dev/mysql"
_ "gocloud.dev/mysql/awsmysql"
)
func Example() {
// This example is used in https://gocloud.dev/howto/sql/#aws
// import _ "gocloud.dev/mysql/awsmysql"
// Variables set up elsewhere:
ctx := context.Background()
// Replace these with your actual settings.
db, err := mysql.Open(ctx,
"awsmysql://myrole:[email protected]/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Use database in your program.
db.ExecContext(ctx, "CREATE TABLE foo (bar INT);")
}
| 1 | 19,583 | This would read better if you add "Skip code/lines" or (exclude/hide code if you follow my earlier suggestion") | google-go-cloud | go |
@@ -34,6 +34,13 @@ import java.util.HashSet;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
+import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
public class DatasetUtil {
| 1 | package edu.harvard.iq.dataverse.dataset;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DatasetField;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.FileMetadata;
import edu.harvard.iq.dataverse.dataaccess.DataAccess;
import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO;
import edu.harvard.iq.dataverse.dataaccess.StorageIO;
import edu.harvard.iq.dataverse.dataaccess.ImageThumbConverter;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import edu.harvard.iq.dataverse.util.FileUtil;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
public class DatasetUtil {
private static final Logger logger = Logger.getLogger(DatasetUtil.class.getCanonicalName());
public static String datasetLogoFilenameFinal = "dataset_logo_original";
public static String datasetLogoThumbnail = "dataset_logo";
public static String thumb48addedByImageThumbConverter = ".thumb48";
public static List<DatasetThumbnail> getThumbnailCandidates(Dataset dataset, boolean considerDatasetLogoAsCandidate) {
List<DatasetThumbnail> thumbnails = new ArrayList<>();
if (dataset == null) {
return thumbnails;
}
if (considerDatasetLogoAsCandidate) {
// Path path = Paths.get(dataset.getFileSystemDirectory() + File.separator + datasetLogoThumbnail + thumb48addedByImageThumbConverter);
// if (Files.exists(path)) {
// logger.fine("Thumbnail created from dataset logo exists!");
// File file = path.toFile();
// try {
// byte[] bytes = Files.readAllBytes(file.toPath());
StorageIO<Dataset> dataAccess = null;
try{
dataAccess = DataAccess.getStorageIO(dataset);
}
catch(IOException ioex){
}
InputStream in = null;
try {
in = dataAccess.getAuxFileAsInputStream(datasetLogoThumbnail + thumb48addedByImageThumbConverter);
} catch (Exception ioex) {
}
if (in != null) {
logger.fine("Thumbnail created from dataset logo exists!");
try {
byte[] bytes = IOUtils.toByteArray(in);
String base64image = Base64.getEncoder().encodeToString(bytes);
DatasetThumbnail datasetThumbnail = new DatasetThumbnail(FileUtil.DATA_URI_SCHEME + base64image, null);
thumbnails.add(datasetThumbnail);
} catch (IOException ex) {
logger.warning("Unable to rescale image: " + ex);
}
} else {
logger.fine("There is no thumbnail created from a dataset logo");
}
IOUtils.closeQuietly(in);
}
for (FileMetadata fileMetadata : dataset.getLatestVersion().getFileMetadatas()) {
DataFile dataFile = fileMetadata.getDataFile();
if (dataFile != null && FileUtil.isThumbnailSupported(dataFile)
&& ImageThumbConverter.isThumbnailAvailable(dataFile)
&& !dataFile.isRestricted()) {
String imageSourceBase64 = null;
imageSourceBase64 = ImageThumbConverter.getImageThumbnailAsBase64(dataFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE);
if (imageSourceBase64 != null) {
DatasetThumbnail datasetThumbnail = new DatasetThumbnail(imageSourceBase64, dataFile);
thumbnails.add(datasetThumbnail);
}
}
}
return thumbnails;
}
/**
* Note "datasetVersionId" can be null. If needed, it helps the "efficiency"
* of "attemptToAutomaticallySelectThumbnailFromDataFiles"
*
* @param dataset
* @param datasetVersion
* @return
*/
public static DatasetThumbnail getThumbnail(Dataset dataset, DatasetVersion datasetVersion) {
if (dataset == null) {
return null;
}
StorageIO<Dataset> dataAccess = null;
try{
dataAccess = DataAccess.getStorageIO(dataset);
}
catch(IOException ioex){
logger.warning("getThumbnail(): Failed to initialize dataset StorageIO for " + dataset.getStorageIdentifier() + " (" + ioex.getMessage() + ")");
}
InputStream in = null;
try {
if (dataAccess == null) {
logger.warning("getThumbnail(): Failed to initialize dataset StorageIO for " + dataset.getStorageIdentifier());
} else if (dataAccess.getAuxFileAsInputStream(datasetLogoThumbnail + thumb48addedByImageThumbConverter) != null) {
in = dataAccess.getAuxFileAsInputStream(datasetLogoThumbnail + thumb48addedByImageThumbConverter);
}
} catch (IOException ex) {
logger.fine("Dataset-level thumbnail file does not exist, or failed to open; will try to find an image file that can be used as the thumbnail.");
}
if (in != null) {
try {
byte[] bytes = IOUtils.toByteArray(in);
String base64image = Base64.getEncoder().encodeToString(bytes);
DatasetThumbnail datasetThumbnail = new DatasetThumbnail(FileUtil.DATA_URI_SCHEME + base64image, null);
logger.fine("will get thumbnail from dataset logo");
return datasetThumbnail;
} catch (IOException ex) {
logger.fine("Unable to read thumbnail image from file: " + ex);
return null;
} finally
{
IOUtils.closeQuietly(in);
}
} else {
DataFile thumbnailFile = dataset.getThumbnailFile();
if (thumbnailFile == null) {
if (dataset.isUseGenericThumbnail()) {
logger.fine("Dataset (id :" + dataset.getId() + ") does not have a thumbnail and is 'Use Generic'.");
return null;
} else {
thumbnailFile = attemptToAutomaticallySelectThumbnailFromDataFiles(dataset, datasetVersion);
if (thumbnailFile == null) {
logger.fine("Dataset (id :" + dataset.getId() + ") does not have a thumbnail available that could be selected automatically.");
return null;
} else {
String imageSourceBase64 = ImageThumbConverter.getImageThumbnailAsBase64(thumbnailFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE);
DatasetThumbnail defaultDatasetThumbnail = new DatasetThumbnail(imageSourceBase64, thumbnailFile);
logger.fine("thumbnailFile (id :" + thumbnailFile.getId() + ") will get thumbnail through automatic selection from DataFile id " + thumbnailFile.getId());
return defaultDatasetThumbnail;
}
}
} else if (thumbnailFile.isRestricted()) {
logger.fine("Dataset (id :" + dataset.getId() + ") has a thumbnail the user selected but the file must have later been restricted. Returning null.");
return null;
} else {
String imageSourceBase64 = ImageThumbConverter.getImageThumbnailAsBase64(thumbnailFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE);
DatasetThumbnail userSpecifiedDatasetThumbnail = new DatasetThumbnail(imageSourceBase64, thumbnailFile);
logger.fine("Dataset (id :" + dataset.getId() + ") will get thumbnail the user specified from DataFile id " + thumbnailFile.getId());
return userSpecifiedDatasetThumbnail;
}
}
}
public static DatasetThumbnail getThumbnail(Dataset dataset) {
if (dataset == null) {
return null;
}
return getThumbnail(dataset, null);
}
public static boolean deleteDatasetLogo(Dataset dataset) {
if (dataset == null) {
return false;
}
try {
StorageIO<Dataset> storageIO = getStorageIO(dataset);
if (storageIO == null) {
logger.warning("Null storageIO in deleteDatasetLogo()");
return false;
}
storageIO.deleteAuxObject(datasetLogoFilenameFinal);
storageIO.deleteAuxObject(datasetLogoThumbnail + thumb48addedByImageThumbConverter);
} catch (IOException ex) {
logger.info("Failed to delete dataset logo: " + ex.getMessage());
return false;
}
return true;
//TODO: Is this required?
// File originalFile = new File(dataset.getFileSystemDirectory().toString(), datasetLogoFilenameFinal);
// boolean originalFileDeleted = originalFile.delete();
// File thumb48 = new File(dataset.getFileSystemDirectory().toString(), File.separator + datasetLogoThumbnail + thumb48addedByImageThumbConverter);
// boolean thumb48Deleted = thumb48.delete();
// if (originalFileDeleted && thumb48Deleted) {
// return true;
// } else {
// logger.info("One of the files wasn't deleted. Original deleted: " + originalFileDeleted + ". thumb48 deleted: " + thumb48Deleted + ".");
// return false;
// }
}
/**
* Pass an optional datasetVersion in case the file system is checked
*
* @param dataset
* @param datasetVersion
* @return
*/
public static DataFile attemptToAutomaticallySelectThumbnailFromDataFiles(Dataset dataset, DatasetVersion datasetVersion) {
if (dataset == null) {
return null;
}
if (dataset.isUseGenericThumbnail()) {
logger.fine("Bypassing logic to find a thumbnail because a generic icon for the dataset is desired.");
return null;
}
if (datasetVersion == null) {
logger.fine("getting a published version of the dataset");
// We want to use published files only when automatically selecting
// dataset thumbnails.
datasetVersion = dataset.getReleasedVersion();
}
// No published version? - No [auto-selected] thumbnail for you.
if (datasetVersion == null) {
return null;
}
for (FileMetadata fmd : datasetVersion.getFileMetadatas()) {
DataFile testFile = fmd.getDataFile();
// We don't want to use a restricted image file as the dedicated thumbnail:
if (!testFile.isRestricted() && FileUtil.isThumbnailSupported(testFile) && ImageThumbConverter.isThumbnailAvailable(testFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE)) {
return testFile;
}
}
logger.fine("In attemptToAutomaticallySelectThumbnailFromDataFiles and interated through all the files but couldn't find a thumbnail.");
return null;
}
public static Dataset persistDatasetLogoToStorageAndCreateThumbnail(Dataset dataset, InputStream inputStream) {
if (dataset == null) {
return null;
}
File tmpFile = null;
try {
tmpFile = FileUtil.inputStreamToFile(inputStream);
} catch (IOException ex) {
logger.severe(ex.getMessage());
}
StorageIO<Dataset> dataAccess = null;
try{
dataAccess = DataAccess.createNewStorageIO(dataset,"placeholder");
}
catch(IOException ioex){
//TODO: Add a suitable waing message
logger.warning("Failed to save the file, storage id " + dataset.getStorageIdentifier() + " (" + ioex.getMessage() + ")");
}
//File originalFile = new File(datasetDirectory.toString(), datasetLogoFilenameFinal);
try {
//this goes through Swift API/local storage/s3 to write the dataset thumbnail into a container
dataAccess.savePathAsAux(tmpFile.toPath(), datasetLogoFilenameFinal);
} catch (IOException ex) {
logger.severe("Failed to move original file from " + tmpFile.getAbsolutePath() + " to its DataAccess location" + ": " + ex);
}
BufferedImage fullSizeImage = null;
try {
fullSizeImage = ImageIO.read(tmpFile);
} catch (IOException ex) {
logger.severe(ex.getMessage());
return null;
}
if (fullSizeImage == null) {
logger.fine("fullSizeImage was null!");
return null;
}
int width = fullSizeImage.getWidth();
int height = fullSizeImage.getHeight();
FileChannel src = null;
try {
src = new FileInputStream(tmpFile).getChannel();
} catch (FileNotFoundException ex) {
logger.severe(ex.getMessage());
return null;
}
FileChannel dest = null;
try {
dest = new FileOutputStream(tmpFile).getChannel();
} catch (FileNotFoundException ex) {
logger.severe(ex.getMessage());
return null;
}
try {
dest.transferFrom(src, 0, src.size());
} catch (IOException ex) {
logger.severe(ex.getMessage());
return null;
}
File tmpFileForResize = null;
try {
tmpFileForResize = FileUtil.inputStreamToFile(inputStream);
} catch (IOException ex) {
logger.severe(ex.getMessage());
return null;
}
String thumbFileLocation = ImageThumbConverter.rescaleImage(fullSizeImage, width, height, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE, tmpFileForResize.toPath().toString());
logger.fine("thumbFileLocation = " + thumbFileLocation);
logger.fine("tmpFileLocation=" + tmpFileForResize.toPath().toString());
//now we must save the updated thumbnail
try {
dataAccess.savePathAsAux(Paths.get(thumbFileLocation), datasetLogoThumbnail+thumb48addedByImageThumbConverter);
} catch (IOException ex) {
logger.severe("Failed to move updated thumbnail file from " + tmpFile.getAbsolutePath() + " to its DataAccess location" + ": " + ex);
}
//This deletes the tempfiles created for rescaling and encoding
boolean tmpFileWasDeleted = tmpFile.delete();
boolean originalTempFileWasDeleted = tmpFileForResize.delete();
try {
Files.delete(Paths.get(thumbFileLocation));
} catch (IOException ioex) {
logger.fine("Failed to delete temporary thumbnail file");
}
logger.fine("Thumbnail saved to " + thumbFileLocation + ". Temporary file deleted : " + tmpFileWasDeleted + ". Original file deleted : " + originalTempFileWasDeleted);
return dataset;
}
public static InputStream getThumbnailAsInputStream(Dataset dataset) {
if (dataset == null) {
return null;
}
DatasetThumbnail datasetThumbnail = dataset.getDatasetThumbnail();
if (datasetThumbnail == null) {
return null;
} else {
String base64Image = datasetThumbnail.getBase64image();
String leadingStringToRemove = FileUtil.DATA_URI_SCHEME;
String encodedImg = base64Image.substring(leadingStringToRemove.length());
byte[] decodedImg = null;
try {
decodedImg = Base64.getDecoder().decode(encodedImg.getBytes("UTF-8"));
logger.fine("returning this many bytes for " + "dataset id: " + dataset.getId() + ", persistentId: " + dataset.getIdentifier() + " :" + decodedImg.length);
} catch (UnsupportedEncodingException ex) {
logger.info("dataset thumbnail could not be decoded for dataset id " + dataset.getId() + ": " + ex);
return null;
}
ByteArrayInputStream nonDefaultDatasetThumbnail = new ByteArrayInputStream(decodedImg);
logger.fine("For dataset id " + dataset.getId() + " a thumbnail was found and is being returned.");
return nonDefaultDatasetThumbnail;
}
}
/**
* The dataset logo is the file that a user uploads which is *not* one of
* the data files. Compare to the datavese logo. We do not save the original
* file that is uploaded. Rather, we delete it after first creating at least
* one thumbnail from it.
*/
public static boolean isDatasetLogoPresent(Dataset dataset) {
if (dataset == null) {
return false;
}
StorageIO<Dataset> dataAccess = null;
try {
dataAccess = DataAccess.getStorageIO(dataset);
return dataAccess.isAuxObjectCached(datasetLogoThumbnail + thumb48addedByImageThumbConverter);
} catch (IOException ioex) {
}
return false;
}
public static List<DatasetField> getDatasetSummaryFields(DatasetVersion datasetVersion, String customFields) {
List<DatasetField> datasetFields = new ArrayList<>();
//if customFields are empty, go with default fields.
if(customFields==null || customFields.isEmpty()){
customFields="dsDescription,subject,keyword,publication,notesText";
}
String[] customFieldList= customFields.split(",");
Map<String,DatasetField> DatasetFieldsSet=new HashMap<>();
for (DatasetField dsf : datasetVersion.getFlatDatasetFields()) {
DatasetFieldsSet.put(dsf.getDatasetFieldType().getName(),dsf);
}
for(String cfl : customFieldList)
{
DatasetField df = DatasetFieldsSet.get(cfl);
if(df!=null)
datasetFields.add(df);
}
return datasetFields;
}
}
| 1 | 39,312 | Looks like glassfish went a bit nuts doing a refactor | IQSS-dataverse | java |
@@ -84,6 +84,17 @@ namespace OpenTelemetry.Trace.Export.Internal
return Task.WhenAll(tasks);
}
+ public override Task ForceFlushAsync(CancellationToken cancellationToken)
+ {
+ var tasks = new List<Task>();
+ foreach (var processor in this.processors)
+ {
+ tasks.Add(processor.ForceFlushAsync(cancellationToken));
+ }
+
+ return Task.WhenAll(tasks);
+ }
+
public void Dispose()
{
foreach (var processor in this.processors) | 1 | // <copyright file="BroadcastActivityProcessor.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.Linq;
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Trace.Export.Internal
{
internal class BroadcastActivityProcessor : ActivityProcessor, IDisposable
{
private readonly IEnumerable<ActivityProcessor> processors;
public BroadcastActivityProcessor(IEnumerable<ActivityProcessor> processors)
{
if (processors == null)
{
throw new ArgumentNullException(nameof(processors));
}
if (!processors.Any())
{
throw new ArgumentException($"{nameof(processors)} collection is empty");
}
this.processors = processors;
}
public override void OnEnd(Activity activity)
{
foreach (var processor in this.processors)
{
try
{
processor.OnEnd(activity);
}
catch (Exception e)
{
OpenTelemetrySdkEventSource.Log.SpanProcessorException("OnEnd", e);
}
}
}
public override void OnStart(Activity activity)
{
foreach (var processor in this.processors)
{
try
{
processor.OnStart(activity);
}
catch (Exception e)
{
OpenTelemetrySdkEventSource.Log.SpanProcessorException("OnStart", e);
}
}
}
public override Task ShutdownAsync(CancellationToken cancellationToken)
{
var tasks = new List<Task>();
foreach (var processor in this.processors)
{
tasks.Add(processor.ShutdownAsync(cancellationToken));
}
return Task.WhenAll(tasks);
}
public void Dispose()
{
foreach (var processor in this.processors)
{
try
{
if (processor is IDisposable disposable)
{
disposable.Dispose();
}
}
catch (Exception e)
{
OpenTelemetrySdkEventSource.Log.SpanProcessorException("Dispose", e);
}
}
}
}
}
| 1 | 14,567 | nit: allocate the list using the number of processors. | open-telemetry-opentelemetry-dotnet | .cs |
@@ -142,10 +142,10 @@ public class PartitionSpec implements Serializable {
public String partitionToPath(StructLike data) {
StringBuilder sb = new StringBuilder();
- Class<?>[] javaClasses = javaClasses();
- for (int i = 0; i < javaClasses.length; i += 1) {
+ Class<?>[] initializedClasses = javaClasses();
+ for (int i = 0; i < initializedClasses.length; i += 1) {
PartitionField field = fields[i];
- String valueString = field.transform().toHumanString(get(data, i, javaClasses[i]));
+ String valueString = field.transform().toHumanString(get(data, i, initializedClasses[i]));
if (i > 0) {
sb.append("/"); | 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 com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.iceberg.exceptions.ValidationException;
import org.apache.iceberg.transforms.Transforms;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
/**
* Represents how to produce partition data for a table.
* <p>
* Partition data is produced by transforming columns in a table. Each column transform is
* represented by a named {@link PartitionField}.
*/
public class PartitionSpec implements Serializable {
// start assigning IDs for partition fields at 1000
private static final int PARTITION_DATA_ID_START = 1000;
private final Schema schema;
// this is ordered so that DataFile has a consistent schema
private final int specId;
private final PartitionField[] fields;
private transient Map<Integer, PartitionField> fieldsBySourceId = null;
private transient Map<String, PartitionField> fieldsByName = null;
private transient Class<?>[] javaClasses = null;
private transient List<PartitionField> fieldList = null;
private PartitionSpec(Schema schema, int specId, List<PartitionField> fields) {
this.schema = schema;
this.specId = specId;
this.fields = new PartitionField[fields.size()];
for (int i = 0; i < this.fields.length; i += 1) {
this.fields[i] = fields.get(i);
}
}
/**
* @return the {@link Schema} for this spec.
*/
public Schema schema() {
return schema;
}
/**
* @return the ID of this spec
*/
public int specId() {
return specId;
}
/**
* @return the list of {@link PartitionField partition fields} for this spec.
*/
public List<PartitionField> fields() {
return lazyFieldList();
}
/**
* @param fieldId a field id from the source schema
* @return the {@link PartitionField field} that partitions the given source field
*/
public PartitionField getFieldBySourceId(int fieldId) {
return lazyFieldsBySourceId().get(fieldId);
}
/**
* @return a {@link Types.StructType} for partition data defined by this spec.
*/
public Types.StructType partitionType() {
List<Types.NestedField> structFields = Lists.newArrayListWithExpectedSize(fields.length);
for (int i = 0; i < fields.length; i += 1) {
PartitionField field = fields[i];
Type sourceType = schema.findType(field.sourceId());
Type resultType = field.transform().getResultType(sourceType);
// assign ids for partition fields starting at 100 to leave room for data file's other fields
structFields.add(
Types.NestedField.optional(PARTITION_DATA_ID_START + i, field.name(), resultType));
}
return Types.StructType.of(structFields);
}
public Class<?>[] javaClasses() {
if (javaClasses == null) {
this.javaClasses = new Class<?>[fields.length];
for (int i = 0; i < fields.length; i += 1) {
PartitionField field = fields[i];
Type sourceType = schema.findType(field.sourceId());
Type result = field.transform().getResultType(sourceType);
javaClasses[i] = result.typeId().javaClass();
}
}
return javaClasses;
}
@SuppressWarnings("unchecked")
private <T> T get(StructLike data, int pos, Class<?> javaClass) {
return data.get(pos, (Class<T>) javaClass);
}
private String escape(String string) {
try {
return URLEncoder.encode(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public String partitionToPath(StructLike data) {
StringBuilder sb = new StringBuilder();
Class<?>[] javaClasses = javaClasses();
for (int i = 0; i < javaClasses.length; i += 1) {
PartitionField field = fields[i];
String valueString = field.transform().toHumanString(get(data, i, javaClasses[i]));
if (i > 0) {
sb.append("/");
}
sb.append(field.name()).append("=").append(escape(valueString));
}
return sb.toString();
}
/**
* Returns true if this spec is equivalent to the other, with field names ignored. That is, if
* both specs have the same number of fields, field order, source columns, and transforms.
*
* @param other another PartitionSpec
* @return true if the specs have the same fields, source columns, and transforms.
*/
public boolean compatibleWith(PartitionSpec other) {
if (equals(other)) {
return true;
}
if (fields.length != other.fields.length) {
return false;
}
for (int i = 0; i < fields.length; i += 1) {
PartitionField thisField = fields[i];
PartitionField thatField = other.fields[i];
if (thisField.sourceId() != thatField.sourceId() ||
!thisField.transform().toString().equals(thatField.transform().toString())) {
return false;
}
}
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
PartitionSpec that = (PartitionSpec) other;
if (this.specId != that.specId) {
return false;
}
return Arrays.equals(fields, that.fields);
}
@Override
public int hashCode() {
return Objects.hashCode(Arrays.hashCode(fields));
}
private List<PartitionField> lazyFieldList() {
if (fieldList == null) {
this.fieldList = ImmutableList.copyOf(fields);
}
return fieldList;
}
private Map<String, PartitionField> lazyFieldsByName() {
if (fieldsByName == null) {
ImmutableMap.Builder<String, PartitionField> builder = ImmutableMap.builder();
for (PartitionField field : fields) {
builder.put(field.name(), field);
}
this.fieldsByName = builder.build();
}
return fieldsByName;
}
private Map<Integer, PartitionField> lazyFieldsBySourceId() {
if (fieldsBySourceId == null) {
ImmutableMap.Builder<Integer, PartitionField> byIdBuilder = ImmutableMap.builder();
for (PartitionField field : fields) {
byIdBuilder.put(field.sourceId(), field);
}
this.fieldsBySourceId = byIdBuilder.build();
}
return fieldsBySourceId;
}
/**
* Returns the source field ids for identity partitions.
*
* @return a set of source ids for the identity partitions.
*/
public Set<Integer> identitySourceIds() {
Set<Integer> sourceIds = Sets.newHashSet();
List<PartitionField> fields = this.fields();
for (PartitionField field : fields) {
if ("identity".equals(field.transform().toString())) {
sourceIds.add(field.sourceId());
}
}
return sourceIds;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (PartitionField field : fields) {
sb.append("\n");
sb.append(" ").append(field.name()).append(": ").append(field.transform())
.append("(").append(field.sourceId()).append(")");
}
if (fields.length > 0) {
sb.append("\n");
}
sb.append("]");
return sb.toString();
}
private static final PartitionSpec UNPARTITIONED_SPEC =
new PartitionSpec(new Schema(), 0, ImmutableList.of());
/**
* Returns a spec for unpartitioned tables.
*
* @return a partition spec with no partitions
*/
public static PartitionSpec unpartitioned() {
return UNPARTITIONED_SPEC;
}
/**
* Creates a new {@link Builder partition spec builder} for the given {@link Schema}.
*
* @param schema a schema
* @return a partition spec builder for the given schema
*/
public static Builder builderFor(Schema schema) {
return new Builder(schema);
}
/**
* Used to create valid {@link PartitionSpec partition specs}.
* <p>
* Call {@link #builderFor(Schema)} to create a new builder.
*/
public static class Builder {
private final Schema schema;
private final List<PartitionField> fields = Lists.newArrayList();
private final Set<String> partitionNames = Sets.newHashSet();
private int specId = 0;
private Builder(Schema schema) {
this.schema = schema;
}
private void checkAndAddPartitionName(String name) {
Preconditions.checkArgument(name != null && !name.isEmpty(),
"Cannot use empty or null partition name: %s", name);
Preconditions.checkArgument(!partitionNames.contains(name),
"Cannot use partition name more than once: %s", name);
partitionNames.add(name);
}
public Builder withSpecId(int specId) {
this.specId = specId;
return this;
}
private Types.NestedField findSourceColumn(String sourceName) {
Types.NestedField sourceColumn = schema.findField(sourceName);
Preconditions.checkNotNull(sourceColumn, "Cannot find source column: %s", sourceName);
return sourceColumn;
}
public Builder identity(String sourceName) {
checkAndAddPartitionName(sourceName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), sourceName, Transforms.identity(sourceColumn.type())));
return this;
}
public Builder year(String sourceName) {
String name = sourceName + "_year";
checkAndAddPartitionName(name);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), name, Transforms.year(sourceColumn.type())));
return this;
}
public Builder month(String sourceName) {
String name = sourceName + "_month";
checkAndAddPartitionName(name);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), name, Transforms.month(sourceColumn.type())));
return this;
}
public Builder day(String sourceName) {
String name = sourceName + "_day";
checkAndAddPartitionName(name);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), name, Transforms.day(sourceColumn.type())));
return this;
}
public Builder hour(String sourceName) {
String name = sourceName + "_hour";
checkAndAddPartitionName(name);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), name, Transforms.hour(sourceColumn.type())));
return this;
}
public Builder bucket(String sourceName, int numBuckets) {
String name = sourceName + "_bucket";
checkAndAddPartitionName(name);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), name, Transforms.bucket(sourceColumn.type(), numBuckets)));
return this;
}
public Builder truncate(String sourceName, int width) {
String name = sourceName + "_trunc";
checkAndAddPartitionName(name);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), name, Transforms.truncate(sourceColumn.type(), width)));
return this;
}
public Builder add(int sourceId, String name, String transform) {
checkAndAddPartitionName(name);
Types.NestedField column = schema.findField(sourceId);
Preconditions.checkNotNull(column, "Cannot find source column: %d", sourceId);
fields.add(new PartitionField(
sourceId, name, Transforms.fromString(column.type(), transform)));
return this;
}
public PartitionSpec build() {
PartitionSpec spec = new PartitionSpec(schema, specId, fields);
checkCompatibility(spec, schema);
return spec;
}
}
public static void checkCompatibility(PartitionSpec spec, Schema schema) {
for (PartitionField field : spec.fields) {
Type sourceType = schema.findType(field.sourceId());
ValidationException.check(sourceType.isPrimitiveType(),
"Cannot partition by non-primitive source field: %s", sourceType);
ValidationException.check(
field.transform().canTransform(sourceType),
"Invalid source type %s for transform: %s",
sourceType, field.transform());
}
}
}
| 1 | 13,085 | Was this change triggered by baseline? | apache-iceberg | java |
@@ -36,17 +36,13 @@ class OrgThirtyDayActivity < ActiveRecord::Base
private
def with_commits_and_affiliates
- orgs = Organization.arel_table
joins(:organization)
- .where(id: orgs[:thirty_day_activity_id])
.where(arel_table[:thirty_day_commit_count].gt(0)
.and(arel_table[:affiliate_count].gt(0)))
end
def with_thirty_day_commit_count
- orgs = Organization.arel_table
joins(:organization)
- .where(id: orgs[:thirty_day_activity_id])
.where.not(thirty_day_commit_count: nil)
.order(thirty_day_commit_count: :desc)
.limit(5) | 1 | class OrgThirtyDayActivity < ActiveRecord::Base
SORT_TYPES = [['All Organizations', 'all_orgs'], %w(Commercial commercial), %w(Education educational),
%w(Government government), %w(Non-Profit non_profit), %w(Large large),
%w(Medium medium), %w(Small small)]
FILTER_TYPES = { all_orgs: :filter_all_orgs, small: :filter_small_orgs, medium: :filter_medium_orgs,
large: :filter_large_orgs, commercial: :filter_commercial_orgs,
government: :filter_government_orgs, non_profit: :filter_non_profit_orgs,
educational: :filter_educational_orgs }
belongs_to :organization
scope :filter_all_orgs, -> { with_thirty_day_commit_count }
scope :filter_small_orgs, -> { with_thirty_day_commit_count.where(project_count: 1..10) }
scope :filter_medium_orgs, -> { with_thirty_day_commit_count.where(project_count: 11..50) }
scope :filter_large_orgs, -> { with_thirty_day_commit_count.where(arel_table[:project_count].gt(50)) }
scope :filter_commercial_orgs, -> { with_thirty_day_commit_count.where(org_type: 1) }
scope :filter_educational_orgs, -> { with_thirty_day_commit_count.where(org_type: 2) }
scope :filter_government_orgs, -> { with_thirty_day_commit_count.where(org_type: 3) }
scope :filter_non_profit_orgs, -> { with_thirty_day_commit_count.where(org_type: 4) }
class << self
def most_active_orgs
commits_per_affliate = (arel_table[:thirty_day_commit_count] / arel_table[:affiliate_count])
with_commits_and_affiliates
.select([Arel.star, commits_per_affliate.as('commits_per_affiliate')])
.order(commits_per_affliate.desc).limit(3)
end
def filter(filter_type)
filter_type = filter_type.to_sym
filter_type = :all_orgs unless FILTER_TYPES.keys.include?(filter_type)
send(FILTER_TYPES[filter_type])
end
private
def with_commits_and_affiliates
orgs = Organization.arel_table
joins(:organization)
.where(id: orgs[:thirty_day_activity_id])
.where(arel_table[:thirty_day_commit_count].gt(0)
.and(arel_table[:affiliate_count].gt(0)))
end
def with_thirty_day_commit_count
orgs = Organization.arel_table
joins(:organization)
.where(id: orgs[:thirty_day_activity_id])
.where.not(thirty_day_commit_count: nil)
.order(thirty_day_commit_count: :desc)
.limit(5)
end
end
end
| 1 | 7,980 | This code was doing nothing as far as I can tell and was making the SQL find nothing with the new version of Rails. Remove it unless someone can explain why it is there. | blackducksoftware-ohloh-ui | rb |
@@ -39,6 +39,7 @@ public class RestExplorerApp extends Application {
public void onCreate() {
super.onCreate();
SalesforceSDKManager.initNative(getApplicationContext(), new KeyImpl(), ExplorerActivity.class);
+ SalesforceSDKManager.getInstance().setBrowserLoginEnabled(true);
/*
* Un-comment the line below to enable push notifications in this app. | 1 | /*
* Copyright (c) 2011-present, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software 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 salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.samples.restexplorer;
import android.app.Application;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
/**
* Application class for the rest explorer app.
*/
public class RestExplorerApp extends Application {
@Override
public void onCreate() {
super.onCreate();
SalesforceSDKManager.initNative(getApplicationContext(), new KeyImpl(), ExplorerActivity.class);
/*
* Un-comment the line below to enable push notifications in this app.
* Replace 'pnInterface' with your implementation of 'PushNotificationInterface'.
* Add your Google package ID in 'bootonfig.xml', as the value
* for the key 'androidPushNotificationClientId'.
*/
// SalesforceSDKManager.getInstance().setPushNotificationReceiver(pnInterface);
}
}
| 1 | 16,099 | Setting browser based login as the default for `RestAPIExplorer`. | forcedotcom-SalesforceMobileSDK-Android | java |
@@ -231,6 +231,11 @@ void DataParallelTreeLearner<TREELEARNER_T>::FindBestSplitsFromHistograms(const
}
// sync global best info
+ auto max_cat_threshold = this->config_->max_cat_threshold;
+ int splitInfoSize = SplitInfo::Size(max_cat_threshold);
+ if (input_buffer_.size() < splitInfoSize * 2) {
+ input_buffer_.resize(splitInfoSize * 2);
+ }
SyncUpGlobalBestSplit(input_buffer_.data(), input_buffer_.data(), &smaller_best_split, &larger_best_split, this->config_->max_cat_threshold);
// set best split | 1 | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <cstring>
#include <tuple>
#include <vector>
#include "parallel_tree_learner.h"
namespace LightGBM {
template <typename TREELEARNER_T>
DataParallelTreeLearner<TREELEARNER_T>::DataParallelTreeLearner(const Config* config)
:TREELEARNER_T(config) {
}
template <typename TREELEARNER_T>
DataParallelTreeLearner<TREELEARNER_T>::~DataParallelTreeLearner() {
}
template <typename TREELEARNER_T>
void DataParallelTreeLearner<TREELEARNER_T>::Init(const Dataset* train_data, bool is_constant_hessian) {
// initialize SerialTreeLearner
TREELEARNER_T::Init(train_data, is_constant_hessian);
// Get local rank and global machine size
rank_ = Network::rank();
num_machines_ = Network::num_machines();
// allocate buffer for communication
size_t buffer_size = this->train_data_->NumTotalBin() * kHistEntrySize;
input_buffer_.resize(buffer_size);
output_buffer_.resize(buffer_size);
is_feature_aggregated_.resize(this->num_features_);
block_start_.resize(num_machines_);
block_len_.resize(num_machines_);
buffer_write_start_pos_.resize(this->num_features_);
buffer_read_start_pos_.resize(this->num_features_);
global_data_count_in_leaf_.resize(this->config_->num_leaves);
}
template <typename TREELEARNER_T>
void DataParallelTreeLearner<TREELEARNER_T>::ResetConfig(const Config* config) {
TREELEARNER_T::ResetConfig(config);
global_data_count_in_leaf_.resize(this->config_->num_leaves);
}
template <typename TREELEARNER_T>
void DataParallelTreeLearner<TREELEARNER_T>::BeforeTrain() {
TREELEARNER_T::BeforeTrain();
// generate feature partition for current tree
std::vector<std::vector<int>> feature_distribution(num_machines_, std::vector<int>());
std::vector<int> num_bins_distributed(num_machines_, 0);
for (int i = 0; i < this->train_data_->num_total_features(); ++i) {
int inner_feature_index = this->train_data_->InnerFeatureIndex(i);
if (inner_feature_index == -1) { continue; }
if (this->col_sampler_.is_feature_used_bytree()[inner_feature_index]) {
int cur_min_machine = static_cast<int>(ArrayArgs<int>::ArgMin(num_bins_distributed));
feature_distribution[cur_min_machine].push_back(inner_feature_index);
auto num_bin = this->train_data_->FeatureNumBin(inner_feature_index);
if (this->train_data_->FeatureBinMapper(inner_feature_index)->GetMostFreqBin() == 0) {
num_bin -= 1;
}
num_bins_distributed[cur_min_machine] += num_bin;
}
is_feature_aggregated_[inner_feature_index] = false;
}
// get local used feature
for (auto fid : feature_distribution[rank_]) {
is_feature_aggregated_[fid] = true;
}
// get block start and block len for reduce scatter
reduce_scatter_size_ = 0;
for (int i = 0; i < num_machines_; ++i) {
block_len_[i] = 0;
for (auto fid : feature_distribution[i]) {
auto num_bin = this->train_data_->FeatureNumBin(fid);
if (this->train_data_->FeatureBinMapper(fid)->GetMostFreqBin() == 0) {
num_bin -= 1;
}
block_len_[i] += num_bin * kHistEntrySize;
}
reduce_scatter_size_ += block_len_[i];
}
block_start_[0] = 0;
for (int i = 1; i < num_machines_; ++i) {
block_start_[i] = block_start_[i - 1] + block_len_[i - 1];
}
// get buffer_write_start_pos_
int bin_size = 0;
for (int i = 0; i < num_machines_; ++i) {
for (auto fid : feature_distribution[i]) {
buffer_write_start_pos_[fid] = bin_size;
auto num_bin = this->train_data_->FeatureNumBin(fid);
if (this->train_data_->FeatureBinMapper(fid)->GetMostFreqBin() == 0) {
num_bin -= 1;
}
bin_size += num_bin * kHistEntrySize;
}
}
// get buffer_read_start_pos_
bin_size = 0;
for (auto fid : feature_distribution[rank_]) {
buffer_read_start_pos_[fid] = bin_size;
auto num_bin = this->train_data_->FeatureNumBin(fid);
if (this->train_data_->FeatureBinMapper(fid)->GetMostFreqBin() == 0) {
num_bin -= 1;
}
bin_size += num_bin * kHistEntrySize;
}
// sync global data sumup info
std::tuple<data_size_t, double, double> data(this->smaller_leaf_splits_->num_data_in_leaf(),
this->smaller_leaf_splits_->sum_gradients(), this->smaller_leaf_splits_->sum_hessians());
int size = sizeof(data);
std::memcpy(input_buffer_.data(), &data, size);
// global sumup reduce
Network::Allreduce(input_buffer_.data(), size, sizeof(std::tuple<data_size_t, double, double>), output_buffer_.data(), [](const char *src, char *dst, int type_size, comm_size_t len) {
comm_size_t used_size = 0;
const std::tuple<data_size_t, double, double> *p1;
std::tuple<data_size_t, double, double> *p2;
while (used_size < len) {
p1 = reinterpret_cast<const std::tuple<data_size_t, double, double> *>(src);
p2 = reinterpret_cast<std::tuple<data_size_t, double, double> *>(dst);
std::get<0>(*p2) = std::get<0>(*p2) + std::get<0>(*p1);
std::get<1>(*p2) = std::get<1>(*p2) + std::get<1>(*p1);
std::get<2>(*p2) = std::get<2>(*p2) + std::get<2>(*p1);
src += type_size;
dst += type_size;
used_size += type_size;
}
});
// copy back
std::memcpy(reinterpret_cast<void*>(&data), output_buffer_.data(), size);
// set global sumup info
this->smaller_leaf_splits_->Init(std::get<1>(data), std::get<2>(data));
// init global data count in leaf
global_data_count_in_leaf_[0] = std::get<0>(data);
}
template <typename TREELEARNER_T>
void DataParallelTreeLearner<TREELEARNER_T>::FindBestSplits() {
TREELEARNER_T::ConstructHistograms(
this->col_sampler_.is_feature_used_bytree(), true);
// construct local histograms
#pragma omp parallel for schedule(static)
for (int feature_index = 0; feature_index < this->num_features_; ++feature_index) {
if (this->col_sampler_.is_feature_used_bytree()[feature_index] == false)
continue;
// copy to buffer
std::memcpy(input_buffer_.data() + buffer_write_start_pos_[feature_index],
this->smaller_leaf_histogram_array_[feature_index].RawData(),
this->smaller_leaf_histogram_array_[feature_index].SizeOfHistgram());
}
// Reduce scatter for histogram
Network::ReduceScatter(input_buffer_.data(), reduce_scatter_size_, sizeof(hist_t), block_start_.data(),
block_len_.data(), output_buffer_.data(), static_cast<comm_size_t>(output_buffer_.size()), &HistogramSumReducer);
this->FindBestSplitsFromHistograms(
this->col_sampler_.is_feature_used_bytree(), true);
}
template <typename TREELEARNER_T>
void DataParallelTreeLearner<TREELEARNER_T>::FindBestSplitsFromHistograms(const std::vector<int8_t>&, bool) {
std::vector<SplitInfo> smaller_bests_per_thread(this->share_state_->num_threads);
std::vector<SplitInfo> larger_bests_per_thread(this->share_state_->num_threads);
std::vector<int8_t> smaller_node_used_features =
this->col_sampler_.GetByNode();
std::vector<int8_t> larger_node_used_features =
this->col_sampler_.GetByNode();
OMP_INIT_EX();
#pragma omp parallel for schedule(static)
for (int feature_index = 0; feature_index < this->num_features_; ++feature_index) {
OMP_LOOP_EX_BEGIN();
if (!is_feature_aggregated_[feature_index]) continue;
const int tid = omp_get_thread_num();
const int real_feature_index = this->train_data_->RealFeatureIndex(feature_index);
// restore global histograms from buffer
this->smaller_leaf_histogram_array_[feature_index].FromMemory(
output_buffer_.data() + buffer_read_start_pos_[feature_index]);
this->train_data_->FixHistogram(feature_index,
this->smaller_leaf_splits_->sum_gradients(), this->smaller_leaf_splits_->sum_hessians(),
this->smaller_leaf_histogram_array_[feature_index].RawData());
this->ComputeBestSplitForFeature(
this->smaller_leaf_histogram_array_, feature_index, real_feature_index,
smaller_node_used_features[feature_index],
GetGlobalDataCountInLeaf(this->smaller_leaf_splits_->leaf_index()),
this->smaller_leaf_splits_.get(),
&smaller_bests_per_thread[tid]);
// only root leaf
if (this->larger_leaf_splits_ == nullptr || this->larger_leaf_splits_->leaf_index() < 0) continue;
// construct histgroms for large leaf, we init larger leaf as the parent, so we can just subtract the smaller leaf's histograms
this->larger_leaf_histogram_array_[feature_index].Subtract(
this->smaller_leaf_histogram_array_[feature_index]);
this->ComputeBestSplitForFeature(
this->larger_leaf_histogram_array_, feature_index, real_feature_index,
larger_node_used_features[feature_index],
GetGlobalDataCountInLeaf(this->larger_leaf_splits_->leaf_index()),
this->larger_leaf_splits_.get(),
&larger_bests_per_thread[tid]);
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
auto smaller_best_idx = ArrayArgs<SplitInfo>::ArgMax(smaller_bests_per_thread);
int leaf = this->smaller_leaf_splits_->leaf_index();
this->best_split_per_leaf_[leaf] = smaller_bests_per_thread[smaller_best_idx];
if (this->larger_leaf_splits_ != nullptr && this->larger_leaf_splits_->leaf_index() >= 0) {
leaf = this->larger_leaf_splits_->leaf_index();
auto larger_best_idx = ArrayArgs<SplitInfo>::ArgMax(larger_bests_per_thread);
this->best_split_per_leaf_[leaf] = larger_bests_per_thread[larger_best_idx];
}
SplitInfo smaller_best_split, larger_best_split;
smaller_best_split = this->best_split_per_leaf_[this->smaller_leaf_splits_->leaf_index()];
// find local best split for larger leaf
if (this->larger_leaf_splits_->leaf_index() >= 0) {
larger_best_split = this->best_split_per_leaf_[this->larger_leaf_splits_->leaf_index()];
}
// sync global best info
SyncUpGlobalBestSplit(input_buffer_.data(), input_buffer_.data(), &smaller_best_split, &larger_best_split, this->config_->max_cat_threshold);
// set best split
this->best_split_per_leaf_[this->smaller_leaf_splits_->leaf_index()] = smaller_best_split;
if (this->larger_leaf_splits_->leaf_index() >= 0) {
this->best_split_per_leaf_[this->larger_leaf_splits_->leaf_index()] = larger_best_split;
}
}
template <typename TREELEARNER_T>
void DataParallelTreeLearner<TREELEARNER_T>::Split(Tree* tree, int best_Leaf, int* left_leaf, int* right_leaf) {
TREELEARNER_T::SplitInner(tree, best_Leaf, left_leaf, right_leaf, false);
const SplitInfo& best_split_info = this->best_split_per_leaf_[best_Leaf];
// need update global number of data in leaf
global_data_count_in_leaf_[*left_leaf] = best_split_info.left_count;
global_data_count_in_leaf_[*right_leaf] = best_split_info.right_count;
}
// instantiate template classes, otherwise linker cannot find the code
template class DataParallelTreeLearner<GPUTreeLearner>;
template class DataParallelTreeLearner<SerialTreeLearner>;
} // namespace LightGBM
| 1 | 24,142 | maybe we can do this in Init function? | microsoft-LightGBM | cpp |
@@ -2086,10 +2086,15 @@ func (wh *WorkflowHandler) ResetWorkflowExecution(ctx context.Context, request *
if request == nil {
return nil, errRequestNotSet
}
-
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
+ if request.GetRequestId() == "" {
+ return nil, errRequestIDNotSet
+ }
+ if len(request.GetRequestId()) > wh.config.MaxIDLengthLimit() {
+ return nil, errRequestIDTooLong
+ }
if err := wh.validateExecution(request.WorkflowExecution); err != nil {
return nil, err | 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 frontend
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/pborman/uuid"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
filterpb "go.temporal.io/api/filter/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
"go.temporal.io/api/workflowservice/v1"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"go.temporal.io/server/common/persistence/visibility/manager"
historyspb "go.temporal.io/server/api/history/v1"
"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/api/matchingservice/v1"
tokenspb "go.temporal.io/server/api/token/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/archiver"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/enums"
"go.temporal.io/server/common/failure"
"go.temporal.io/server/common/headers"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/resource"
"go.temporal.io/server/common/rpc/interceptor"
"go.temporal.io/server/common/searchattribute"
)
const (
// HealthStatusOK is used when this node is healthy and rpc requests are allowed
HealthStatusOK HealthStatus = iota + 1
// HealthStatusShuttingDown is used when the rpc handler is shutting down
HealthStatusShuttingDown
)
const (
serviceName = "temporal.api.workflowservice.v1.WorkflowService"
)
var _ Handler = (*WorkflowHandler)(nil)
var (
minTime = time.Unix(0, 0).UTC()
maxTime = time.Date(2100, 1, 1, 1, 0, 0, 0, time.UTC)
)
type (
// WorkflowHandler - gRPC handler interface for workflowservice
WorkflowHandler struct {
resource.Resource
status int32
healthStatus int32
tokenSerializer common.TaskTokenSerializer
config *Config
versionChecker headers.VersionChecker
namespaceHandler namespace.Handler
getDefaultWorkflowRetrySettings dynamicconfig.MapPropertyFnWithNamespaceFilter
visibilityMrg manager.VisibilityManager
}
// HealthStatus is an enum that refers to the rpc handler health status
HealthStatus int32
)
var (
frontendServiceRetryPolicy = common.CreateFrontendServiceRetryPolicy()
)
// NewWorkflowHandler creates a gRPC handler for workflowservice
func NewWorkflowHandler(
resource resource.Resource,
config *Config,
namespaceReplicationQueue persistence.NamespaceReplicationQueue,
visibilityMrg manager.VisibilityManager,
) *WorkflowHandler {
handler := &WorkflowHandler{
Resource: resource,
status: common.DaemonStatusInitialized,
config: config,
healthStatus: int32(HealthStatusOK),
tokenSerializer: common.NewProtoTaskTokenSerializer(),
versionChecker: headers.NewDefaultVersionChecker(),
namespaceHandler: namespace.NewHandler(
config.MaxBadBinaries,
resource.GetLogger(),
resource.GetMetadataManager(),
resource.GetClusterMetadata(),
namespace.NewNamespaceReplicator(namespaceReplicationQueue, resource.GetLogger()),
resource.GetArchivalMetadata(),
resource.GetArchiverProvider(),
),
getDefaultWorkflowRetrySettings: config.DefaultWorkflowRetryPolicy,
visibilityMrg: visibilityMrg,
}
return handler
}
// Start starts the handler
func (wh *WorkflowHandler) Start() {
if !atomic.CompareAndSwapInt32(
&wh.status,
common.DaemonStatusInitialized,
common.DaemonStatusStarted,
) {
return
}
}
// Stop stops the handler
func (wh *WorkflowHandler) Stop() {
if !atomic.CompareAndSwapInt32(
&wh.status,
common.DaemonStatusStarted,
common.DaemonStatusStopped,
) {
return
}
}
// UpdateHealthStatus sets the health status for this rpc handler.
// This health status will be used within the rpc health check handler
func (wh *WorkflowHandler) UpdateHealthStatus(status HealthStatus) {
atomic.StoreInt32(&wh.healthStatus, int32(status))
}
func (wh *WorkflowHandler) isStopped() bool {
return atomic.LoadInt32(&wh.status) == common.DaemonStatusStopped
}
// GetResource return resource
func (wh *WorkflowHandler) GetResource() resource.Resource {
return wh.Resource
}
// GetConfig return config
func (wh *WorkflowHandler) GetConfig() *Config {
return wh.config
}
// Check is from: https://github.com/grpc/grpc/blob/master/doc/health-checking.md
func (wh *WorkflowHandler) Check(_ context.Context, request *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
wh.GetLogger().Debug("Frontend service health check endpoint (gRPC) reached.")
if request.Service != serviceName {
return &healthpb.HealthCheckResponse{
Status: healthpb.HealthCheckResponse_SERVICE_UNKNOWN,
}, nil
}
status := HealthStatus(atomic.LoadInt32(&wh.healthStatus))
if status == HealthStatusOK {
return &healthpb.HealthCheckResponse{
Status: healthpb.HealthCheckResponse_SERVING,
}, nil
}
return &healthpb.HealthCheckResponse{
Status: healthpb.HealthCheckResponse_NOT_SERVING,
}, nil
}
func (wh *WorkflowHandler) Watch(*healthpb.HealthCheckRequest, healthpb.Health_WatchServer) error {
return serviceerror.NewUnimplemented("Watch is not implemented.")
}
// RegisterNamespace creates a new namespace which can be used as a container for all resources. Namespace is a top level
// entity within Temporal, used as a container for all resources like workflow executions, taskqueues, etc. Namespace
// acts as a sandbox and provides isolation for all resources within the namespace. All resources belongs to exactly one
// namespace.
func (wh *WorkflowHandler) RegisterNamespace(ctx context.Context, request *workflowservice.RegisterNamespaceRequest) (_ *workflowservice.RegisterNamespaceResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
resp, err := wh.namespaceHandler.RegisterNamespace(ctx, request)
if err != nil {
return nil, err
}
return resp, nil
}
// DescribeNamespace returns the information and configuration for a registered namespace.
func (wh *WorkflowHandler) DescribeNamespace(ctx context.Context, request *workflowservice.DescribeNamespaceRequest) (_ *workflowservice.DescribeNamespaceResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" && request.GetId() == "" {
return nil, errNamespaceNotSet
}
resp, err := wh.namespaceHandler.DescribeNamespace(ctx, request)
if err != nil {
return resp, err
}
return resp, err
}
// ListNamespaces returns the information and configuration for all namespaces.
func (wh *WorkflowHandler) ListNamespaces(ctx context.Context, request *workflowservice.ListNamespacesRequest) (_ *workflowservice.ListNamespacesResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
resp, err := wh.namespaceHandler.ListNamespaces(ctx, request)
if err != nil {
return resp, err
}
return resp, err
}
// UpdateNamespace is used to update the information and configuration for a registered namespace.
func (wh *WorkflowHandler) UpdateNamespace(ctx context.Context, request *workflowservice.UpdateNamespaceRequest) (_ *workflowservice.UpdateNamespaceResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
resp, err := wh.namespaceHandler.UpdateNamespace(ctx, request)
if err != nil {
return resp, err
}
return resp, err
}
// DeprecateNamespace us used to update status of a registered namespace to DEPRECATED. Once the namespace is deprecated
// it cannot be used to start new workflow executions. Existing workflow executions will continue to run on
// deprecated namespaces.
func (wh *WorkflowHandler) DeprecateNamespace(ctx context.Context, request *workflowservice.DeprecateNamespaceRequest) (_ *workflowservice.DeprecateNamespaceResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
resp, err := wh.namespaceHandler.DeprecateNamespace(ctx, request)
if err != nil {
return nil, err
}
return resp, err
}
// StartWorkflowExecution starts a new long running workflow instance. It will create the instance with
// 'WorkflowExecutionStarted' event in history and also schedule the first WorkflowTask for the worker to make the
// first workflow task for this instance. It will return 'WorkflowExecutionAlreadyStartedError', if an instance already
// exists with same workflowId.
func (wh *WorkflowHandler) StartWorkflowExecution(ctx context.Context, request *workflowservice.StartWorkflowExecutionRequest) (_ *workflowservice.StartWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
namespaceName := namespace.Name(request.GetNamespace())
if namespaceName.IsEmpty() {
return nil, errNamespaceNotSet
}
if len(namespaceName) > wh.config.MaxIDLengthLimit() {
return nil, errNamespaceTooLong
}
if request.GetWorkflowId() == "" {
return nil, errWorkflowIDNotSet
}
if len(request.GetWorkflowId()) > wh.config.MaxIDLengthLimit() {
return nil, errWorkflowIDTooLong
}
if err := wh.validateRetryPolicy(request.GetNamespace(), request.RetryPolicy); err != nil {
return nil, err
}
if err := backoff.ValidateSchedule(request.GetCronSchedule()); err != nil {
return nil, err
}
wh.GetLogger().Debug(
"Received StartWorkflowExecution",
tag.WorkflowID(request.GetWorkflowId()))
if request.WorkflowType == nil || request.WorkflowType.GetName() == "" {
return nil, errWorkflowTypeNotSet
}
if len(request.WorkflowType.GetName()) > wh.config.MaxIDLengthLimit() {
return nil, errWorkflowTypeTooLong
}
if err := wh.validateTaskQueue(request.TaskQueue); err != nil {
return nil, err
}
if err := wh.validateStartWorkflowTimeouts(request); err != nil {
return nil, err
}
if request.GetRequestId() == "" {
return nil, errRequestIDNotSet
}
if len(request.GetRequestId()) > wh.config.MaxIDLengthLimit() {
return nil, errRequestIDTooLong
}
enums.SetDefaultWorkflowIdReusePolicy(&request.WorkflowIdReusePolicy)
wh.GetLogger().Debug("Start workflow execution request namespace", tag.WorkflowNamespace(namespaceName.String()))
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
wh.GetLogger().Debug("Start workflow execution request namespaceID", tag.WorkflowNamespaceID(namespaceID.String()))
resp, err := wh.GetHistoryClient().StartWorkflowExecution(ctx, common.CreateHistoryStartWorkflowRequest(namespaceID.String(), request, nil, time.Now().UTC()))
if err != nil {
return nil, err
}
return &workflowservice.StartWorkflowExecutionResponse{RunId: resp.GetRunId()}, nil
}
// GetWorkflowExecutionHistory returns the history of specified workflow execution. It fails with 'EntityNotExistError' if speficied workflow
// execution in unknown to the service.
func (wh *WorkflowHandler) GetWorkflowExecutionHistory(ctx context.Context, request *workflowservice.GetWorkflowExecutionHistoryRequest) (_ *workflowservice.GetWorkflowExecutionHistoryResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateExecution(request.Execution); err != nil {
return nil, err
}
if request.GetMaximumPageSize() <= 0 {
request.MaximumPageSize = int32(wh.config.HistoryMaxPageSize(request.GetNamespace()))
}
enums.SetDefaultHistoryEventFilterType(&request.HistoryEventFilterType)
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
// force limit page size if exceed
if request.GetMaximumPageSize() > common.GetHistoryMaxPageSize {
wh.GetThrottledLogger().Warn("GetHistory page size is larger than threshold",
tag.WorkflowID(request.Execution.GetWorkflowId()),
tag.WorkflowRunID(request.Execution.GetRunId()),
tag.WorkflowNamespaceID(namespaceID.String()), tag.WorkflowSize(int64(request.GetMaximumPageSize())))
request.MaximumPageSize = common.GetHistoryMaxPageSize
}
if !request.GetSkipArchival() {
enableArchivalRead := wh.GetArchivalMetadata().GetHistoryConfig().ReadEnabled()
historyArchived := wh.historyArchived(ctx, request, namespaceID)
if enableArchivalRead && historyArchived {
return wh.getArchivedHistory(ctx, request, namespaceID)
}
}
// this function returns the following 7 things,
// 1. the current branch token (to use to retrieve history events)
// 2. the workflow run ID
// 3. the last first event ID (the event ID of the last batch of events in the history)
// 4. the last first event transaction id
// 5. the next event ID
// 6. whether the workflow is running
// 7. error if any
queryHistory := func(
namespaceUUID namespace.ID,
execution *commonpb.WorkflowExecution,
expectedNextEventID int64,
currentBranchToken []byte,
) ([]byte, string, int64, int64, int64, bool, error) {
response, err := wh.GetHistoryClient().PollMutableState(ctx, &historyservice.PollMutableStateRequest{
NamespaceId: namespaceUUID.String(),
Execution: execution,
ExpectedNextEventId: expectedNextEventID,
CurrentBranchToken: currentBranchToken,
})
if err != nil {
return nil, "", 0, 0, 0, false, err
}
isWorkflowRunning := response.GetWorkflowStatus() == enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING
return response.CurrentBranchToken,
response.Execution.GetRunId(),
response.GetLastFirstEventId(),
response.GetLastFirstEventTxnId(),
response.GetNextEventId(),
isWorkflowRunning,
nil
}
isLongPoll := request.GetWaitNewEvent()
isCloseEventOnly := request.GetHistoryEventFilterType() == enumspb.HISTORY_EVENT_FILTER_TYPE_CLOSE_EVENT
execution := request.Execution
var continuationToken *tokenspb.HistoryContinuation
var runID string
lastFirstEventID := common.FirstEventID
lastFirstEventTxnID := int64(0)
var nextEventID int64
var isWorkflowRunning bool
// process the token for paging
queryNextEventID := common.EndEventID
if request.NextPageToken != nil {
continuationToken, err = deserializeHistoryToken(request.NextPageToken)
if err != nil {
return nil, errInvalidNextPageToken
}
if execution.GetRunId() != "" && execution.GetRunId() != continuationToken.GetRunId() {
return nil, errNextPageTokenRunIDMismatch
}
execution.RunId = continuationToken.GetRunId()
// we need to update the current next event ID and whether workflow is running
if len(continuationToken.PersistenceToken) == 0 && isLongPoll && continuationToken.IsWorkflowRunning {
if !isCloseEventOnly {
queryNextEventID = continuationToken.GetNextEventId()
}
continuationToken.BranchToken, _, lastFirstEventID, lastFirstEventTxnID, nextEventID, isWorkflowRunning, err =
queryHistory(namespaceID, execution, queryNextEventID, continuationToken.BranchToken)
if err != nil {
return nil, err
}
continuationToken.FirstEventId = continuationToken.GetNextEventId()
continuationToken.NextEventId = nextEventID
continuationToken.IsWorkflowRunning = isWorkflowRunning
}
} else {
continuationToken = &tokenspb.HistoryContinuation{}
if !isCloseEventOnly {
queryNextEventID = common.FirstEventID
}
continuationToken.BranchToken, runID, lastFirstEventID, lastFirstEventTxnID, nextEventID, isWorkflowRunning, err =
queryHistory(namespaceID, execution, queryNextEventID, nil)
if err != nil {
return nil, err
}
execution.RunId = runID
continuationToken.RunId = runID
continuationToken.FirstEventId = common.FirstEventID
continuationToken.NextEventId = nextEventID
continuationToken.IsWorkflowRunning = isWorkflowRunning
continuationToken.PersistenceToken = nil
}
// TODO below is a temporal solution to guard against invalid event batch
// when data inconsistency occurs
// long term solution should check event batch pointing backwards within history store
defer func() {
// lastFirstEventTxnID != 0 exists due to forward / backward compatibility
if _, ok := retError.(*serviceerror.DataLoss); ok && lastFirstEventTxnID != 0 {
_, _ = wh.GetExecutionManager().TrimHistoryBranch(&persistence.TrimHistoryBranchRequest{
ShardID: common.WorkflowIDToHistoryShard(namespaceID.String(), execution.GetWorkflowId(), wh.config.NumHistoryShards),
BranchToken: continuationToken.BranchToken,
NodeID: lastFirstEventID,
TransactionID: lastFirstEventTxnID,
})
}
}()
rawHistoryQueryEnabled := wh.config.SendRawWorkflowHistory(request.GetNamespace())
history := &historypb.History{}
history.Events = []*historypb.HistoryEvent{}
var historyBlob []*commonpb.DataBlob
if isCloseEventOnly {
if !isWorkflowRunning {
if rawHistoryQueryEnabled {
historyBlob, _, err = wh.getRawHistory(
wh.metricsScope(ctx),
namespaceID,
*execution,
lastFirstEventID,
nextEventID,
request.GetMaximumPageSize(),
nil,
continuationToken.TransientWorkflowTask,
continuationToken.BranchToken,
)
if err != nil {
return nil, err
}
// since getHistory func will not return empty history, so the below is safe
historyBlob = historyBlob[len(historyBlob)-1:]
} else {
history, _, err = wh.getHistory(
wh.metricsScope(ctx),
namespaceID,
namespace.Name(request.GetNamespace()),
*execution,
lastFirstEventID,
nextEventID,
request.GetMaximumPageSize(),
nil,
continuationToken.TransientWorkflowTask,
continuationToken.BranchToken,
)
if err != nil {
return nil, err
}
// since getHistory func will not return empty history, so the below is safe
history.Events = history.Events[len(history.Events)-1 : len(history.Events)]
}
continuationToken = nil
} else if isLongPoll {
// set the persistence token to be nil so next time we will query history for updates
continuationToken.PersistenceToken = nil
} else {
continuationToken = nil
}
} else {
// return all events
if continuationToken.FirstEventId >= continuationToken.NextEventId {
// currently there is no new event
history.Events = []*historypb.HistoryEvent{}
if !isWorkflowRunning {
continuationToken = nil
}
} else {
if rawHistoryQueryEnabled {
historyBlob, continuationToken.PersistenceToken, err = wh.getRawHistory(
wh.metricsScope(ctx),
namespaceID,
*execution,
continuationToken.FirstEventId,
continuationToken.NextEventId,
request.GetMaximumPageSize(),
continuationToken.PersistenceToken,
continuationToken.TransientWorkflowTask,
continuationToken.BranchToken,
)
} else {
history, continuationToken.PersistenceToken, err = wh.getHistory(
wh.metricsScope(ctx),
namespaceID,
namespace.Name(request.GetNamespace()),
*execution,
continuationToken.FirstEventId,
continuationToken.NextEventId,
request.GetMaximumPageSize(),
continuationToken.PersistenceToken,
continuationToken.TransientWorkflowTask,
continuationToken.BranchToken,
)
}
if err != nil {
return nil, err
}
// here, for long pull on history events, we need to intercept the paging token from cassandra
// and do something clever
if len(continuationToken.PersistenceToken) == 0 && (!continuationToken.IsWorkflowRunning || !isLongPoll) {
// meaning, there is no more history to be returned
continuationToken = nil
}
}
}
nextToken, err := serializeHistoryToken(continuationToken)
if err != nil {
return nil, err
}
// Backwards-compatibility fix for retry events after #1866: older SDKs don't know how to "follow"
// subsequent runs linked in WorkflowExecutionFailed or TimedOut events, so they'll get the wrong result
// when trying to "get" the result of a workflow run. (This applies to cron runs also but "get" on a cron
// workflow isn't really sensible.)
//
// To handle this in a backwards-compatible way, we'll pretend the completion event is actually
// ContinuedAsNew, if it's Failed or TimedOut. We want to do this only when the client is looking for a
// completion event, and not when it's getting the history to display for other purposes. The best signal
// for that purpose is `isCloseEventOnly`. (We can't use `isLongPoll` also because in some cases, older
// versions of the Java SDK don't set that flag.)
//
// TODO: We can remove this once we no longer support SDK versions prior to around September 2021.
// Revisit this once we have an SDK deprecation policy.
if isCloseEventOnly &&
!wh.versionChecker.ClientSupportsFeature(ctx, headers.FeatureFollowsNextRunID) &&
len(history.Events) > 0 {
lastEvent := history.Events[len(history.Events)-1]
fakeEvent, err := wh.makeFakeContinuedAsNewEvent(ctx, lastEvent)
if err != nil {
return nil, err
}
if fakeEvent != nil {
history.Events[len(history.Events)-1] = fakeEvent
}
}
return &workflowservice.GetWorkflowExecutionHistoryResponse{
History: history,
RawHistory: historyBlob,
NextPageToken: nextToken,
Archived: false,
}, nil
}
// PollWorkflowTaskQueue is called by application worker to process WorkflowTask from a specific task queue. A
// WorkflowTask is dispatched to callers for active workflow executions, with pending workflow tasks.
// Application is then expected to call 'RespondWorkflowTaskCompleted' API when it is done processing the WorkflowTask.
// It will also create a 'WorkflowTaskStarted' event in the history for that session before handing off WorkflowTask to
// application worker.
func (wh *WorkflowHandler) PollWorkflowTaskQueue(ctx context.Context, request *workflowservice.PollWorkflowTaskQueueRequest) (_ *workflowservice.PollWorkflowTaskQueueResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
callTime := time.Now().UTC()
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
wh.GetLogger().Debug("Received PollWorkflowTaskQueue")
if err := common.ValidateLongPollContextTimeout(
ctx,
"PollWorkflowTaskQueue",
wh.GetThrottledLogger(),
); err != nil {
return nil, err
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if len(request.GetNamespace()) > wh.config.MaxIDLengthLimit() {
return nil, errNamespaceTooLong
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
if err := wh.validateTaskQueue(request.TaskQueue); err != nil {
return nil, err
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespace(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
namespaceID := namespaceEntry.ID()
wh.GetLogger().Debug("Poll workflow task queue.", tag.WorkflowNamespace(namespaceEntry.Name().String()), tag.WorkflowNamespaceID(namespaceID.String()))
if err := wh.checkBadBinary(namespaceEntry, request.GetBinaryChecksum()); err != nil {
return nil, err
}
pollerID := uuid.New()
var matchingResp *matchingservice.PollWorkflowTaskQueueResponse
op := func() error {
var err error
matchingResp, err = wh.GetMatchingClient().PollWorkflowTaskQueue(ctx, &matchingservice.PollWorkflowTaskQueueRequest{
NamespaceId: namespaceID.String(),
PollerId: pollerID,
PollRequest: request,
})
return err
}
err = backoff.Retry(op, frontendServiceRetryPolicy, common.IsServiceTransientError)
if err != nil {
contextWasCanceled := wh.cancelOutstandingPoll(ctx, namespaceID, enumspb.TASK_QUEUE_TYPE_WORKFLOW, request.TaskQueue, pollerID)
if contextWasCanceled {
// Clear error as we don't want to report context cancellation error to count against our SLA.
// It doesn't matter what to return here, client has already gone. But (nil,nil) is invalid gogo return pair.
return &workflowservice.PollWorkflowTaskQueueResponse{}, nil
}
// For all other errors log an error and return it back to client.
ctxTimeout := "not-set"
ctxDeadline, ok := ctx.Deadline()
if ok {
ctxTimeout = ctxDeadline.Sub(callTime).String()
}
wh.GetLogger().Error("Unable to call matching.PollWorkflowTaskQueue.",
tag.WorkflowTaskQueueName(request.GetTaskQueue().GetName()),
tag.Timeout(ctxTimeout),
tag.Error(err))
return nil, err
}
resp, err := wh.createPollWorkflowTaskQueueResponse(ctx, namespaceID, matchingResp, matchingResp.GetBranchToken())
if err != nil {
return nil, err
}
return resp, nil
}
// RespondWorkflowTaskCompleted is called by application worker to complete a WorkflowTask handed as a result of
// 'PollWorkflowTaskQueue' API call. Completing a WorkflowTask will result in new events for the workflow execution and
// potentially new ActivityTask being created for corresponding commands. It will also create a WorkflowTaskCompleted
// event in the history for that session. Use the 'taskToken' provided as response of PollWorkflowTaskQueue API call
// for completing the WorkflowTask.
// The response could contain a new workflow task if there is one or if the request asking for one.
func (wh *WorkflowHandler) RespondWorkflowTaskCompleted(
ctx context.Context,
request *workflowservice.RespondWorkflowTaskCompletedRequest,
) (_ *workflowservice.RespondWorkflowTaskCompletedResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
taskToken, err := wh.tokenSerializer.Deserialize(request.TaskToken)
if err != nil {
return nil, err
}
namespaceId := namespace.ID(taskToken.GetNamespaceId())
if namespaceId.IsEmpty() {
return nil, errNamespaceNotSet
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceId)
if err != nil {
return nil, err
}
namespaceName := namespaceEntry.Name()
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.checkNamespaceMatch(request.Namespace, namespaceName); err != nil {
return nil, err
}
histResp, err := wh.GetHistoryClient().RespondWorkflowTaskCompleted(ctx, &historyservice.RespondWorkflowTaskCompletedRequest{
NamespaceId: namespaceId.String(),
CompleteRequest: request},
)
if err != nil {
return nil, err
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
completedResp := &workflowservice.RespondWorkflowTaskCompletedResponse{}
if request.GetReturnNewWorkflowTask() && histResp != nil && histResp.StartedResponse != nil {
taskToken := &tokenspb.Task{
NamespaceId: taskToken.GetNamespaceId(),
WorkflowId: taskToken.GetWorkflowId(),
RunId: taskToken.GetRunId(),
ScheduleId: histResp.StartedResponse.GetScheduledEventId(),
ScheduleAttempt: histResp.StartedResponse.GetAttempt(),
}
token, _ := wh.tokenSerializer.Serialize(taskToken)
workflowExecution := &commonpb.WorkflowExecution{
WorkflowId: taskToken.GetWorkflowId(),
RunId: taskToken.GetRunId(),
}
matchingResp := common.CreateMatchingPollWorkflowTaskQueueResponse(histResp.StartedResponse, workflowExecution, token)
newWorkflowTask, err := wh.createPollWorkflowTaskQueueResponse(ctx, namespaceId, matchingResp, matchingResp.GetBranchToken())
if err != nil {
return nil, err
}
completedResp.WorkflowTask = newWorkflowTask
}
return completedResp, nil
}
// RespondWorkflowTaskFailed is called by application worker to indicate failure. This results in
// WorkflowTaskFailedEvent written to the history and a new WorkflowTask created. This API can be used by client to
// either clear sticky taskqueue or report any panics during WorkflowTask processing. Temporal will only append first
// WorkflowTaskFailed event to the history of workflow execution for consecutive failures.
func (wh *WorkflowHandler) RespondWorkflowTaskFailed(
ctx context.Context,
request *workflowservice.RespondWorkflowTaskFailedRequest,
) (_ *workflowservice.RespondWorkflowTaskFailedResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
taskToken, err := wh.tokenSerializer.Deserialize(request.TaskToken)
if err != nil {
return nil, err
}
namespaceId := namespace.ID(taskToken.GetNamespaceId())
if namespaceId.IsEmpty() {
return nil, errNamespaceNotSet
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceId)
if err != nil {
return nil, err
}
namespaceName := namespaceEntry.Name()
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.checkNamespaceMatch(request.Namespace, namespaceName); err != nil {
return nil, err
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetFailure().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceId.String(),
taskToken.GetWorkflowId(),
taskToken.GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondWorkflowTaskFailed"),
); err != nil {
serverFailure := failure.NewServerFailure(common.FailureReasonFailureExceedsLimit, false)
serverFailure.Cause = failure.Truncate(request.Failure, sizeLimitWarn)
request.Failure = serverFailure
}
if request.GetCause() == enumspb.WORKFLOW_TASK_FAILED_CAUSE_NON_DETERMINISTIC_ERROR {
wh.GetLogger().Info("Non-Deterministic Error",
tag.WorkflowNamespaceID(taskToken.GetNamespaceId()),
tag.WorkflowID(taskToken.GetWorkflowId()),
tag.WorkflowRunID(taskToken.GetRunId()),
)
wh.metricsScope(ctx).IncCounter(metrics.ServiceErrNonDeterministicCounter)
}
_, err = wh.GetHistoryClient().RespondWorkflowTaskFailed(ctx, &historyservice.RespondWorkflowTaskFailedRequest{
NamespaceId: namespaceId.String(),
FailedRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.RespondWorkflowTaskFailedResponse{}, nil
}
// PollActivityTaskQueue is called by application worker to process ActivityTask from a specific task queue. ActivityTask
// is dispatched to callers whenever a ScheduleTask command is made for a workflow execution.
// Application is expected to call 'RespondActivityTaskCompleted' or 'RespondActivityTaskFailed' once it is done
// processing the task.
// Application also needs to call 'RecordActivityTaskHeartbeat' API within 'heartbeatTimeoutSeconds' interval to
// prevent the task from getting timed out. An event 'ActivityTaskStarted' event is also written to workflow execution
// history before the ActivityTask is dispatched to application worker.
func (wh *WorkflowHandler) PollActivityTaskQueue(ctx context.Context, request *workflowservice.PollActivityTaskQueueRequest) (_ *workflowservice.PollActivityTaskQueueResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
callTime := time.Now().UTC()
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
wh.GetLogger().Debug("Received PollActivityTaskQueue")
if err := common.ValidateLongPollContextTimeout(
ctx,
"PollActivityTaskQueue",
wh.GetThrottledLogger(),
); err != nil {
return nil, err
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if len(request.GetNamespace()) > wh.config.MaxIDLengthLimit() {
return nil, errNamespaceTooLong
}
if err := wh.validateTaskQueue(request.TaskQueue); err != nil {
return nil, err
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
pollerID := uuid.New()
var matchingResponse *matchingservice.PollActivityTaskQueueResponse
op := func() error {
var err error
matchingResponse, err = wh.GetMatchingClient().PollActivityTaskQueue(ctx, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID.String(),
PollerId: pollerID,
PollRequest: request,
})
return err
}
err = backoff.Retry(op, frontendServiceRetryPolicy, common.IsServiceTransientError)
if err != nil {
contextWasCanceled := wh.cancelOutstandingPoll(ctx, namespaceID, enumspb.TASK_QUEUE_TYPE_ACTIVITY, request.TaskQueue, pollerID)
if contextWasCanceled {
// Clear error as we don't want to report context cancellation error to count against our SLA.
// It doesn't matter what to return here, client has already gone. But (nil,nil) is invalid gogo return pair.
return &workflowservice.PollActivityTaskQueueResponse{}, nil
}
// For all other errors log an error and return it back to client.
ctxTimeout := "not-set"
ctxDeadline, ok := ctx.Deadline()
if ok {
ctxTimeout = ctxDeadline.Sub(callTime).String()
}
wh.GetLogger().Error("Unable to call matching.PollActivityTaskQueue.",
tag.WorkflowTaskQueueName(request.GetTaskQueue().GetName()),
tag.Timeout(ctxTimeout),
tag.Error(err))
return nil, err
}
return &workflowservice.PollActivityTaskQueueResponse{
TaskToken: matchingResponse.TaskToken,
WorkflowExecution: matchingResponse.WorkflowExecution,
ActivityId: matchingResponse.ActivityId,
ActivityType: matchingResponse.ActivityType,
Input: matchingResponse.Input,
ScheduledTime: matchingResponse.ScheduledTime,
ScheduleToCloseTimeout: matchingResponse.ScheduleToCloseTimeout,
StartedTime: matchingResponse.StartedTime,
StartToCloseTimeout: matchingResponse.StartToCloseTimeout,
HeartbeatTimeout: matchingResponse.HeartbeatTimeout,
Attempt: matchingResponse.Attempt,
CurrentAttemptScheduledTime: matchingResponse.CurrentAttemptScheduledTime,
HeartbeatDetails: matchingResponse.HeartbeatDetails,
WorkflowType: matchingResponse.WorkflowType,
WorkflowNamespace: matchingResponse.WorkflowNamespace,
Header: matchingResponse.Header,
}, nil
}
// RecordActivityTaskHeartbeat is called by application worker while it is processing an ActivityTask. If worker fails
// to heartbeat within 'heartbeatTimeoutSeconds' interval for the ActivityTask, then it will be marked as timedout and
// 'ActivityTaskTimedOut' event will be written to the workflow history. Calling 'RecordActivityTaskHeartbeat' will
// fail with 'EntityNotExistsError' in such situations. Use the 'taskToken' provided as response of
// PollActivityTaskQueue API call for heartbeating.
func (wh *WorkflowHandler) RecordActivityTaskHeartbeat(ctx context.Context, request *workflowservice.RecordActivityTaskHeartbeatRequest) (_ *workflowservice.RecordActivityTaskHeartbeatResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
wh.GetLogger().Debug("Received RecordActivityTaskHeartbeat")
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
taskToken, err := wh.tokenSerializer.Deserialize(request.TaskToken)
if err != nil {
return nil, err
}
namespaceId := namespace.ID(taskToken.GetNamespaceId())
if namespaceId.IsEmpty() {
return nil, errNamespaceNotSet
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceId)
if err != nil {
return nil, err
}
if wh.isStopped() {
return nil, errShuttingDown
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetDetails().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceId.String(),
taskToken.GetWorkflowId(),
taskToken.GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RecordActivityTaskHeartbeat"),
); err != nil {
// heartbeat details exceed size limit, we would fail the activity immediately with explicit error reason
failRequest := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: request.TaskToken,
Failure: failure.NewServerFailure(common.FailureReasonHeartbeatExceedsLimit, true),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceId.String(),
FailedRequest: failRequest,
})
if err != nil {
return nil, err
}
return &workflowservice.RecordActivityTaskHeartbeatResponse{CancelRequested: true}, nil
}
resp, err := wh.GetHistoryClient().RecordActivityTaskHeartbeat(ctx, &historyservice.RecordActivityTaskHeartbeatRequest{
NamespaceId: namespaceId.String(),
HeartbeatRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.RecordActivityTaskHeartbeatResponse{CancelRequested: resp.GetCancelRequested()}, nil
}
// RecordActivityTaskHeartbeatById is called by application worker while it is processing an ActivityTask. If worker fails
// to heartbeat within 'heartbeatTimeoutSeconds' interval for the ActivityTask, then it will be marked as timedout and
// 'ActivityTaskTimedOut' event will be written to the workflow history. Calling 'RecordActivityTaskHeartbeatById' will
// fail with 'EntityNotExistsError' in such situations. Instead of using 'taskToken' like in RecordActivityTaskHeartbeat,
// use Namespace, WorkflowID and ActivityID
func (wh *WorkflowHandler) RecordActivityTaskHeartbeatById(ctx context.Context, request *workflowservice.RecordActivityTaskHeartbeatByIdRequest) (_ *workflowservice.RecordActivityTaskHeartbeatByIdResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
wh.GetLogger().Debug("Received RecordActivityTaskHeartbeatById")
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
workflowID := request.GetWorkflowId()
runID := request.GetRunId() // runID is optional so can be empty
activityID := request.GetActivityId()
if namespaceID.IsEmpty() {
return nil, errNamespaceNotSet
}
if workflowID == "" {
return nil, errWorkflowIDNotSet
}
if activityID == "" {
return nil, errActivityIDNotSet
}
taskToken := &tokenspb.Task{
NamespaceId: namespaceID.String(),
RunId: runID,
WorkflowId: workflowID,
ScheduleId: common.EmptyEventID,
ActivityId: activityID,
ScheduleAttempt: 1,
}
token, err := wh.tokenSerializer.Serialize(taskToken)
if err != nil {
return nil, err
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetDetails().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
taskToken.GetWorkflowId(),
taskToken.GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RecordActivityTaskHeartbeatById"),
); err != nil {
// heartbeat details exceed size limit, we would fail the activity immediately with explicit error reason
failRequest := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: token,
Failure: failure.NewServerFailure(common.FailureReasonHeartbeatExceedsLimit, true),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceID.String(),
FailedRequest: failRequest,
})
if err != nil {
return nil, err
}
return &workflowservice.RecordActivityTaskHeartbeatByIdResponse{CancelRequested: true}, nil
}
req := &workflowservice.RecordActivityTaskHeartbeatRequest{
TaskToken: token,
Details: request.Details,
Identity: request.Identity,
}
resp, err := wh.GetHistoryClient().RecordActivityTaskHeartbeat(ctx, &historyservice.RecordActivityTaskHeartbeatRequest{
NamespaceId: namespaceID.String(),
HeartbeatRequest: req,
})
if err != nil {
return nil, err
}
return &workflowservice.RecordActivityTaskHeartbeatByIdResponse{CancelRequested: resp.GetCancelRequested()}, nil
}
// RespondActivityTaskCompleted is called by application worker when it is done processing an ActivityTask. It will
// result in a new 'ActivityTaskCompleted' event being written to the workflow history and a new WorkflowTask
// created for the workflow so new commands could be made. Use the 'taskToken' provided as response of
// PollActivityTaskQueue API call for completion. It fails with 'NotFoundFailure' if the taskToken is not valid
// anymore due to activity timeout.
func (wh *WorkflowHandler) RespondActivityTaskCompleted(
ctx context.Context,
request *workflowservice.RespondActivityTaskCompletedRequest,
) (_ *workflowservice.RespondActivityTaskCompletedResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
taskToken, err := wh.tokenSerializer.Deserialize(request.TaskToken)
if err != nil {
return nil, err
}
namespaceId := namespace.ID(taskToken.GetNamespaceId())
if namespaceId.IsEmpty() {
return nil, errNamespaceNotSet
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceId)
if err != nil {
return nil, err
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
namespaceName := namespaceEntry.Name()
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.checkNamespaceMatch(request.Namespace, namespaceName); err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetResult().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceId.String(),
taskToken.GetWorkflowId(),
taskToken.GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondActivityTaskCompleted"),
); err != nil {
// result exceeds blob size limit, we would record it as failure
failRequest := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: request.TaskToken,
Failure: failure.NewServerFailure(common.FailureReasonCompleteResultExceedsLimit, true),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceId.String(),
FailedRequest: failRequest,
})
if err != nil {
return nil, err
}
} else {
_, err = wh.GetHistoryClient().RespondActivityTaskCompleted(ctx, &historyservice.RespondActivityTaskCompletedRequest{
NamespaceId: namespaceId.String(),
CompleteRequest: request,
})
if err != nil {
return nil, err
}
}
return &workflowservice.RespondActivityTaskCompletedResponse{}, nil
}
// RespondActivityTaskCompletedById is called by application worker when it is done processing an ActivityTask.
// It will result in a new 'ActivityTaskCompleted' event being written to the workflow history and a new WorkflowTask
// created for the workflow so new commands could be made. Similar to RespondActivityTaskCompleted but use Namespace,
// WorkflowId and ActivityId instead of 'taskToken' for completion. It fails with 'NotFoundFailure'
// if the these Ids are not valid anymore due to activity timeout.
func (wh *WorkflowHandler) RespondActivityTaskCompletedById(ctx context.Context, request *workflowservice.RespondActivityTaskCompletedByIdRequest) (_ *workflowservice.RespondActivityTaskCompletedByIdResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
workflowID := request.GetWorkflowId()
runID := request.GetRunId() // runID is optional so can be empty
activityID := request.GetActivityId()
if namespaceID.IsEmpty() {
return nil, errNamespaceNotSet
}
if workflowID == "" {
return nil, errWorkflowIDNotSet
}
if activityID == "" {
return nil, errActivityIDNotSet
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
taskToken := &tokenspb.Task{
NamespaceId: namespaceID.String(),
RunId: runID,
WorkflowId: workflowID,
ScheduleId: common.EmptyEventID,
ActivityId: activityID,
ScheduleAttempt: 1,
}
token, err := wh.tokenSerializer.Serialize(taskToken)
if err != nil {
return nil, err
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetResult().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
taskToken.GetWorkflowId(),
runID,
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondActivityTaskCompletedById"),
); err != nil {
// result exceeds blob size limit, we would record it as failure
failRequest := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: token,
Failure: failure.NewServerFailure(common.FailureReasonCompleteResultExceedsLimit, true),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceID.String(),
FailedRequest: failRequest,
})
if err != nil {
return nil, err
}
} else {
req := &workflowservice.RespondActivityTaskCompletedRequest{
TaskToken: token,
Result: request.Result,
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskCompleted(ctx, &historyservice.RespondActivityTaskCompletedRequest{
NamespaceId: namespaceID.String(),
CompleteRequest: req,
})
if err != nil {
return nil, err
}
}
return &workflowservice.RespondActivityTaskCompletedByIdResponse{}, nil
}
// RespondActivityTaskFailed is called by application worker when it is done processing an ActivityTask. It will
// result in a new 'ActivityTaskFailed' event being written to the workflow history and a new WorkflowTask
// created for the workflow instance so new commands could be made. Use the 'taskToken' provided as response of
// PollActivityTaskQueue API call for completion. It fails with 'EntityNotExistsError' if the taskToken is not valid
// anymore due to activity timeout.
func (wh *WorkflowHandler) RespondActivityTaskFailed(
ctx context.Context,
request *workflowservice.RespondActivityTaskFailedRequest,
) (_ *workflowservice.RespondActivityTaskFailedResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
taskToken, err := wh.tokenSerializer.Deserialize(request.TaskToken)
if err != nil {
return nil, err
}
namespaceID := namespace.ID(taskToken.GetNamespaceId())
if namespaceID.IsEmpty() {
return nil, errNamespaceNotSet
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
if request.GetFailure() != nil && request.GetFailure().GetApplicationFailureInfo() == nil {
return nil, errFailureMustHaveApplicationFailureInfo
}
namespaceName := namespaceEntry.Name()
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.checkNamespaceMatch(request.Namespace, namespaceName); err != nil {
return nil, err
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetFailure().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
taskToken.GetWorkflowId(),
taskToken.GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondActivityTaskFailed"),
); err != nil {
serverFailure := failure.NewServerFailure(common.FailureReasonFailureExceedsLimit, false)
serverFailure.Cause = failure.Truncate(request.Failure, sizeLimitWarn)
request.Failure = serverFailure
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceID.String(),
FailedRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.RespondActivityTaskFailedResponse{}, nil
}
// RespondActivityTaskFailedById is called by application worker when it is done processing an ActivityTask.
// It will result in a new 'ActivityTaskFailed' event being written to the workflow history and a new WorkflowTask
// created for the workflow instance so new commands could be made. Similar to RespondActivityTaskFailed but use
// Namespace, WorkflowID and ActivityID instead of 'taskToken' for completion. It fails with 'EntityNotExistsError'
// if the these IDs are not valid anymore due to activity timeout.
func (wh *WorkflowHandler) RespondActivityTaskFailedById(ctx context.Context, request *workflowservice.RespondActivityTaskFailedByIdRequest) (_ *workflowservice.RespondActivityTaskFailedByIdResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
workflowID := request.GetWorkflowId()
runID := request.GetRunId() // runID is optional so can be empty
activityID := request.GetActivityId()
if namespaceID.IsEmpty() {
return nil, errNamespaceNotSet
}
if workflowID == "" {
return nil, errWorkflowIDNotSet
}
if activityID == "" {
return nil, errActivityIDNotSet
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
taskToken := &tokenspb.Task{
NamespaceId: namespaceID.String(),
RunId: runID,
WorkflowId: workflowID,
ScheduleId: common.EmptyEventID,
ActivityId: activityID,
ScheduleAttempt: 1,
}
token, err := wh.tokenSerializer.Serialize(taskToken)
if err != nil {
return nil, err
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetFailure().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
taskToken.GetWorkflowId(),
runID,
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondActivityTaskFailedById"),
); err != nil {
serverFailure := failure.NewServerFailure(common.FailureReasonFailureExceedsLimit, false)
serverFailure.Cause = failure.Truncate(request.Failure, sizeLimitWarn)
request.Failure = serverFailure
}
req := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: token,
Failure: request.GetFailure(),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceID.String(),
FailedRequest: req,
})
if err != nil {
return nil, err
}
return &workflowservice.RespondActivityTaskFailedByIdResponse{}, nil
}
// RespondActivityTaskCanceled is called by application worker when it is successfully canceled an ActivityTask. It will
// result in a new 'ActivityTaskCanceled' event being written to the workflow history and a new WorkflowTask
// created for the workflow instance so new commands could be made. Use the 'taskToken' provided as response of
// PollActivityTaskQueue API call for completion. It fails with 'EntityNotExistsError' if the taskToken is not valid
// anymore due to activity timeout.
func (wh *WorkflowHandler) RespondActivityTaskCanceled(ctx context.Context, request *workflowservice.RespondActivityTaskCanceledRequest) (_ *workflowservice.RespondActivityTaskCanceledResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
taskToken, err := wh.tokenSerializer.Deserialize(request.TaskToken)
if err != nil {
return nil, err
}
namespaceID := namespace.ID(taskToken.GetNamespaceId())
if namespaceID.IsEmpty() {
return nil, errNamespaceNotSet
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
namespaceName := namespaceEntry.Name()
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.checkNamespaceMatch(request.Namespace, namespaceName); err != nil {
return nil, err
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetDetails().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
taskToken.GetWorkflowId(),
taskToken.GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondActivityTaskCanceled"),
); err != nil {
// details exceeds blob size limit, we would record it as failure
failRequest := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: request.TaskToken,
Failure: failure.NewServerFailure(common.FailureReasonCancelDetailsExceedsLimit, true),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: taskToken.GetNamespaceId(),
FailedRequest: failRequest,
})
if err != nil {
return nil, err
}
} else {
_, err = wh.GetHistoryClient().RespondActivityTaskCanceled(ctx, &historyservice.RespondActivityTaskCanceledRequest{
NamespaceId: taskToken.GetNamespaceId(),
CancelRequest: request,
})
if err != nil {
return nil, err
}
}
return &workflowservice.RespondActivityTaskCanceledResponse{}, nil
}
// RespondActivityTaskCanceledById is called by application worker when it is successfully canceled an ActivityTask.
// It will result in a new 'ActivityTaskCanceled' event being written to the workflow history and a new WorkflowTask
// created for the workflow instance so new commands could be made. Similar to RespondActivityTaskCanceled but use
// Namespace, WorkflowID and ActivityID instead of 'taskToken' for completion. It fails with 'EntityNotExistsError'
// if the these IDs are not valid anymore due to activity timeout.
func (wh *WorkflowHandler) RespondActivityTaskCanceledById(ctx context.Context, request *workflowservice.RespondActivityTaskCanceledByIdRequest) (_ *workflowservice.RespondActivityTaskCanceledByIdResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
workflowID := request.GetWorkflowId()
runID := request.GetRunId() // runID is optional so can be empty
activityID := request.GetActivityId()
if namespaceID.IsEmpty() {
return nil, errNamespaceNotSet
}
if workflowID == "" {
return nil, errWorkflowIDNotSet
}
if activityID == "" {
return nil, errActivityIDNotSet
}
if len(request.GetIdentity()) > wh.config.MaxIDLengthLimit() {
return nil, errIdentityTooLong
}
taskToken := &tokenspb.Task{
NamespaceId: namespaceID.String(),
RunId: runID,
WorkflowId: workflowID,
ScheduleId: common.EmptyEventID,
ActivityId: activityID,
ScheduleAttempt: 1,
}
token, err := wh.tokenSerializer.Serialize(taskToken)
if err != nil {
return nil, err
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetDetails().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
taskToken.GetWorkflowId(),
runID,
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondActivityTaskCanceledById"),
); err != nil {
// details exceeds blob size limit, we would record it as failure
failRequest := &workflowservice.RespondActivityTaskFailedRequest{
TaskToken: token,
Failure: failure.NewServerFailure(common.FailureReasonCancelDetailsExceedsLimit, true),
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskFailed(ctx, &historyservice.RespondActivityTaskFailedRequest{
NamespaceId: namespaceID.String(),
FailedRequest: failRequest,
})
if err != nil {
return nil, err
}
} else {
req := &workflowservice.RespondActivityTaskCanceledRequest{
TaskToken: token,
Details: request.Details,
Identity: request.Identity,
}
_, err = wh.GetHistoryClient().RespondActivityTaskCanceled(ctx, &historyservice.RespondActivityTaskCanceledRequest{
NamespaceId: namespaceID.String(),
CancelRequest: req,
})
if err != nil {
return nil, err
}
}
return &workflowservice.RespondActivityTaskCanceledByIdResponse{}, nil
}
// RequestCancelWorkflowExecution is called by application worker when it wants to request cancellation of a workflow instance.
// It will result in a new 'WorkflowExecutionCancelRequested' event being written to the workflow history and a new WorkflowTask
// created for the workflow instance so new commands could be made. It fails with 'EntityNotExistsError' if the workflow is not valid
// anymore due to completion or doesn't exist.
func (wh *WorkflowHandler) RequestCancelWorkflowExecution(ctx context.Context, request *workflowservice.RequestCancelWorkflowExecutionRequest) (_ *workflowservice.RequestCancelWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateExecution(request.WorkflowExecution); err != nil {
return nil, err
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
_, err = wh.GetHistoryClient().RequestCancelWorkflowExecution(ctx, &historyservice.RequestCancelWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
CancelRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.RequestCancelWorkflowExecutionResponse{}, nil
}
// SignalWorkflowExecution is used to send a signal event to running workflow execution. This results in
// WorkflowExecutionSignaled event recorded in the history and a workflow task being created for the execution.
func (wh *WorkflowHandler) SignalWorkflowExecution(ctx context.Context, request *workflowservice.SignalWorkflowExecutionRequest) (_ *workflowservice.SignalWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if len(request.GetNamespace()) > wh.config.MaxIDLengthLimit() {
return nil, errNamespaceTooLong
}
if err := wh.validateExecution(request.WorkflowExecution); err != nil {
return nil, err
}
if request.GetSignalName() == "" {
return nil, errSignalNameTooLong
}
if len(request.GetSignalName()) > wh.config.MaxIDLengthLimit() {
return nil, errSignalNameTooLong
}
if len(request.GetRequestId()) > wh.config.MaxIDLengthLimit() {
return nil, errRequestIDTooLong
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(request.GetNamespace())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(request.GetNamespace())
if err := common.CheckEventBlobSizeLimit(
request.GetInput().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
request.GetWorkflowExecution().GetWorkflowId(),
request.GetWorkflowExecution().GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("SignalWorkflowExecution"),
); err != nil {
return nil, err
}
_, err = wh.GetHistoryClient().SignalWorkflowExecution(ctx, &historyservice.SignalWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
SignalRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.SignalWorkflowExecutionResponse{}, nil
}
// SignalWithStartWorkflowExecution is used to ensure sending signal to a workflow.
// If the workflow is running, this results in WorkflowExecutionSignaled event being recorded in the history
// and a workflow task being created for the execution.
// If the workflow is not running or not found, this results in WorkflowExecutionStarted and WorkflowExecutionSignaled
// events being recorded in history, and a workflow task being created for the execution
func (wh *WorkflowHandler) SignalWithStartWorkflowExecution(ctx context.Context, request *workflowservice.SignalWithStartWorkflowExecutionRequest) (_ *workflowservice.SignalWithStartWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
namespaceName := namespace.Name(request.GetNamespace())
if namespaceName.IsEmpty() {
return nil, errNamespaceNotSet
}
if len(namespaceName) > wh.config.MaxIDLengthLimit() {
return nil, errNamespaceTooLong
}
if request.GetWorkflowId() == "" {
return nil, errWorkflowIDNotSet
}
if len(request.GetWorkflowId()) > wh.config.MaxIDLengthLimit() {
return nil, errWorkflowIDTooLong
}
if request.GetSignalName() == "" {
return nil, errSignalNameNotSet
}
if len(request.GetSignalName()) > wh.config.MaxIDLengthLimit() {
return nil, errSignalNameTooLong
}
if request.WorkflowType == nil || request.WorkflowType.GetName() == "" {
return nil, errWorkflowTypeNotSet
}
if len(request.WorkflowType.GetName()) > wh.config.MaxIDLengthLimit() {
return nil, errWorkflowTypeTooLong
}
if err := wh.validateTaskQueue(request.TaskQueue); err != nil {
return nil, err
}
if len(request.GetRequestId()) > wh.config.MaxIDLengthLimit() {
return nil, errRequestIDTooLong
}
if err := wh.validateSignalWithStartWorkflowTimeouts(request); err != nil {
return nil, err
}
if err := wh.validateRetryPolicy(request.GetNamespace(), request.RetryPolicy); err != nil {
return nil, err
}
if err := backoff.ValidateSchedule(request.GetCronSchedule()); err != nil {
return nil, err
}
enums.SetDefaultWorkflowIdReusePolicy(&request.WorkflowIdReusePolicy)
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
var runId string
op := func() error {
var err error
resp, err := wh.GetHistoryClient().SignalWithStartWorkflowExecution(ctx, &historyservice.SignalWithStartWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
SignalWithStartRequest: request,
})
if err != nil {
return err
}
runId = resp.GetRunId()
return nil
}
err = backoff.Retry(op, frontendServiceRetryPolicy, common.IsServiceTransientError)
if err != nil {
return nil, err
}
return &workflowservice.SignalWithStartWorkflowExecutionResponse{RunId: runId}, nil
}
// ResetWorkflowExecution reset an existing workflow execution to WorkflowTaskCompleted event(exclusive).
// And it will immediately terminating the current execution instance.
func (wh *WorkflowHandler) ResetWorkflowExecution(ctx context.Context, request *workflowservice.ResetWorkflowExecutionRequest) (_ *workflowservice.ResetWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateExecution(request.WorkflowExecution); err != nil {
return nil, err
}
switch request.GetResetReapplyType() {
case enumspb.RESET_REAPPLY_TYPE_UNSPECIFIED:
request.ResetReapplyType = enumspb.RESET_REAPPLY_TYPE_SIGNAL
case enumspb.RESET_REAPPLY_TYPE_SIGNAL:
// noop
case enumspb.RESET_REAPPLY_TYPE_NONE:
// noop
default:
return nil, serviceerror.NewInternal("unknown reset type")
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
resp, err := wh.GetHistoryClient().ResetWorkflowExecution(ctx, &historyservice.ResetWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
ResetRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.ResetWorkflowExecutionResponse{RunId: resp.GetRunId()}, nil
}
// TerminateWorkflowExecution terminates an existing workflow execution by recording WorkflowExecutionTerminated event
// in the history and immediately terminating the execution instance.
func (wh *WorkflowHandler) TerminateWorkflowExecution(ctx context.Context, request *workflowservice.TerminateWorkflowExecutionRequest) (_ *workflowservice.TerminateWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateExecution(request.WorkflowExecution); err != nil {
return nil, err
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
_, err = wh.GetHistoryClient().TerminateWorkflowExecution(ctx, &historyservice.TerminateWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
TerminateRequest: request,
})
if err != nil {
return nil, err
}
return &workflowservice.TerminateWorkflowExecutionResponse{}, nil
}
// ListOpenWorkflowExecutions is a visibility API to list the open executions in a specific namespace.
func (wh *WorkflowHandler) ListOpenWorkflowExecutions(ctx context.Context, request *workflowservice.ListOpenWorkflowExecutionsRequest) (_ *workflowservice.ListOpenWorkflowExecutionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if request.StartTimeFilter == nil {
request.StartTimeFilter = &filterpb.StartTimeFilter{}
}
if timestamp.TimeValue(request.GetStartTimeFilter().GetEarliestTime()).IsZero() {
request.GetStartTimeFilter().EarliestTime = &minTime
}
if timestamp.TimeValue(request.GetStartTimeFilter().GetLatestTime()).IsZero() {
request.GetStartTimeFilter().LatestTime = &maxTime
}
if timestamp.TimeValue(request.StartTimeFilter.GetEarliestTime()).After(timestamp.TimeValue(request.StartTimeFilter.GetLatestTime())) {
return nil, errEarliestTimeIsGreaterThanLatestTime
}
if request.GetMaximumPageSize() <= 0 {
request.MaximumPageSize = int32(wh.config.VisibilityMaxPageSize(request.GetNamespace()))
}
if wh.isListRequestPageSizeTooLarge(request.GetMaximumPageSize(), request.GetNamespace()) {
return nil, serviceerror.NewInvalidArgument(fmt.Sprintf(errPageSizeTooBigMessage, wh.config.ESIndexMaxResultWindow()))
}
namespaceName := namespace.Name(request.GetNamespace())
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
baseReq := &manager.ListWorkflowExecutionsRequest{
NamespaceID: namespaceID,
Namespace: namespaceName,
PageSize: int(request.GetMaximumPageSize()),
NextPageToken: request.NextPageToken,
EarliestStartTime: timestamp.TimeValue(request.StartTimeFilter.GetEarliestTime()),
LatestStartTime: timestamp.TimeValue(request.StartTimeFilter.GetLatestTime()),
}
var persistenceResp *manager.ListWorkflowExecutionsResponse
if request.GetExecutionFilter() != nil {
if wh.config.DisableListVisibilityByFilter(namespaceName.String()) {
err = errNoPermission
} else {
persistenceResp, err = wh.visibilityMrg.ListOpenWorkflowExecutionsByWorkflowID(
&manager.ListWorkflowExecutionsByWorkflowIDRequest{
ListWorkflowExecutionsRequest: baseReq,
WorkflowID: request.GetExecutionFilter().GetWorkflowId(),
})
}
wh.GetLogger().Debug("List open workflow with filter",
tag.WorkflowNamespace(request.GetNamespace()), tag.WorkflowListWorkflowFilterByID)
} else if request.GetTypeFilter() != nil {
if wh.config.DisableListVisibilityByFilter(namespaceName.String()) {
err = errNoPermission
} else {
persistenceResp, err = wh.visibilityMrg.ListOpenWorkflowExecutionsByType(&manager.ListWorkflowExecutionsByTypeRequest{
ListWorkflowExecutionsRequest: baseReq,
WorkflowTypeName: request.GetTypeFilter().GetName(),
})
}
wh.GetLogger().Debug("List open workflow with filter",
tag.WorkflowNamespace(request.GetNamespace()), tag.WorkflowListWorkflowFilterByType)
} else {
persistenceResp, err = wh.visibilityMrg.ListOpenWorkflowExecutions(baseReq)
}
if err != nil {
return nil, err
}
return &workflowservice.ListOpenWorkflowExecutionsResponse{
Executions: persistenceResp.Executions,
NextPageToken: persistenceResp.NextPageToken,
}, nil
}
// ListClosedWorkflowExecutions is a visibility API to list the closed executions in a specific namespace.
func (wh *WorkflowHandler) ListClosedWorkflowExecutions(ctx context.Context, request *workflowservice.ListClosedWorkflowExecutionsRequest) (_ *workflowservice.ListClosedWorkflowExecutionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if request.StartTimeFilter == nil {
request.StartTimeFilter = &filterpb.StartTimeFilter{}
}
if timestamp.TimeValue(request.GetStartTimeFilter().GetEarliestTime()).IsZero() {
request.GetStartTimeFilter().EarliestTime = &minTime
}
if timestamp.TimeValue(request.GetStartTimeFilter().GetLatestTime()).IsZero() {
request.GetStartTimeFilter().LatestTime = &maxTime
}
if timestamp.TimeValue(request.StartTimeFilter.GetEarliestTime()).After(timestamp.TimeValue(request.StartTimeFilter.GetLatestTime())) {
return nil, errEarliestTimeIsGreaterThanLatestTime
}
if request.GetMaximumPageSize() <= 0 {
request.MaximumPageSize = int32(wh.config.VisibilityMaxPageSize(request.GetNamespace()))
}
if wh.isListRequestPageSizeTooLarge(request.GetMaximumPageSize(), request.GetNamespace()) {
return nil, serviceerror.NewInvalidArgument(fmt.Sprintf(errPageSizeTooBigMessage, wh.config.ESIndexMaxResultWindow()))
}
namespaceName := namespace.Name(request.GetNamespace())
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
baseReq := &manager.ListWorkflowExecutionsRequest{
NamespaceID: namespaceID,
Namespace: namespaceName,
PageSize: int(request.GetMaximumPageSize()),
NextPageToken: request.NextPageToken,
EarliestStartTime: timestamp.TimeValue(request.StartTimeFilter.GetEarliestTime()),
LatestStartTime: timestamp.TimeValue(request.StartTimeFilter.GetLatestTime()),
}
var persistenceResp *manager.ListWorkflowExecutionsResponse
if request.GetExecutionFilter() != nil {
if wh.config.DisableListVisibilityByFilter(namespaceName.String()) {
err = errNoPermission
} else {
persistenceResp, err = wh.visibilityMrg.ListClosedWorkflowExecutionsByWorkflowID(
&manager.ListWorkflowExecutionsByWorkflowIDRequest{
ListWorkflowExecutionsRequest: baseReq,
WorkflowID: request.GetExecutionFilter().GetWorkflowId(),
})
}
wh.GetLogger().Debug("List closed workflow with filter",
tag.WorkflowNamespace(request.GetNamespace()), tag.WorkflowListWorkflowFilterByID)
} else if request.GetTypeFilter() != nil {
if wh.config.DisableListVisibilityByFilter(namespaceName.String()) {
err = errNoPermission
} else {
persistenceResp, err = wh.visibilityMrg.ListClosedWorkflowExecutionsByType(&manager.ListWorkflowExecutionsByTypeRequest{
ListWorkflowExecutionsRequest: baseReq,
WorkflowTypeName: request.GetTypeFilter().GetName(),
})
}
wh.GetLogger().Debug("List closed workflow with filter",
tag.WorkflowNamespace(request.GetNamespace()), tag.WorkflowListWorkflowFilterByType)
} else if request.GetStatusFilter() != nil {
if wh.config.DisableListVisibilityByFilter(namespaceName.String()) {
err = errNoPermission
} else {
if request.GetStatusFilter().GetStatus() == enumspb.WORKFLOW_EXECUTION_STATUS_UNSPECIFIED || request.GetStatusFilter().GetStatus() == enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING {
err = errStatusFilterMustBeNotRunning
} else {
persistenceResp, err = wh.visibilityMrg.ListClosedWorkflowExecutionsByStatus(&manager.ListClosedWorkflowExecutionsByStatusRequest{
ListWorkflowExecutionsRequest: baseReq,
Status: request.GetStatusFilter().GetStatus(),
})
}
}
wh.GetLogger().Debug("List closed workflow with filter",
tag.WorkflowNamespace(request.GetNamespace()), tag.WorkflowListWorkflowFilterByStatus)
} else {
persistenceResp, err = wh.visibilityMrg.ListClosedWorkflowExecutions(baseReq)
}
if err != nil {
return nil, err
}
return &workflowservice.ListClosedWorkflowExecutionsResponse{
Executions: persistenceResp.Executions,
NextPageToken: persistenceResp.NextPageToken,
}, nil
}
// ListWorkflowExecutions is a visibility API to list workflow executions in a specific namespace.
func (wh *WorkflowHandler) ListWorkflowExecutions(ctx context.Context, request *workflowservice.ListWorkflowExecutionsRequest) (_ *workflowservice.ListWorkflowExecutionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if request.GetPageSize() <= 0 {
request.PageSize = int32(wh.config.VisibilityMaxPageSize(request.GetNamespace()))
}
if wh.isListRequestPageSizeTooLarge(request.GetPageSize(), request.GetNamespace()) {
return nil, serviceerror.NewInvalidArgument(fmt.Sprintf(errPageSizeTooBigMessage, wh.config.ESIndexMaxResultWindow()))
}
namespaceName := namespace.Name(request.GetNamespace())
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
req := &manager.ListWorkflowExecutionsRequestV2{
NamespaceID: namespaceID,
Namespace: namespaceName,
PageSize: int(request.GetPageSize()),
NextPageToken: request.NextPageToken,
Query: request.GetQuery(),
}
persistenceResp, err := wh.visibilityMrg.ListWorkflowExecutions(req)
if err != nil {
return nil, err
}
return &workflowservice.ListWorkflowExecutionsResponse{
Executions: persistenceResp.Executions,
NextPageToken: persistenceResp.NextPageToken,
}, nil
}
// ListArchivedWorkflowExecutions is a visibility API to list archived workflow executions in a specific namespace.
func (wh *WorkflowHandler) ListArchivedWorkflowExecutions(ctx context.Context, request *workflowservice.ListArchivedWorkflowExecutionsRequest) (_ *workflowservice.ListArchivedWorkflowExecutionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if request.GetPageSize() <= 0 {
request.PageSize = int32(wh.config.VisibilityMaxPageSize(request.GetNamespace()))
}
maxPageSize := wh.config.VisibilityArchivalQueryMaxPageSize()
if int(request.GetPageSize()) > maxPageSize {
return nil, serviceerror.NewInvalidArgument(fmt.Sprintf(errPageSizeTooBigMessage, maxPageSize))
}
if !wh.GetArchivalMetadata().GetVisibilityConfig().ClusterConfiguredForArchival() {
return nil, errClusterIsNotConfiguredForVisibilityArchival
}
if !wh.GetArchivalMetadata().GetVisibilityConfig().ReadEnabled() {
return nil, errClusterIsNotConfiguredForReadingArchivalVisibility
}
entry, err := wh.GetNamespaceRegistry().GetNamespace(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
if entry.VisibilityArchivalState().State != enumspb.ARCHIVAL_STATE_ENABLED {
return nil, errNamespaceIsNotConfiguredForVisibilityArchival
}
URI, err := archiver.NewURI(entry.VisibilityArchivalState().URI)
if err != nil {
return nil, err
}
visibilityArchiver, err := wh.GetArchiverProvider().GetVisibilityArchiver(URI.Scheme(), common.FrontendServiceName)
if err != nil {
return nil, err
}
archiverRequest := &archiver.QueryVisibilityRequest{
NamespaceID: entry.ID().String(),
PageSize: int(request.GetPageSize()),
NextPageToken: request.NextPageToken,
Query: request.GetQuery(),
}
searchAttributes, err := wh.Resource.GetSearchAttributesProvider().GetSearchAttributes(wh.config.ESIndexName, false)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf(errUnableToGetSearchAttributesMessage, err))
}
archiverResponse, err := visibilityArchiver.Query(
ctx,
URI,
archiverRequest,
searchAttributes)
if err != nil {
return nil, err
}
// special handling of ExecutionTime for cron or retry
for _, execution := range archiverResponse.Executions {
if timestamp.TimeValue(execution.GetExecutionTime()).IsZero() {
execution.ExecutionTime = execution.GetStartTime()
}
}
return &workflowservice.ListArchivedWorkflowExecutionsResponse{
Executions: archiverResponse.Executions,
NextPageToken: archiverResponse.NextPageToken,
}, nil
}
// ScanWorkflowExecutions is a visibility API to list large amount of workflow executions in a specific namespace without order.
func (wh *WorkflowHandler) ScanWorkflowExecutions(ctx context.Context, request *workflowservice.ScanWorkflowExecutionsRequest) (_ *workflowservice.ScanWorkflowExecutionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if request.GetPageSize() <= 0 {
request.PageSize = int32(wh.config.VisibilityMaxPageSize(request.GetNamespace()))
}
if wh.isListRequestPageSizeTooLarge(request.GetPageSize(), request.GetNamespace()) {
return nil, serviceerror.NewInvalidArgument(fmt.Sprintf(errPageSizeTooBigMessage, wh.config.ESIndexMaxResultWindow()))
}
namespaceName := namespace.Name(request.GetNamespace())
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
req := &manager.ListWorkflowExecutionsRequestV2{
NamespaceID: namespaceID,
Namespace: namespaceName,
PageSize: int(request.GetPageSize()),
NextPageToken: request.NextPageToken,
Query: request.GetQuery(),
}
persistenceResp, err := wh.visibilityMrg.ScanWorkflowExecutions(req)
if err != nil {
return nil, err
}
resp := &workflowservice.ScanWorkflowExecutionsResponse{
Executions: persistenceResp.Executions,
NextPageToken: persistenceResp.NextPageToken,
}
return resp, nil
}
// CountWorkflowExecutions is a visibility API to count of workflow executions in a specific namespace.
func (wh *WorkflowHandler) CountWorkflowExecutions(ctx context.Context, request *workflowservice.CountWorkflowExecutionsRequest) (_ *workflowservice.CountWorkflowExecutionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
namespaceName := namespace.Name(request.GetNamespace())
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
req := &manager.CountWorkflowExecutionsRequest{
NamespaceID: namespaceID,
Namespace: namespaceName,
Query: request.GetQuery(),
}
persistenceResp, err := wh.visibilityMrg.CountWorkflowExecutions(req)
if err != nil {
return nil, err
}
resp := &workflowservice.CountWorkflowExecutionsResponse{
Count: persistenceResp.Count,
}
return resp, nil
}
// GetSearchAttributes is a visibility API to get all legal keys that could be used in list APIs
func (wh *WorkflowHandler) GetSearchAttributes(ctx context.Context, _ *workflowservice.GetSearchAttributesRequest) (_ *workflowservice.GetSearchAttributesResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
searchAttributes, err := wh.GetSearchAttributesProvider().GetSearchAttributes(wh.config.ESIndexName, false)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf(errUnableToGetSearchAttributesMessage, err))
}
resp := &workflowservice.GetSearchAttributesResponse{
Keys: searchAttributes.All(),
}
return resp, nil
}
// RespondQueryTaskCompleted is called by application worker to complete a QueryTask (which is a WorkflowTask for query)
// as a result of 'PollWorkflowTaskQueue' API call. Completing a QueryTask will unblock the client call to 'QueryWorkflow'
// API and return the query result to client as a response to 'QueryWorkflow' API call.
func (wh *WorkflowHandler) RespondQueryTaskCompleted(
ctx context.Context,
request *workflowservice.RespondQueryTaskCompletedRequest,
) (_ *workflowservice.RespondQueryTaskCompletedResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.TaskToken == nil {
return nil, errTaskTokenNotSet
}
queryTaskToken, err := wh.tokenSerializer.DeserializeQueryTaskToken(request.TaskToken)
if err != nil {
return nil, err
}
if queryTaskToken.GetNamespaceId() == "" || queryTaskToken.GetTaskQueue() == "" || queryTaskToken.GetTaskId() == "" {
return nil, errInvalidTaskToken
}
namespaceEntry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespace.ID(queryTaskToken.GetNamespaceId()))
if err != nil {
return nil, err
}
namespaceName := namespaceEntry.Name()
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.checkNamespaceMatch(request.Namespace, namespaceName); err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(namespaceEntry.Name().String())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(namespaceEntry.Name().String())
if err := common.CheckEventBlobSizeLimit(
request.GetQueryResult().Size(),
sizeLimitWarn,
sizeLimitError,
queryTaskToken.GetNamespaceId(),
"",
"",
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("RespondQueryTaskCompleted"),
); err != nil {
request = &workflowservice.RespondQueryTaskCompletedRequest{
TaskToken: request.TaskToken,
CompletedType: enumspb.QUERY_RESULT_TYPE_FAILED,
QueryResult: nil,
ErrorMessage: err.Error(),
}
}
matchingRequest := &matchingservice.RespondQueryTaskCompletedRequest{
NamespaceId: queryTaskToken.GetNamespaceId(),
TaskQueue: &taskqueuepb.TaskQueue{
Name: queryTaskToken.GetTaskQueue(),
Kind: enumspb.TASK_QUEUE_KIND_NORMAL,
},
TaskId: queryTaskToken.GetTaskId(),
CompletedRequest: request,
}
_, err = wh.GetMatchingClient().RespondQueryTaskCompleted(ctx, matchingRequest)
if err != nil {
return nil, err
}
return &workflowservice.RespondQueryTaskCompletedResponse{}, nil
}
// ResetStickyTaskQueue resets the sticky taskqueue related information in mutable state of a given workflow.
// Things cleared are:
// 1. StickyTaskQueue
// 2. StickyScheduleToStartTimeout
func (wh *WorkflowHandler) ResetStickyTaskQueue(ctx context.Context, request *workflowservice.ResetStickyTaskQueueRequest) (_ *workflowservice.ResetStickyTaskQueueResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateExecution(request.Execution); err != nil {
return nil, err
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
_, err = wh.GetHistoryClient().ResetStickyTaskQueue(ctx, &historyservice.ResetStickyTaskQueueRequest{
NamespaceId: namespaceID.String(),
Execution: request.Execution,
})
if err != nil {
return nil, err
}
return &workflowservice.ResetStickyTaskQueueResponse{}, nil
}
// QueryWorkflow returns query result for a specified workflow execution
func (wh *WorkflowHandler) QueryWorkflow(ctx context.Context, request *workflowservice.QueryWorkflowRequest) (_ *workflowservice.QueryWorkflowResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if wh.config.DisallowQuery(request.GetNamespace()) {
return nil, errQueryDisallowedForNamespace
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateExecution(request.Execution); err != nil {
return nil, err
}
if request.Query == nil {
return nil, errQueryNotSet
}
if request.Query.GetQueryType() == "" {
return nil, errQueryTypeNotSet
}
enums.SetDefaultQueryRejectCondition(&request.QueryRejectCondition)
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
sizeLimitError := wh.config.BlobSizeLimitError(request.GetNamespace())
sizeLimitWarn := wh.config.BlobSizeLimitWarn(request.GetNamespace())
if err := common.CheckEventBlobSizeLimit(
request.GetQuery().GetQueryArgs().Size(),
sizeLimitWarn,
sizeLimitError,
namespaceID.String(),
request.GetExecution().GetWorkflowId(),
request.GetExecution().GetRunId(),
wh.metricsScope(ctx).Tagged(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String())),
wh.GetThrottledLogger(),
tag.BlobSizeViolationOperation("QueryWorkflow")); err != nil {
return nil, err
}
req := &historyservice.QueryWorkflowRequest{
NamespaceId: namespaceID.String(),
Request: request,
}
hResponse, err := wh.GetHistoryClient().QueryWorkflow(ctx, req)
if err != nil {
return nil, err
}
return hResponse.GetResponse(), nil
}
// DescribeWorkflowExecution returns information about the specified workflow execution.
func (wh *WorkflowHandler) DescribeWorkflowExecution(ctx context.Context, request *workflowservice.DescribeWorkflowExecutionRequest) (_ *workflowservice.DescribeWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
if err := wh.validateExecution(request.Execution); err != nil {
return nil, err
}
response, err := wh.GetHistoryClient().DescribeWorkflowExecution(ctx, &historyservice.DescribeWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
Request: request,
})
if err != nil {
return nil, err
}
if response.GetWorkflowExecutionInfo().GetSearchAttributes() != nil {
saTypeMap, err := wh.GetSearchAttributesProvider().GetSearchAttributes(wh.config.ESIndexName, false)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf(errUnableToGetSearchAttributesMessage, err))
}
searchattribute.ApplyTypeMap(response.GetWorkflowExecutionInfo().GetSearchAttributes(), saTypeMap)
err = searchattribute.ApplyAliases(wh.GetSearchAttributesMapper(), response.GetWorkflowExecutionInfo().GetSearchAttributes(), request.GetNamespace())
if err != nil {
return nil, err
}
}
return &workflowservice.DescribeWorkflowExecutionResponse{
ExecutionConfig: response.GetExecutionConfig(),
WorkflowExecutionInfo: response.GetWorkflowExecutionInfo(),
PendingActivities: response.GetPendingActivities(),
PendingChildren: response.GetPendingChildren(),
}, nil
}
// DescribeTaskQueue returns information about the target taskqueue, right now this API returns the
// pollers which polled this taskqueue in last few minutes.
func (wh *WorkflowHandler) DescribeTaskQueue(ctx context.Context, request *workflowservice.DescribeTaskQueueRequest) (_ *workflowservice.DescribeTaskQueueResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if err := wh.versionChecker.ClientSupported(ctx, wh.config.EnableClientVersionCheck()); err != nil {
return nil, err
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
namespaceID, err := wh.GetNamespaceRegistry().GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
if err := wh.validateTaskQueue(request.TaskQueue); err != nil {
return nil, err
}
var matchingResponse *matchingservice.DescribeTaskQueueResponse
op := func() error {
var err error
matchingResponse, err = wh.GetMatchingClient().DescribeTaskQueue(ctx, &matchingservice.DescribeTaskQueueRequest{
NamespaceId: namespaceID.String(),
DescRequest: request,
})
return err
}
err = backoff.Retry(op, frontendServiceRetryPolicy, common.IsServiceTransientError)
if err != nil {
return nil, err
}
return &workflowservice.DescribeTaskQueueResponse{
Pollers: matchingResponse.Pollers,
TaskQueueStatus: matchingResponse.TaskQueueStatus,
}, nil
}
// GetClusterInfo return information about Temporal deployment.
func (wh *WorkflowHandler) GetClusterInfo(_ context.Context, _ *workflowservice.GetClusterInfoRequest) (_ *workflowservice.GetClusterInfoResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
metadata, err := wh.GetClusterMetadataManager().GetClusterMetadata()
if err != nil {
return nil, err
}
return &workflowservice.GetClusterInfoResponse{
SupportedClients: headers.SupportedClients,
ServerVersion: headers.ServerVersion,
ClusterId: metadata.ClusterId,
VersionInfo: metadata.VersionInfo,
ClusterName: metadata.ClusterName,
HistoryShardCount: metadata.HistoryShardCount,
PersistenceStore: wh.GetExecutionManager().GetName(),
VisibilityStore: wh.visibilityMrg.GetName(),
}, nil
}
// ListTaskQueuePartitions returns all the partition and host for a task queue.
func (wh *WorkflowHandler) ListTaskQueuePartitions(ctx context.Context, request *workflowservice.ListTaskQueuePartitionsRequest) (_ *workflowservice.ListTaskQueuePartitionsResponse, retError error) {
defer log.CapturePanic(wh.GetLogger(), &retError)
if wh.isStopped() {
return nil, errShuttingDown
}
if request == nil {
return nil, errRequestNotSet
}
if request.GetNamespace() == "" {
return nil, errNamespaceNotSet
}
if err := wh.validateTaskQueue(request.TaskQueue); err != nil {
return nil, err
}
matchingResponse, err := wh.GetMatchingClient().ListTaskQueuePartitions(ctx, &matchingservice.ListTaskQueuePartitionsRequest{
Namespace: request.GetNamespace(),
TaskQueue: request.TaskQueue,
})
if matchingResponse == nil {
return nil, err
}
return &workflowservice.ListTaskQueuePartitionsResponse{
ActivityTaskQueuePartitions: matchingResponse.ActivityTaskQueuePartitions,
WorkflowTaskQueuePartitions: matchingResponse.WorkflowTaskQueuePartitions,
}, err
}
func (wh *WorkflowHandler) getRawHistory(
scope metrics.Scope,
namespaceID namespace.ID,
execution commonpb.WorkflowExecution,
firstEventID int64,
nextEventID int64,
pageSize int32,
nextPageToken []byte,
transientWorkflowTaskInfo *historyspb.TransientWorkflowTaskInfo,
branchToken []byte,
) ([]*commonpb.DataBlob, []byte, error) {
var rawHistory []*commonpb.DataBlob
shardID := common.WorkflowIDToHistoryShard(namespaceID.String(), execution.GetWorkflowId(), wh.config.NumHistoryShards)
resp, err := wh.GetExecutionManager().ReadRawHistoryBranch(&persistence.ReadHistoryBranchRequest{
BranchToken: branchToken,
MinEventID: firstEventID,
MaxEventID: nextEventID,
PageSize: int(pageSize),
NextPageToken: nextPageToken,
ShardID: shardID,
})
if err != nil {
return nil, nil, err
}
for _, data := range resp.HistoryEventBlobs {
rawHistory = append(rawHistory, &commonpb.DataBlob{
EncodingType: data.EncodingType,
Data: data.Data,
})
}
if len(nextPageToken) == 0 && transientWorkflowTaskInfo != nil {
if err := wh.validateTransientWorkflowTaskEvents(nextEventID, transientWorkflowTaskInfo); err != nil {
scope.IncCounter(metrics.ServiceErrIncompleteHistoryCounter)
wh.GetLogger().Error("getHistory error",
tag.WorkflowNamespaceID(namespaceID.String()),
tag.WorkflowID(execution.GetWorkflowId()),
tag.WorkflowRunID(execution.GetRunId()),
tag.Error(err))
}
blob, err := wh.GetPayloadSerializer().SerializeEvent(transientWorkflowTaskInfo.ScheduledEvent, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, nil, err
}
rawHistory = append(rawHistory, &commonpb.DataBlob{
EncodingType: enumspb.ENCODING_TYPE_PROTO3,
Data: blob.Data,
})
blob, err = wh.GetPayloadSerializer().SerializeEvent(transientWorkflowTaskInfo.StartedEvent, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, nil, err
}
rawHistory = append(rawHistory, &commonpb.DataBlob{
EncodingType: enumspb.ENCODING_TYPE_PROTO3,
Data: blob.Data,
})
}
return rawHistory, resp.NextPageToken, nil
}
func (wh *WorkflowHandler) getHistory(
scope metrics.Scope,
namespaceID namespace.ID,
namespace namespace.Name,
execution commonpb.WorkflowExecution,
firstEventID int64,
nextEventID int64,
pageSize int32,
nextPageToken []byte,
transientWorkflowTaskInfo *historyspb.TransientWorkflowTaskInfo,
branchToken []byte,
) (*historypb.History, []byte, error) {
var size int
isFirstPage := len(nextPageToken) == 0
shardID := common.WorkflowIDToHistoryShard(namespaceID.String(), execution.GetWorkflowId(), wh.config.NumHistoryShards)
var err error
var historyEvents []*historypb.HistoryEvent
historyEvents, size, nextPageToken, err = persistence.ReadFullPageEvents(wh.GetExecutionManager(), &persistence.ReadHistoryBranchRequest{
BranchToken: branchToken,
MinEventID: firstEventID,
MaxEventID: nextEventID,
PageSize: int(pageSize),
NextPageToken: nextPageToken,
ShardID: shardID,
})
switch err.(type) {
case nil:
// noop
case *serviceerror.DataLoss:
// log event
wh.GetLogger().Error("encounter data loss event", tag.WorkflowNamespaceID(namespaceID.String()), tag.WorkflowID(execution.GetWorkflowId()), tag.WorkflowRunID(execution.GetRunId()))
return nil, nil, err
default:
return nil, nil, err
}
scope.Tagged(metrics.StatsTypeTag(metrics.SizeStatsTypeTagValue)).RecordDistribution(metrics.HistorySize, size)
isLastPage := len(nextPageToken) == 0
if err := wh.verifyHistoryIsComplete(
historyEvents,
firstEventID,
nextEventID-1,
isFirstPage,
isLastPage,
int(pageSize)); err != nil {
scope.IncCounter(metrics.ServiceErrIncompleteHistoryCounter)
wh.GetLogger().Error("getHistory: incomplete history",
tag.WorkflowNamespaceID(namespaceID.String()),
tag.WorkflowID(execution.GetWorkflowId()),
tag.WorkflowRunID(execution.GetRunId()),
tag.Error(err))
return nil, nil, err
}
if len(nextPageToken) == 0 && transientWorkflowTaskInfo != nil {
if err := wh.validateTransientWorkflowTaskEvents(nextEventID, transientWorkflowTaskInfo); err != nil {
scope.IncCounter(metrics.ServiceErrIncompleteHistoryCounter)
wh.GetLogger().Error("getHistory error",
tag.WorkflowNamespaceID(namespaceID.String()),
tag.WorkflowID(execution.GetWorkflowId()),
tag.WorkflowRunID(execution.GetRunId()),
tag.Error(err))
}
// Append the transient workflow task events once we are done enumerating everything from the events table
historyEvents = append(historyEvents, transientWorkflowTaskInfo.ScheduledEvent, transientWorkflowTaskInfo.StartedEvent)
}
if err := wh.processSearchAttributes(historyEvents, namespace); err != nil {
return nil, nil, err
}
executionHistory := &historypb.History{
Events: historyEvents,
}
return executionHistory, nextPageToken, nil
}
func (wh *WorkflowHandler) processSearchAttributes(events []*historypb.HistoryEvent, namespace namespace.Name) error {
saTypeMap, err := wh.GetSearchAttributesProvider().GetSearchAttributes(wh.config.ESIndexName, false)
if err != nil {
return serviceerror.NewUnavailable(fmt.Sprintf(errUnableToGetSearchAttributesMessage, err))
}
for _, event := range events {
var searchAttributes *commonpb.SearchAttributes
switch event.EventType {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED:
searchAttributes = event.GetWorkflowExecutionStartedEventAttributes().GetSearchAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW:
searchAttributes = event.GetWorkflowExecutionContinuedAsNewEventAttributes().GetSearchAttributes()
case enumspb.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED:
searchAttributes = event.GetStartChildWorkflowExecutionInitiatedEventAttributes().GetSearchAttributes()
case enumspb.EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES:
searchAttributes = event.GetUpsertWorkflowSearchAttributesEventAttributes().GetSearchAttributes()
}
if searchAttributes != nil {
searchattribute.ApplyTypeMap(searchAttributes, saTypeMap)
err = searchattribute.ApplyAliases(wh.GetSearchAttributesMapper(), searchAttributes, namespace.String())
if err != nil {
return err
}
}
}
return nil
}
func (wh *WorkflowHandler) validateTransientWorkflowTaskEvents(
expectedNextEventID int64,
transientWorkflowTaskInfo *historyspb.TransientWorkflowTaskInfo,
) error {
if transientWorkflowTaskInfo.ScheduledEvent.GetEventId() == expectedNextEventID &&
transientWorkflowTaskInfo.StartedEvent.GetEventId() == expectedNextEventID+1 {
return nil
}
return fmt.Errorf("invalid transient workflow task: expectedScheduledEventID=%v expectedStartedEventID=%v but have scheduledEventID=%v startedEventID=%v",
expectedNextEventID,
expectedNextEventID+1,
transientWorkflowTaskInfo.ScheduledEvent.GetEventId(),
transientWorkflowTaskInfo.StartedEvent.GetEventId())
}
func (wh *WorkflowHandler) validateTaskQueue(t *taskqueuepb.TaskQueue) error {
if t == nil || t.GetName() == "" {
return errTaskQueueNotSet
}
if len(t.GetName()) > wh.config.MaxIDLengthLimit() {
return errTaskQueueTooLong
}
enums.SetDefaultTaskQueueKind(&t.Kind)
return nil
}
func (wh *WorkflowHandler) validateExecution(w *commonpb.WorkflowExecution) error {
err := validateExecution(w)
if err != nil {
return err
}
return nil
}
func (wh *WorkflowHandler) createPollWorkflowTaskQueueResponse(
ctx context.Context,
namespaceID namespace.ID,
matchingResp *matchingservice.PollWorkflowTaskQueueResponse,
branchToken []byte,
) (*workflowservice.PollWorkflowTaskQueueResponse, error) {
if matchingResp.WorkflowExecution == nil {
// this will happen if there is no workflow task to be send to worker / caller
return &workflowservice.PollWorkflowTaskQueueResponse{}, nil
}
var history *historypb.History
var continuation []byte
var err error
if matchingResp.GetStickyExecutionEnabled() && matchingResp.Query != nil {
// meaning sticky query, we should not return any events to worker
// since query task only check the current status
history = &historypb.History{
Events: []*historypb.HistoryEvent{},
}
} else {
// here we have 3 cases:
// 1. sticky && non query task
// 2. non sticky && non query task
// 3. non sticky && query task
// for 1, partial history have to be send back
// for 2 and 3, full history have to be send back
var persistenceToken []byte
firstEventID := common.FirstEventID
nextEventID := matchingResp.GetNextEventId()
if matchingResp.GetStickyExecutionEnabled() {
firstEventID = matchingResp.GetPreviousStartedEventId() + 1
}
namespaceEntry, dErr := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if dErr != nil {
return nil, dErr
}
history, persistenceToken, err = wh.getHistory(
wh.metricsScope(ctx),
namespaceID,
namespaceEntry.Name(),
*matchingResp.GetWorkflowExecution(),
firstEventID,
nextEventID,
int32(wh.config.HistoryMaxPageSize(namespaceEntry.Name().String())),
nil,
matchingResp.GetWorkflowTaskInfo(),
branchToken,
)
if err != nil {
return nil, err
}
if len(persistenceToken) != 0 {
continuation, err = serializeHistoryToken(&tokenspb.HistoryContinuation{
RunId: matchingResp.WorkflowExecution.GetRunId(),
FirstEventId: firstEventID,
NextEventId: nextEventID,
PersistenceToken: persistenceToken,
TransientWorkflowTask: matchingResp.GetWorkflowTaskInfo(),
BranchToken: branchToken,
})
if err != nil {
return nil, err
}
}
}
resp := &workflowservice.PollWorkflowTaskQueueResponse{
TaskToken: matchingResp.TaskToken,
WorkflowExecution: matchingResp.WorkflowExecution,
WorkflowType: matchingResp.WorkflowType,
PreviousStartedEventId: matchingResp.PreviousStartedEventId,
StartedEventId: matchingResp.StartedEventId,
Query: matchingResp.Query,
BacklogCountHint: matchingResp.BacklogCountHint,
Attempt: matchingResp.Attempt,
History: history,
NextPageToken: continuation,
WorkflowExecutionTaskQueue: matchingResp.WorkflowExecutionTaskQueue,
ScheduledTime: matchingResp.ScheduledTime,
StartedTime: matchingResp.StartedTime,
Queries: matchingResp.Queries,
}
return resp, nil
}
func (wh *WorkflowHandler) verifyHistoryIsComplete(
events []*historypb.HistoryEvent,
expectedFirstEventID int64,
expectedLastEventID int64,
isFirstPage bool,
isLastPage bool,
pageSize int,
) error {
nEvents := len(events)
if nEvents == 0 {
if isLastPage {
// we seem to be returning a non-nil pageToken on the lastPage which
// in turn cases the client to call getHistory again - only to find
// there are no more events to consume - bail out if this is the case here
return nil
}
return serviceerror.NewDataLoss("History contains zero events.")
}
firstEventID := events[0].GetEventId()
lastEventID := events[nEvents-1].GetEventId()
if !isFirstPage { // at least one page of history has been read previously
if firstEventID <= expectedFirstEventID {
// not first page and no events have been read in the previous pages - not possible
return serviceerror.NewDataLoss(fmt.Sprintf("Invalid history: expected first eventID to be > %v but got %v", expectedFirstEventID, firstEventID))
}
expectedFirstEventID = firstEventID
}
if !isLastPage {
// estimate lastEventID based on pageSize. This is a lower bound
// since the persistence layer counts "batch of events" as a single page
expectedLastEventID = expectedFirstEventID + int64(pageSize) - 1
}
nExpectedEvents := expectedLastEventID - expectedFirstEventID + 1
if firstEventID == expectedFirstEventID &&
((isLastPage && lastEventID == expectedLastEventID && int64(nEvents) == nExpectedEvents) ||
(!isLastPage && lastEventID >= expectedLastEventID && int64(nEvents) >= nExpectedEvents)) {
return nil
}
return serviceerror.NewDataLoss(fmt.Sprintf("Incomplete history: expected events [%v-%v] but got events [%v-%v] of length %v: isFirstPage=%v,isLastPage=%v,pageSize=%v",
expectedFirstEventID,
expectedLastEventID,
firstEventID,
lastEventID,
nEvents,
isFirstPage,
isLastPage,
pageSize))
}
func (wh *WorkflowHandler) isFailoverRequest(updateRequest *workflowservice.UpdateNamespaceRequest) bool {
return updateRequest.ReplicationConfig != nil && updateRequest.ReplicationConfig.GetActiveClusterName() != ""
}
func (wh *WorkflowHandler) historyArchived(ctx context.Context, request *workflowservice.GetWorkflowExecutionHistoryRequest, namespaceID namespace.ID) bool {
if request.GetExecution() == nil || request.GetExecution().GetRunId() == "" {
return false
}
getMutableStateRequest := &historyservice.GetMutableStateRequest{
NamespaceId: namespaceID.String(),
Execution: request.Execution,
}
_, err := wh.GetHistoryClient().GetMutableState(ctx, getMutableStateRequest)
if err == nil {
return false
}
switch err.(type) {
case *serviceerror.NotFound:
// the only case in which history is assumed to be archived is if getting mutable state returns entity not found error
return true
}
return false
}
func (wh *WorkflowHandler) getArchivedHistory(
ctx context.Context,
request *workflowservice.GetWorkflowExecutionHistoryRequest,
namespaceID namespace.ID,
) (*workflowservice.GetWorkflowExecutionHistoryResponse, error) {
entry, err := wh.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
URIString := entry.HistoryArchivalState().URI
if URIString == "" {
// if URI is empty, it means the namespace has never enabled for archival.
// the error is not "workflow has passed retention period", because
// we have no way to tell if the requested workflow exists or not.
return nil, errHistoryNotFound
}
URI, err := archiver.NewURI(URIString)
if err != nil {
return nil, err
}
historyArchiver, err := wh.GetArchiverProvider().GetHistoryArchiver(URI.Scheme(), common.FrontendServiceName)
if err != nil {
return nil, err
}
resp, err := historyArchiver.Get(ctx, URI, &archiver.GetHistoryRequest{
NamespaceID: namespaceID.String(),
WorkflowID: request.GetExecution().GetWorkflowId(),
RunID: request.GetExecution().GetRunId(),
NextPageToken: request.GetNextPageToken(),
PageSize: int(request.GetMaximumPageSize()),
})
if err != nil {
return nil, err
}
history := &historypb.History{}
for _, batch := range resp.HistoryBatches {
history.Events = append(history.Events, batch.Events...)
}
return &workflowservice.GetWorkflowExecutionHistoryResponse{
History: history,
NextPageToken: resp.NextPageToken,
Archived: true,
}, nil
}
func (wh *WorkflowHandler) isListRequestPageSizeTooLarge(pageSize int32, namespace string) bool {
return wh.config.EnableReadVisibilityFromES(namespace) &&
pageSize > int32(wh.config.ESIndexMaxResultWindow())
}
// cancelOutstandingPoll cancel outstanding poll if context was canceled and returns true. Otherwise returns false.
func (wh *WorkflowHandler) cancelOutstandingPoll(ctx context.Context, namespaceID namespace.ID, taskQueueType enumspb.TaskQueueType,
taskQueue *taskqueuepb.TaskQueue, pollerID string) bool {
// First check if this err is due to context cancellation. This means client connection to frontend is closed.
if ctx.Err() != context.Canceled {
return false
}
// Our rpc stack does not propagates context cancellation to the other service. Lets make an explicit
// call to matching to notify this poller is gone to prevent any tasks being dispatched to zombie pollers.
_, err := wh.GetMatchingClient().CancelOutstandingPoll(context.Background(), &matchingservice.CancelOutstandingPollRequest{
NamespaceId: namespaceID.String(),
TaskQueueType: taskQueueType,
TaskQueue: taskQueue,
PollerId: pollerID,
})
// We can not do much if this call fails. Just log the error and move on.
if err != nil {
wh.GetLogger().Warn("Failed to cancel outstanding poller.",
tag.WorkflowTaskQueueName(taskQueue.GetName()), tag.Error(err))
}
return true
}
func (wh *WorkflowHandler) checkBadBinary(namespaceEntry *namespace.Namespace, binaryChecksum string) error {
if err := namespaceEntry.VerifyBinaryChecksum(binaryChecksum); err != nil {
return serviceerror.NewInvalidArgument(fmt.Sprintf("Binary %v already marked as bad deployment.", binaryChecksum))
}
return nil
}
func (hs HealthStatus) String() string {
switch hs {
case HealthStatusOK:
return "OK"
case HealthStatusShuttingDown:
return "ShuttingDown"
default:
return "unknown"
}
}
func (wh *WorkflowHandler) validateRetryPolicy(namespace string, retryPolicy *commonpb.RetryPolicy) error {
if retryPolicy == nil {
// By default, if the user does not explicitly set a retry policy for a Workflow, do not perform any retries.
return nil
}
defaultWorkflowRetrySettings := common.FromConfigToDefaultRetrySettings(wh.getDefaultWorkflowRetrySettings(namespace))
common.EnsureRetryPolicyDefaults(retryPolicy, defaultWorkflowRetrySettings)
return common.ValidateRetryPolicy(retryPolicy)
}
func (wh *WorkflowHandler) validateStartWorkflowTimeouts(
request *workflowservice.StartWorkflowExecutionRequest,
) error {
if timestamp.DurationValue(request.GetWorkflowExecutionTimeout()) < 0 {
return errInvalidWorkflowExecutionTimeoutSeconds
}
if timestamp.DurationValue(request.GetWorkflowRunTimeout()) < 0 {
return errInvalidWorkflowRunTimeoutSeconds
}
if timestamp.DurationValue(request.GetWorkflowTaskTimeout()) < 0 {
return errInvalidWorkflowTaskTimeoutSeconds
}
return nil
}
func (wh *WorkflowHandler) validateSignalWithStartWorkflowTimeouts(
request *workflowservice.SignalWithStartWorkflowExecutionRequest,
) error {
if timestamp.DurationValue(request.GetWorkflowExecutionTimeout()) < 0 {
return errInvalidWorkflowExecutionTimeoutSeconds
}
if timestamp.DurationValue(request.GetWorkflowRunTimeout()) < 0 {
return errInvalidWorkflowRunTimeoutSeconds
}
if timestamp.DurationValue(request.GetWorkflowTaskTimeout()) < 0 {
return errInvalidWorkflowTaskTimeoutSeconds
}
return nil
}
func (wh *WorkflowHandler) checkNamespaceMatch(requestNamespace string, tokenNamespace namespace.Name) error {
if !wh.config.EnableTokenNamespaceEnforcement() {
return nil
}
if namespace.Name(requestNamespace) != tokenNamespace {
return errTokenNamespaceMismatch
}
return nil
}
func (wh *WorkflowHandler) metricsScope(ctx context.Context) metrics.Scope {
return interceptor.MetricsScope(ctx, wh.GetLogger())
}
func (wh *WorkflowHandler) makeFakeContinuedAsNewEvent(
_ context.Context,
lastEvent *historypb.HistoryEvent,
) (*historypb.HistoryEvent, error) {
switch lastEvent.EventType {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED:
if lastEvent.GetWorkflowExecutionCompletedEventAttributes().GetNewExecutionRunId() == "" {
return nil, nil
}
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED:
if lastEvent.GetWorkflowExecutionFailedEventAttributes().GetNewExecutionRunId() == "" {
return nil, nil
}
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT:
if lastEvent.GetWorkflowExecutionTimedOutEventAttributes().GetNewExecutionRunId() == "" {
return nil, nil
}
default:
return nil, nil
}
// We need to replace the last event with a continued-as-new event that has at least the
// NewExecutionRunId field. We don't actually need any other fields, since that's the only one
// the client looks at in this case, but copy the last result or failure from the real completed
// event just so it's clear what the result was.
newAttrs := &historypb.WorkflowExecutionContinuedAsNewEventAttributes{}
switch lastEvent.EventType {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED:
attrs := lastEvent.GetWorkflowExecutionCompletedEventAttributes()
newAttrs.NewExecutionRunId = attrs.NewExecutionRunId
newAttrs.LastCompletionResult = attrs.Result
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED:
attrs := lastEvent.GetWorkflowExecutionFailedEventAttributes()
newAttrs.NewExecutionRunId = attrs.NewExecutionRunId
newAttrs.Failure = attrs.Failure
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT:
attrs := lastEvent.GetWorkflowExecutionTimedOutEventAttributes()
newAttrs.NewExecutionRunId = attrs.NewExecutionRunId
newAttrs.Failure = failure.NewTimeoutFailure("workflow timeout", enumspb.TIMEOUT_TYPE_START_TO_CLOSE)
}
return &historypb.HistoryEvent{
EventId: lastEvent.EventId,
EventTime: lastEvent.EventTime,
EventType: enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW,
Version: lastEvent.Version,
TaskId: lastEvent.TaskId,
Attributes: &historypb.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes{
WorkflowExecutionContinuedAsNewEventAttributes: newAttrs,
},
}, nil
}
| 1 | 13,176 | How about if request ID not set, service should generate a random uuid? | temporalio-temporal | go |
@@ -105,7 +105,7 @@ func TestPerformUpdateWithUpdatesDisabled(t *testing.T) {
Reason: ptr("Updates are disabled").(*string),
}})
- u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
+ u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string), | 1 | // Copyright 2014-2016 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 updater
import (
"bytes"
"errors"
"fmt"
"path/filepath"
"reflect"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aws/amazon-ecs-agent/agent/acs/model/ecsacs"
"github.com/aws/amazon-ecs-agent/agent/acs/update_handler/os/mock"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/engine"
"github.com/aws/amazon-ecs-agent/agent/httpclient"
"github.com/aws/amazon-ecs-agent/agent/httpclient/mock"
"github.com/aws/amazon-ecs-agent/agent/sighandlers/exitcodes"
"github.com/aws/amazon-ecs-agent/agent/statemanager"
mock_client "github.com/aws/amazon-ecs-agent/agent/wsclient/mock"
)
func ptr(i interface{}) interface{} {
n := reflect.New(reflect.TypeOf(i))
n.Elem().Set(reflect.ValueOf(i))
return n.Interface()
}
func mocks(t *testing.T, cfg *config.Config) (*updater, *gomock.Controller, *config.Config, *mock_os.MockFileSystem, *mock_client.MockClientServer, *mock_http.MockRoundTripper) {
if cfg == nil {
cfg = &config.Config{
UpdatesEnabled: true,
UpdateDownloadDir: filepath.Clean("/tmp/test/"),
}
}
ctrl := gomock.NewController(t)
mockfs := mock_os.NewMockFileSystem(ctrl)
mockacs := mock_client.NewMockClientServer(ctrl)
mockhttp := mock_http.NewMockRoundTripper(ctrl)
httpClient := httpclient.New(updateDownloadTimeout, false)
httpClient.Transport.(httpclient.OverridableTransport).SetTransport(mockhttp)
u := &updater{
acs: mockacs,
config: cfg,
fs: mockfs,
httpclient: httpClient,
}
return u, ctrl, cfg, mockfs, mockacs, mockhttp
}
func TestStageUpdateWithUpdatesDisabled(t *testing.T) {
u, ctrl, _, _, mockacs, _ := mocks(t, &config.Config{
UpdatesEnabled: false,
})
defer ctrl.Finish()
mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
Reason: ptr("Updates are disabled").(*string),
}})
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
}
func TestPerformUpdateWithUpdatesDisabled(t *testing.T) {
u, ctrl, cfg, _, mockacs, _ := mocks(t, &config.Config{
UpdatesEnabled: false,
})
defer ctrl.Finish()
mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
Reason: ptr("Updates are disabled").(*string),
}})
u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("c54518806ff4d14b680c35784113e1e7478491fe").(*string),
},
})
}
func TestFullUpdateFlow(t *testing.T) {
// Test support for update via other regions' endpoints.
regions := map[string]string{
"us-east-1": "s3.amazonaws.com",
"us-east-2": "s3-us-east-2.amazonaws.com",
"us-west-1": "s3-us-west-1.amazonaws.com",
}
for region, host := range regions {
t.Run(region, func(t *testing.T) {
u, ctrl, cfg, mockfs, mockacs, mockhttp := mocks(t, nil)
defer ctrl.Finish()
var writtenFile bytes.Buffer
gomock.InOrder(
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://"+host+"/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
mockfs.EXPECT().WriteFile(filepath.Clean("/tmp/test/desired-image"), gomock.Any(), gomock.Any()).Return(nil),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
})),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
})),
mockfs.EXPECT().Exit(exitcodes.ExitUpdate),
)
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://" + host + "/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
require.Equal(t, "update-tar-data", writtenFile.String(), "incorrect data written")
u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://" + host + "/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("c54518806ff4d14b680c35784113e1e7478491fe").(*string),
},
})
})
}
}
type nackRequestMatcher struct {
*ecsacs.NackRequest
}
func (m *nackRequestMatcher) Matches(nack interface{}) bool {
other := nack.(*ecsacs.NackRequest)
if m.Cluster != nil && *m.Cluster != *other.Cluster {
return false
}
if m.ContainerInstance != nil && *m.ContainerInstance != *other.ContainerInstance {
return false
}
if m.MessageId != nil && *m.MessageId != *other.MessageId {
return false
}
if m.Reason != nil && *m.Reason != *other.Reason {
return false
}
return true
}
func TestMissingUpdateInfo(t *testing.T) {
u, ctrl, _, _, mockacs, _ := mocks(t, nil)
defer ctrl.Finish()
mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
}})
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
})
}
func (m *nackRequestMatcher) String() string {
return fmt.Sprintf("Nack request matcher %v", m.NackRequest)
}
func TestUndownloadedUpdate(t *testing.T) {
u, ctrl, cfg, _, mockacs, _ := mocks(t, nil)
defer ctrl.Finish()
mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
}})
u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
})
}
func TestDuplicateUpdateMessagesWithSuccess(t *testing.T) {
u, ctrl, cfg, mockfs, mockacs, mockhttp := mocks(t, nil)
defer ctrl.Finish()
var writtenFile bytes.Buffer
gomock.InOrder(
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
mockfs.EXPECT().WriteFile(filepath.Clean("/tmp/test/desired-image"), gomock.Any(), gomock.Any()).Return(nil),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
})),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
})),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid3").(*string),
})),
mockfs.EXPECT().Exit(exitcodes.ExitUpdate),
)
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
// Multiple requests to stage something with the same signature should still
// result in only one download / update procedure.
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
require.Equal(t, "update-tar-data", writtenFile.String(), "incorrect data written")
u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid3").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("c54518806ff4d14b680c35784113e1e7478491fe").(*string),
},
})
}
func TestDuplicateUpdateMessagesWithFailure(t *testing.T) {
u, ctrl, cfg, mockfs, mockacs, mockhttp := mocks(t, nil)
defer ctrl.Finish()
var writtenFile bytes.Buffer
gomock.InOrder(
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(nil, errors.New("test error")),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
Reason: ptr("Unable to download: test error").(*string),
})),
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
mockfs.EXPECT().WriteFile(filepath.Clean("/tmp/test/desired-image"), gomock.Any(), gomock.Any()).Return(nil),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
})),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid3").(*string),
})),
mockfs.EXPECT().Exit(exitcodes.ExitUpdate),
)
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
// Multiple requests to stage something with the same signature where the previous update failed
// should cause another update attempt to be started
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
require.Equal(t, "update-tar-data", writtenFile.String(), "incorrect data written")
u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid3").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("c54518806ff4d14b680c35784113e1e7478491fe").(*string),
},
})
}
func TestNewerUpdateMessages(t *testing.T) {
u, ctrl, cfg, mockfs, mockacs, mockhttp := mocks(t, nil)
defer ctrl.Finish()
var writtenFile bytes.Buffer
gomock.InOrder(
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
mockfs.EXPECT().WriteFile(filepath.Clean("/tmp/test/desired-image"), gomock.Any(), gomock.Any()).Return(nil),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("StageMID").(*string),
})),
mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("StageMID").(*string),
Reason: ptr("New update arrived: StageMIDNew").(*string),
}}),
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/new.tar")).Return(mock_http.SuccessResponse("newer-update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
mockfs.EXPECT().WriteFile(filepath.Clean("/tmp/test/desired-image"), gomock.Any(), gomock.Any()).Return(nil),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("StageMIDNew").(*string),
})),
mockacs.EXPECT().MakeRequest(gomock.Eq(&ecsacs.AckRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
})),
mockfs.EXPECT().Exit(exitcodes.ExitUpdate),
)
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("StageMID").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("6caeef375a080e3241781725b357890758d94b15d7ce63f6b2ff1cb5589f2007").(*string),
},
})
require.Equal(t, "update-tar-data", writtenFile.String(), "incorrect data written")
writtenFile.Reset()
// Never perform, make sure a new hash results in a new stage
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("StageMIDNew").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/new.tar").(*string),
Signature: ptr("9c6ea7bd7d49f95b6d516517e453b965897109bf8a1d6ff3a6e57287049eb2de").(*string),
},
})
require.Equal(t, "newer-update-tar-data", writtenFile.String(), "incorrect data written")
u.performUpdateHandler(statemanager.NewNoopStateManager(), engine.NewTaskEngine(cfg, nil, nil, nil, nil, nil, nil))(&ecsacs.PerformUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("mid2").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("c54518806ff4d14b680c35784113e1e7478491fe").(*string),
},
})
}
func TestValidationError(t *testing.T) {
u, ctrl, _, mockfs, mockacs, mockhttp := mocks(t, nil)
defer ctrl.Finish()
var writtenFile bytes.Buffer
gomock.InOrder(
mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
mockfs.EXPECT().Remove(gomock.Any()),
mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
Cluster: ptr("cluster").(*string),
ContainerInstance: ptr("containerInstance").(*string),
MessageId: ptr("StageMID").(*string),
}}),
)
u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
ClusterArn: ptr("cluster").(*string),
ContainerInstanceArn: ptr("containerInstance").(*string),
MessageId: ptr("StageMID").(*string),
UpdateInfo: &ecsacs.UpdateInfo{
Location: ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
Signature: ptr("Invalid signature").(*string),
},
})
assert.Equal(t, "update-tar-data", writtenFile.String(), "incorrect data written")
}
| 1 | 18,807 | minor: this is an opportunity for you to split these long lines into multiple lines :) | aws-amazon-ecs-agent | go |
@@ -259,7 +259,10 @@ class RequestsParser(object):
req = ensure_is_dict(raw_requests, key, "url")
if not require_url and "url" not in req:
req["url"] = None
- requests.append(self.__parse_request(req))
+ try:
+ requests.append(self.__parse_request(req))
+ except:
+ raise TaurusConfigError("Wrong request:\n %s" % req)
return requests
def extract_requests(self, require_url=True): | 1 | """
Copyright 2017 BlazeMeter 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 mimetypes
import re
from bzt import TaurusConfigError, TaurusInternalException
from bzt.utils import ensure_is_dict, dehumanize_time, get_full_path
VARIABLE_PATTERN = re.compile("\${.+\}")
def has_variable_pattern(val):
return bool(VARIABLE_PATTERN.search(val))
class Request(object):
NAME = "request"
def __init__(self, config, scenario=None):
self.config = config
self.scenario = scenario
def priority_option(self, name, default=None):
val = self.config.get(name, None)
if val is None:
val = self.scenario.get(name, None)
if val is None and default is not None:
val = default
return val
class HTTPRequest(Request):
NAME = "request"
def __init__(self, config, scenario, engine):
self.engine = engine
self.log = self.engine.log.getChild(self.__class__.__name__)
super(HTTPRequest, self).__init__(config, scenario)
msg = "Option 'url' is mandatory for request but not found in %s" % config
self.url = self.config.get("url", TaurusConfigError(msg))
self.label = self.config.get("label", self.url)
self.method = self.config.get("method", "GET")
# TODO: add method to join dicts/lists from scenario/request level?
self.headers = self.config.get("headers", {})
self.keepalive = self.config.get('keepalive', None)
self.timeout = self.config.get('timeout', None)
self.think_time = self.config.get('think-time', None)
self.follow_redirects = self.config.get('follow-redirects', None)
self.body = self.__get_body()
def __get_body(self):
body = self.config.get('body', None)
body_file = self.config.get('body-file', None)
if body_file:
if body:
self.log.warning('body and body-file fields are found, only first will take effect')
else:
body_file_path = self.engine.find_file(body_file)
with open(body_file_path) as fhd:
body = fhd.read()
return body
class HierarchicHTTPRequest(HTTPRequest):
def __init__(self, config, scenario, engine):
super(HierarchicHTTPRequest, self).__init__(config, scenario, engine)
self.upload_files = self.config.get("upload-files", [])
method = self.config.get("method")
if method == "PUT" and len(self.upload_files) > 1:
self.upload_files = self.upload_files[:1]
for file_dict in self.upload_files:
param = file_dict.get("param", None)
if method == "PUT":
file_dict["param"] = ""
if method == "POST" and not param:
raise TaurusConfigError("Items from upload-files must specify parameter name")
path_exc = TaurusConfigError("Items from upload-files must specify path to file")
path = str(file_dict.get("path", path_exc))
if not has_variable_pattern(path): # exclude variables
path = get_full_path(self.engine.find_file(path)) # prepare full path for jmx
else:
msg = "Path '%s' contains variable and can't be expanded. Don't use relative paths in 'upload-files'!"
self.log.warning(msg % path)
file_dict["path"] = path
mime = mimetypes.guess_type(file_dict["path"])[0] or "application/octet-stream"
file_dict.get("mime-type", mime, force_set=True)
self.content_encoding = self.config.get('content-encoding', None)
class IfBlock(Request):
NAME = "if"
def __init__(self, condition, then_clause, else_clause, config):
super(IfBlock, self).__init__(config)
self.condition = condition
self.then_clause = then_clause
self.else_clause = else_clause
def __repr__(self):
then_clause = [repr(req) for req in self.then_clause]
else_clause = [repr(req) for req in self.else_clause]
return "IfBlock(condition=%s, then=%s, else=%s)" % (self.condition, then_clause, else_clause)
class LoopBlock(Request):
NAME = "loop"
def __init__(self, loops, requests, config):
super(LoopBlock, self).__init__(config)
self.loops = loops
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
return "LoopBlock(loops=%s, requests=%s)" % (self.loops, requests)
class WhileBlock(Request):
NAME = "while"
def __init__(self, condition, requests, config):
super(WhileBlock, self).__init__(config)
self.condition = condition
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
return "WhileBlock(condition=%s, requests=%s)" % (self.condition, requests)
class ForEachBlock(Request):
NAME = "foreach"
def __init__(self, input_var, loop_var, requests, config):
super(ForEachBlock, self).__init__(config)
self.input_var = input_var
self.loop_var = loop_var
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
fmt = "ForEachBlock(input=%s, loop_var=%s, requests=%s)"
return fmt % (self.input_var, self.loop_var, requests)
class TransactionBlock(Request):
NAME = "transaction"
def __init__(self, name, requests, include_timers, config, scenario):
super(TransactionBlock, self).__init__(config, scenario)
self.name = name
self.requests = requests
self.include_timers = include_timers
def __repr__(self):
requests = [repr(req) for req in self.requests]
fmt = "TransactionBlock(name=%s, requests=%s, include-timers=%r)"
return fmt % (self.name, requests, self.include_timers)
class IncludeScenarioBlock(Request):
NAME = "include-scenario"
def __init__(self, scenario_name, config):
super(IncludeScenarioBlock, self).__init__(config)
self.scenario_name = scenario_name
def __repr__(self):
return "IncludeScenarioBlock(scenario_name=%r)" % self.scenario_name
class RequestsParser(object):
def __init__(self, scenario, engine):
self.engine = engine
self.scenario = scenario
def __parse_request(self, req):
if 'if' in req:
condition = req.get("if")
# TODO: apply some checks to `condition`?
then_clause = req.get("then", TaurusConfigError("'then' clause is mandatory for 'if' blocks"))
then_requests = self.__parse_requests(then_clause)
else_clause = req.get("else", [])
else_requests = self.__parse_requests(else_clause)
return IfBlock(condition, then_requests, else_requests, req)
elif 'loop' in req:
loops = req.get("loop")
do_block = req.get("do", TaurusConfigError("'do' option is mandatory for 'loop' blocks"))
do_requests = self.__parse_requests(do_block)
return LoopBlock(loops, do_requests, req)
elif 'while' in req:
condition = req.get("while")
do_block = req.get("do", TaurusConfigError("'do' option is mandatory for 'while' blocks"))
do_requests = self.__parse_requests(do_block)
return WhileBlock(condition, do_requests, req)
elif 'foreach' in req:
iteration_str = req.get("foreach")
match = re.match(r'(.+) in (.+)', iteration_str)
if not match:
msg = "'foreach' value should be in format '<elementName> in <collection>' but '%s' found"
raise TaurusConfigError(msg % iteration_str)
loop_var, input_var = match.groups()
do_block = req.get("do", TaurusConfigError("'do' field is mandatory for 'foreach' blocks"))
do_requests = self.__parse_requests(do_block)
return ForEachBlock(input_var, loop_var, do_requests, req)
elif 'transaction' in req:
name = req.get('transaction')
do_block = req.get('do', TaurusConfigError("'do' field is mandatory for transaction blocks"))
do_requests = self.__parse_requests(do_block)
include_timers = req.get('include-timers')
return TransactionBlock(name, do_requests, include_timers, req, self.scenario)
elif 'include-scenario' in req:
name = req.get('include-scenario')
return IncludeScenarioBlock(name, req)
elif 'action' in req:
action = req.get('action')
if action not in ('pause', 'stop', 'stop-now', 'continue'):
raise TaurusConfigError("Action should be either 'pause', 'stop', 'stop-now' or 'continue'")
target = req.get('target', 'current-thread')
if target not in ('current-thread', 'all-threads'):
msg = "Target for action should be either 'current-thread' or 'all-threads' but '%s' found"
raise TaurusConfigError(msg % target)
duration = req.get('pause-duration', None)
if duration is not None:
duration = dehumanize_time(duration)
return ActionBlock(action, target, duration, req)
elif 'set-variables' in req:
mapping = req.get('set-variables')
return SetVariables(mapping, req)
else:
return HierarchicHTTPRequest(req, self.scenario, self.engine)
def __parse_requests(self, raw_requests, require_url=True):
requests = []
for key in range(len(raw_requests)): # pylint: disable=consider-using-enumerate
req = ensure_is_dict(raw_requests, key, "url")
if not require_url and "url" not in req:
req["url"] = None
requests.append(self.__parse_request(req))
return requests
def extract_requests(self, require_url=True):
requests = self.scenario.get("requests", [])
return self.__parse_requests(requests, require_url=require_url)
class ActionBlock(Request):
def __init__(self, action, target, duration, config):
super(ActionBlock, self).__init__(config)
self.action = action
self.target = target
self.duration = duration
class SetVariables(Request):
def __init__(self, mapping, config):
super(SetVariables, self).__init__(config)
self.mapping = mapping
class RequestVisitor(object):
def __init__(self):
self.path = []
def clear_path_cache(self):
self.path = []
def record_path(self, path):
self.path.append(path)
def visit(self, node):
class_name = node.__class__.__name__.lower()
visitor = getattr(self, 'visit_' + class_name, None)
if visitor is not None:
return visitor(node)
raise TaurusInternalException("Visitor for class %s not found" % class_name)
class ResourceFilesCollector(RequestVisitor):
def __init__(self, executor):
"""
:param executor: JMeterExecutor
"""
super(ResourceFilesCollector, self).__init__()
self.executor = executor
def visit_hierarchichttprequest(self, request):
files = []
body_file = request.config.get('body-file')
if body_file and not has_variable_pattern(body_file):
files.append(body_file)
uploads = request.config.get('upload-files', [])
files.extend([x['path'] for x in uploads if not has_variable_pattern(x['path'])])
if 'jsr223' in request.config:
jsrs = request.config.get('jsr223')
if isinstance(jsrs, dict):
jsrs = [jsrs]
for jsr in jsrs:
if 'script-file' in jsr:
files.append(jsr.get('script-file'))
return files
def visit_ifblock(self, block):
files = []
for request in block.then_clause:
files.extend(self.visit(request))
for request in block.else_clause:
files.extend(self.visit(request))
return files
def visit_loopblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_whileblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_foreachblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_transactionblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_includescenarioblock(self, block):
scenario_name = block.scenario_name
if scenario_name in self.path:
msg = "Mutual recursion detected in include-scenario blocks (scenario %s)"
raise TaurusConfigError(msg % scenario_name)
self.record_path(scenario_name)
scenario = self.executor.get_scenario(name=block.scenario_name)
return self.executor.res_files_from_scenario(scenario)
def visit_actionblock(self, _):
return []
def visit_setvariables(self, _):
return []
| 1 | 14,986 | It would be nice to have exception dumped somewhere (debug logs, info logs). | Blazemeter-taurus | py |
@@ -84,6 +84,13 @@ type Topic interface {
// https://github.com/google/go-cloud/blob/master/internal/docs/design.md#as
// for more background.
As(i interface{}) bool
+
+ // As allows providers to expose provider-specific types.
+ //
+ // See
+ // https://github.com/google/go-cloud/blob/master/internal/docs/design.md#as
+ // for more background.
+ MessageAs(m *Message, i interface{}) bool
}
// Subscription receives published messages. | 1 | // Copyright 2018 The Go Cloud 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 defines a set of interfaces that the pubsub package uses to
// interact with the underlying pubsub services.
package driver
import (
"context"
)
// Batcher should gather items into batches to be sent to the pubsub service.
type Batcher interface {
// Add should add an item to the batcher.
Add(ctx context.Context, item interface{}) error
// AddNoWait should add an item to the batcher without blocking.
AddNoWait(item interface{}) <-chan error
// Shutdown should wait for all active calls to Add to finish, then
// return. After Shutdown is called, all calls to Add should fail.
Shutdown()
}
// AckID is the identifier of a message for purposes of acknowledgement.
type AckID interface{}
// Message is data to be published (sent) to a topic and later received from
// subscriptions on that topic.
type Message struct {
// Body contains the content of the message.
Body []byte
// Metadata has key/value pairs describing the message.
Metadata map[string]string
// AckID should be set to something identifying the message on the
// server. It may be passed to Subscription.SendAcks() to acknowledge
// the message. This field should only be set by methods implementing
// Subscription.ReceiveBatch.
AckID AckID
}
// Topic publishes messages.
type Topic interface {
// SendBatch publishes all the messages in ms. This method should
// return only after all the messages are sent, an error occurs, or the
// context is done.
//
// Only the Body and (optionally) Metadata fields of the Messages in ms
// will be set by the caller of SendBatch.
//
// If any message in the batch fails to send, SendBatch should return an
// error.
//
// If there is a transient failure, this method should not retry but
// should return an error for which IsRetryable returns true. The
// concrete API takes care of retry logic.
//
// The slice ms should not be retained past the end of the call to
// SendBatch.
//
// SendBatch may be called concurrently from multiple goroutines.
SendBatch(ctx context.Context, ms []*Message) error
// IsRetryable should report whether err can be retried.
// err will always be a non-nil error returned from SendBatch.
IsRetryable(err error) bool
// As allows providers to expose provider-specific types.
//
// See
// https://github.com/google/go-cloud/blob/master/internal/docs/design.md#as
// for more background.
As(i interface{}) bool
}
// Subscription receives published messages.
type Subscription interface {
// ReceiveBatch should return a batch of messages that have queued up
// for the subscription on the server, up to maxMessages.
//
// If there is a transient failure, this method should not retry but
// should return a nil slice and an error. The concrete API will take
// care of retry logic.
//
// If the service returns no messages for some other reason, this
// method should return the empty slice of messages and not attempt to
// retry.
//
// Implementations of ReceiveBatch should request that the underlying
// service wait some non-zero amount of time before returning, if there
// are no messages yet.
//
// ReceiveBatch should be safe for concurrent access from multiple goroutines.
ReceiveBatch(ctx context.Context, maxMessages int) ([]*Message, error)
// SendAcks should acknowledge the messages with the given ackIDs on
// the server so that they will not be received again for this
// subscription if the server gets the acks before their deadlines.
// This method should return only after all the ackIDs are sent, an
// error occurs, or the context is done.
//
// Only one RPC should be made to send the messages, and the returned
// error should be based on the result of that RPC. Implementations
// that send only one ack at a time should return a non-nil error if
// len(ackIDs) != 1.
//
// SendAcks should be safe for concurrent access from multiple goroutines.
SendAcks(ctx context.Context, ackIDs []AckID) error
// IsRetryable should report whether err can be retried.
// err will always be a non-nil error returned from ReceiveBatch or SendAcks.
IsRetryable(err error) bool
// As allows providers to expose provider-specific types.
//
// See
// https://github.com/google/go-cloud/blob/master/internal/docs/design.md#as
// for more background.
As(i interface{}) bool
}
| 1 | 12,775 | So I don't think this is right, as discussed on #657. | google-go-cloud | go |
@@ -65,10 +65,16 @@ GROUP_IDS = """
SELECT group_id from groups_{0};
"""
-GROUP_USERS = """
+GROUP_ID = """
+ SELECT group_id
+ FROM groups_{1}
+ WHERE group_email = "{0}";
+"""
+
+GROUP_MEMBERS = """
SELECT group_id, member_role, member_type, member_id, member_email
- FROM group_members_{0}
- WHERE member_status = "ACTIVE" and member_type = "USER";
+ FROM group_members_{1}
+ WHERE group_id = "{0}";
"""
BUCKETS = """ | 1 | # Copyright 2017 Google 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.
"""SQL queries to select data from snapshot tables."""
RECORD_COUNT = """
SELECT COUNT(*) FROM {0}_{1};
"""
PROJECT_NUMBERS = """
SELECT project_number from projects_{0};
"""
PROJECT_IAM_POLICIES = """
SELECT p.project_number, p.project_id, p.project_name,
p.lifecycle_state as proj_lifecycle, p.parent_type, p.parent_id,
pol.role, pol.member_type, pol.member_name, pol.member_domain
FROM projects_{0} p INNER JOIN project_iam_policies_{1} pol
ON p.project_number = pol.project_number
ORDER BY p.project_number, pol.role, pol.member_type,
pol.member_domain, pol.member_name
"""
ORGANIZATIONS = """
SELECT org_id, name, display_name, lifecycle_state, creation_time
FROM organizations_{0}
ORDER BY display_name
"""
ORGANIZATION_BY_ID = """
SELECT org_id, name, display_name, lifecycle_state, creation_time
FROM organizations_{0}
WHERE org_id = %s
"""
PROJECT_IAM_POLICIES_RAW = """
SELECT p.project_number, p.project_id, p.project_name, p.lifecycle_state,
p.parent_type, p.parent_id, i.iam_policy
FROM projects_{0} p INNER JOIN raw_project_iam_policies_{1} i
ON p.project_number = i.project_number
ORDER BY p.project_id
"""
ORG_IAM_POLICIES = """
SELECT org_id, iam_policy
FROM raw_org_iam_policies_{0}
"""
LATEST_SNAPSHOT_TIMESTAMP = """
SELECT max(cycle_timestamp) FROM snapshot_cycles
"""
GROUP_IDS = """
SELECT group_id from groups_{0};
"""
GROUP_USERS = """
SELECT group_id, member_role, member_type, member_id, member_email
FROM group_members_{0}
WHERE member_status = "ACTIVE" and member_type = "USER";
"""
BUCKETS = """
SELECT project_number, bucket_id, bucket_name, bucket_kind, bucket_storage_class,
bucket_location, bucket_create_time, bucket_update_time, bucket_selflink,
bucket_lifecycle_raw
FROM buckets_{0};
"""
BUCKETS_BY_PROJECT_ID = """
SELECT bucket_name
FROM buckets_{0}
WHERE project_number = {1};
"""
| 1 | 25,822 | should the group_id = "{0}" be group_id = %s You'd still keep the {} for the group_members_{} for the tablename but make the filter clause parameterized. | forseti-security-forseti-security | py |
@@ -89,7 +89,12 @@ class HierarchicHTTPRequest(HTTPRequest):
raise TaurusConfigError("Items from upload-files must specify parameter name")
path_exc = TaurusConfigError("Items from upload-files must specify path to file")
- file_dict["path"] = get_full_path(self.engine.find_file(file_dict.get("path", path_exc)))
+ path = str(file_dict.get("path", path_exc))
+ if not path.startswith('$'): # exclude varables
+ path = get_full_path(self.engine.find_file(path)) # prepare full path for jmx
+
+ file_dict["path"] = path
+
mime = mimetypes.guess_type(file_dict["path"])[0] or "application/octet-stream"
file_dict.get('mime-type', mime)
self.content_encoding = self.config.get('content-encoding', None) | 1 | """
Copyright 2017 BlazeMeter 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 mimetypes
import re
from bzt import TaurusConfigError, TaurusInternalException
from bzt.utils import ensure_is_dict, dehumanize_time, get_full_path
class Request(object):
NAME = "request"
def __init__(self, config, scenario=None):
self.config = config
self.scenario = scenario
def priority_option(self, name, default=None):
val = self.config.get(name, None)
if val is None:
val = self.scenario.get(name, None)
if val is None and default is not None:
val = default
return val
class HTTPRequest(Request):
NAME = "request"
def __init__(self, config, scenario, engine):
self.engine = engine
self.log = self.engine.log.getChild(self.__class__.__name__)
super(HTTPRequest, self).__init__(config, scenario)
msg = "Option 'url' is mandatory for request but not found in %s" % config
self.url = self.config.get("url", TaurusConfigError(msg))
self.label = self.config.get("label", self.url)
self.method = self.config.get("method", "GET")
# TODO: add method to join dicts/lists from scenario/request level?
self.headers = self.config.get("headers", {})
self.keepalive = self.config.get('keepalive', None)
self.timeout = self.config.get('timeout', None)
self.think_time = self.config.get('think-time', None)
self.follow_redirects = self.config.get('follow-redirects', None)
self.body = self.__get_body()
def __get_body(self):
body = self.config.get('body', None)
body_file = self.config.get('body-file', None)
if body_file:
if body:
self.log.warning('body and body-file fields are found, only first will take effect')
else:
body_file_path = self.engine.find_file(body_file)
with open(body_file_path) as fhd:
body = fhd.read()
return body
class HierarchicHTTPRequest(HTTPRequest):
def __init__(self, config, scenario, engine):
super(HierarchicHTTPRequest, self).__init__(config, scenario, engine)
self.upload_files = self.config.get("upload-files", [])
method = self.config.get("method")
if method == "PUT" and len(self.upload_files) > 1:
self.upload_files = self.upload_files[:1]
for file_dict in self.upload_files:
param = file_dict.get("param", None)
if method == "PUT":
file_dict["param"] = ""
if method == "POST" and not param:
raise TaurusConfigError("Items from upload-files must specify parameter name")
path_exc = TaurusConfigError("Items from upload-files must specify path to file")
file_dict["path"] = get_full_path(self.engine.find_file(file_dict.get("path", path_exc)))
mime = mimetypes.guess_type(file_dict["path"])[0] or "application/octet-stream"
file_dict.get('mime-type', mime)
self.content_encoding = self.config.get('content-encoding', None)
class IfBlock(Request):
NAME = "if"
def __init__(self, condition, then_clause, else_clause, config):
super(IfBlock, self).__init__(config)
self.condition = condition
self.then_clause = then_clause
self.else_clause = else_clause
def __repr__(self):
then_clause = [repr(req) for req in self.then_clause]
else_clause = [repr(req) for req in self.else_clause]
return "IfBlock(condition=%s, then=%s, else=%s)" % (self.condition, then_clause, else_clause)
class LoopBlock(Request):
NAME = "loop"
def __init__(self, loops, requests, config):
super(LoopBlock, self).__init__(config)
self.loops = loops
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
return "LoopBlock(loops=%s, requests=%s)" % (self.loops, requests)
class WhileBlock(Request):
NAME = "while"
def __init__(self, condition, requests, config):
super(WhileBlock, self).__init__(config)
self.condition = condition
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
return "WhileBlock(condition=%s, requests=%s)" % (self.condition, requests)
class ForEachBlock(Request):
NAME = "foreach"
def __init__(self, input_var, loop_var, requests, config):
super(ForEachBlock, self).__init__(config)
self.input_var = input_var
self.loop_var = loop_var
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
fmt = "ForEachBlock(input=%s, loop_var=%s, requests=%s)"
return fmt % (self.input_var, self.loop_var, requests)
class TransactionBlock(Request):
NAME = "transaction"
def __init__(self, name, requests, config, scenario):
super(TransactionBlock, self).__init__(config, scenario)
self.name = name
self.requests = requests
def __repr__(self):
requests = [repr(req) for req in self.requests]
fmt = "TransactionBlock(name=%s, requests=%s)"
return fmt % (self.name, requests)
class IncludeScenarioBlock(Request):
NAME = "include-scenario"
def __init__(self, scenario_name, config):
super(IncludeScenarioBlock, self).__init__(config)
self.scenario_name = scenario_name
def __repr__(self):
return "IncludeScenarioBlock(scenario_name=%r)" % self.scenario_name
class RequestsParser(object):
def __init__(self, scenario, engine):
self.engine = engine
self.scenario = scenario
def __parse_request(self, req):
if 'if' in req:
condition = req.get("if")
# TODO: apply some checks to `condition`?
then_clause = req.get("then", TaurusConfigError("'then' clause is mandatory for 'if' blocks"))
then_requests = self.__parse_requests(then_clause)
else_clause = req.get("else", [])
else_requests = self.__parse_requests(else_clause)
return IfBlock(condition, then_requests, else_requests, req)
elif 'loop' in req:
loops = req.get("loop")
do_block = req.get("do", TaurusConfigError("'do' option is mandatory for 'loop' blocks"))
do_requests = self.__parse_requests(do_block)
return LoopBlock(loops, do_requests, req)
elif 'while' in req:
condition = req.get("while")
do_block = req.get("do", TaurusConfigError("'do' option is mandatory for 'while' blocks"))
do_requests = self.__parse_requests(do_block)
return WhileBlock(condition, do_requests, req)
elif 'foreach' in req:
iteration_str = req.get("foreach")
match = re.match(r'(.+) in (.+)', iteration_str)
if not match:
msg = "'foreach' value should be in format '<elementName> in <collection>' but '%s' found"
raise TaurusConfigError(msg % iteration_str)
loop_var, input_var = match.groups()
do_block = req.get("do", TaurusConfigError("'do' field is mandatory for 'foreach' blocks"))
do_requests = self.__parse_requests(do_block)
return ForEachBlock(input_var, loop_var, do_requests, req)
elif 'transaction' in req:
name = req.get('transaction')
do_block = req.get('do', TaurusConfigError("'do' field is mandatory for transaction blocks"))
do_requests = self.__parse_requests(do_block)
return TransactionBlock(name, do_requests, req, self.scenario)
elif 'include-scenario' in req:
name = req.get('include-scenario')
return IncludeScenarioBlock(name, req)
elif 'action' in req:
action = req.get('action')
if action not in ('pause', 'stop', 'stop-now', 'continue'):
raise TaurusConfigError("Action should be either 'pause', 'stop', 'stop-now' or 'continue'")
target = req.get('target', 'current-thread')
if target not in ('current-thread', 'all-threads'):
msg = "Target for action should be either 'current-thread' or 'all-threads' but '%s' found"
raise TaurusConfigError(msg % target)
duration = req.get('pause-duration', None)
if duration is not None:
duration = dehumanize_time(duration)
return ActionBlock(action, target, duration, req)
elif 'set-variables' in req:
mapping = req.get('set-variables')
return SetVariables(mapping, req)
else:
return HierarchicHTTPRequest(req, self.scenario, self.engine)
def __parse_requests(self, raw_requests, require_url=True):
requests = []
for key in range(len(raw_requests)): # pylint: disable=consider-using-enumerate
req = ensure_is_dict(raw_requests, key, "url")
if not require_url and "url" not in req:
req["url"] = None
requests.append(self.__parse_request(req))
return requests
def extract_requests(self, require_url=True):
requests = self.scenario.get("requests", [])
return self.__parse_requests(requests, require_url=require_url)
class ActionBlock(Request):
def __init__(self, action, target, duration, config):
super(ActionBlock, self).__init__(config)
self.action = action
self.target = target
self.duration = duration
class SetVariables(Request):
def __init__(self, mapping, config):
super(SetVariables, self).__init__(config)
self.mapping = mapping
class RequestVisitor(object):
def __init__(self):
self.path = []
def clear_path_cache(self):
self.path = []
def record_path(self, path):
self.path.append(path)
def visit(self, node):
class_name = node.__class__.__name__.lower()
visitor = getattr(self, 'visit_' + class_name, None)
if visitor is not None:
return visitor(node)
raise TaurusInternalException("Visitor for class %s not found" % class_name)
class ResourceFilesCollector(RequestVisitor):
def __init__(self, executor):
"""
:param executor: JMeterExecutor
"""
super(ResourceFilesCollector, self).__init__()
self.executor = executor
def visit_hierarchichttprequest(self, request):
files = []
body_file = request.config.get('body-file')
if body_file:
files.append(body_file)
if 'jsr223' in request.config:
jsrs = request.config.get('jsr223')
if isinstance(jsrs, dict):
jsrs = [jsrs]
for jsr in jsrs:
if 'script-file' in jsr:
files.append(jsr.get('script-file'))
return files
def visit_ifblock(self, block):
files = []
for request in block.then_clause:
files.extend(self.visit(request))
for request in block.else_clause:
files.extend(self.visit(request))
return files
def visit_loopblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_whileblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_foreachblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_transactionblock(self, block):
files = []
for request in block.requests:
files.extend(self.visit(request))
return files
def visit_includescenarioblock(self, block):
scenario_name = block.scenario_name
if scenario_name in self.path:
msg = "Mutual recursion detected in include-scenario blocks (scenario %s)"
raise TaurusConfigError(msg % scenario_name)
self.record_path(scenario_name)
scenario = self.executor.get_scenario(name=block.scenario_name)
return self.executor.res_files_from_scenario(scenario)
def visit_actionblock(self, _):
return []
def visit_setvariables(self, _):
return []
| 1 | 14,674 | Path can contain variable pattern in the middle. Also, `$` is not enough to tell if this is JMeter variable. We have correct variable detecting somewhere in our code. | Blazemeter-taurus | py |
@@ -20,6 +20,11 @@ class FormTestModel extends Model
{
return ['dropdown', 'options'];
}
+
+ public function staticMethodOptions()
+ {
+ return ['static', 'method'];
+ }
}
class FormHelper | 1 | <?php
use Backend\Widgets\Form;
use Illuminate\Database\Eloquent\Model;
use October\Tests\Fixtures\Backend\Models\UserFixture;
class FormTestModel extends Model
{
public function modelCustomOptionsMethod()
{
return ['model', 'custom', 'options'];
}
public function getFieldNameOnModelOptionsMethodOptions()
{
return ['model', 'field name', 'options method'];
}
public function getDropdownOptions()
{
return ['dropdown', 'options'];
}
}
class FormHelper
{
public static function staticMethodOptions()
{
return ['static', 'method'];
}
}
class FormTest extends PluginTestCase
{
public function testRestrictedFieldWithUserWithNoPermissions()
{
$user = new UserFixture;
$this->actingAs($user);
$form = $this->restrictedFormFixture();
$form->render();
$this->assertNull($form->getField('testRestricted'));
}
public function testRestrictedFieldWithUserWithWrongPermissions()
{
$user = new UserFixture;
$this->actingAs($user->withPermission('test.wrong_permission', true));
$form = $this->restrictedFormFixture();
$form->render();
$this->assertNull($form->getField('testRestricted'));
}
public function testRestrictedFieldWithUserWithRightPermissions()
{
$user = new UserFixture;
$this->actingAs($user->withPermission('test.access_field', true));
$form = $this->restrictedFormFixture();
$form->render();
$this->assertNotNull($form->getField('testRestricted'));
}
public function testRestrictedFieldWithUserWithRightWildcardPermissions()
{
$user = new UserFixture;
$this->actingAs($user->withPermission('test.access_field', true));
$form = new Form(null, [
'model' => new FormTestModel,
'arrayName' => 'array',
'fields' => [
'testField' => [
'type' => 'text',
'label' => 'Test 1'
],
'testRestricted' => [
'type' => 'text',
'label' => 'Test 2',
'permission' => 'test.*'
]
]
]);
$form->render();
$this->assertNotNull($form->getField('testRestricted'));
}
public function testRestrictedFieldWithSuperuser()
{
$user = new UserFixture;
$this->actingAs($user->asSuperUser());
$form = $this->restrictedFormFixture();
$form->render();
$this->assertNotNull($form->getField('testRestricted'));
}
public function testRestrictedFieldSinglePermissionWithUserWithWrongPermissions()
{
$user = new UserFixture;
$this->actingAs($user->withPermission('test.wrong_permission', true));
$form = $this->restrictedFormFixture(true);
$form->render();
$this->assertNull($form->getField('testRestricted'));
}
public function testRestrictedFieldSinglePermissionWithUserWithRightPermissions()
{
$user = new UserFixture;
$this->actingAs($user->withPermission('test.access_field', true));
$form = $this->restrictedFormFixture(true);
$form->render();
$this->assertNotNull($form->getField('testRestricted'));
}
public function testCheckboxlistTrigger()
{
$form = new Form(null, [
'model' => new FormTestModel,
'arrayName' => 'array',
'fields' => [
'trigger' => [
'type' => 'checkboxlist',
'options' => [
'1' => 'Value One'
]
],
'triggered' => [
'type' => 'text',
'trigger' => [
'field' => 'trigger[]',
'action' => 'show',
'condition' => 'value[1]'
]
]
]
]);
$form->render();
$attributes = $form->getField('triggered')->getAttributes('container', false);
$this->assertEquals('[name="array[trigger][]"]', array_get($attributes, 'data-trigger'));
}
public function testOptionsGeneration()
{
$form = new Form(null, [
'model' => new FormTestModel,
'arrayName' => 'array',
'fields' => [
'static_method_options' => [
'type' => 'dropdown',
'options' => '\FormHelper::staticMethodOptions',
'expect' => ['static', 'method'],
],
'callable_options' => [
'type' => 'dropdown',
'options' => [\FormHelper::class, 'staticMethodOptions'],
'expect' => ['static', 'method'],
],
'model_method_options' => [
'type' => 'dropdown',
'options' => 'modelCustomOptionsMethod',
'expect' => ['model', 'custom', 'options'],
],
'defined_options' => [
'type' => 'dropdown',
'options' => ['value1', 'value2'],
'expect' => ['value1', 'value2'],
],
'defined_options_key_value' => [
'type' => 'dropdown',
'options' => [
'key1' => 'value1',
'key2' => 'value2',
],
'expect' => [
'key1' => 'value1',
'key2' => 'value2',
],
],
'field_name_on_model_options_method' => [
'type' => 'dropdown',
'expect' => ['model', 'field name', 'options method'],
],
'get_dropdown_options_method' => [
'type' => 'dropdown',
'expect' => ['dropdown', 'options'],
],
]
]);
$form->render();
foreach ($form->getFields() as $name => $field) {
$this->assertEquals($field->options(), $field->config['expect']);
}
}
protected function restrictedFormFixture(bool $singlePermission = false)
{
return new Form(null, [
'model' => new FormTestModel,
'arrayName' => 'array',
'fields' => [
'testField' => [
'type' => 'text',
'label' => 'Test 1'
],
'testRestricted' => [
'type' => 'text',
'label' => 'Test 2',
'permissions' => ($singlePermission) ? 'test.access_field' : [
'test.access_field'
]
]
]
]);
}
}
| 1 | 19,137 | @bennothommo can you revert this section? It shouldn't be required. | octobercms-october | php |
@@ -92,9 +92,13 @@ module Ncr
"ncr"
end
- # @todo - this is pretty ugly
def public_identifier
- self.cart.id
+ fiscal_year = self.created_at.year
+ if self.created_at.month >= 10
+ fiscal_year += 1
+ end
+ fiscal_year = fiscal_year % 100 # convert to two-digit
+ "FY" + fiscal_year.to_s.rjust(2, "0") + " ##{self.id}"
end
def total_price | 1 | module Ncr
# Make sure all table names use 'ncr_XXX'
def self.table_name_prefix
'ncr_'
end
DATA = YAML.load_file("#{Rails.root}/config/data/ncr.yaml")
EXPENSE_TYPES = %w(BA61 BA80)
BUILDING_NUMBERS = DATA['BUILDING_NUMBERS']
OFFICES = DATA['OFFICES']
class WorkOrder < ActiveRecord::Base
# TODO include ProposalDelegate
has_one :proposal, as: :client_data
# TODO remove the dependence
has_one :cart, through: :proposal
after_initialize :set_defaults
# @TODO: use integer number of cents to avoid floating point issues
validates :amount, numericality: {
greater_than_or_equal_to: 0,
less_than_or_equal_to: 3000
}
validates :expense_type, inclusion: {in: EXPENSE_TYPES}, presence: true
validates :vendor, presence: true
validates :building_number, presence: true
# TODO validates :proposal, presence: true
def set_defaults
self.not_to_exceed ||= false
self.emergency ||= false
end
# @todo - this is an awkward dance due to the lingering Cart model. Remove
# that dependence
def init_and_save_cart(approver_email, requester)
cart = Cart.create(
proposal_attributes: {flow: 'linear', client_data: self}
)
cart.set_requester(requester)
self.add_approvals(approver_email)
Dispatcher.deliver_new_cart_emails(cart)
cart
end
def update_cart(approver_email, cart)
cart.proposal.approvals.destroy_all
self.add_approvals(approver_email)
cart.restart!
cart
end
def add_approvals(approver_email)
emails = [approver_email] + self.system_approvers
if self.emergency
emails.each {|email| self.cart.add_observer(email) }
# skip state machine
self.proposal.update_attribute(:status, 'approved')
else
emails.each {|email| self.cart.add_approver(email) }
end
end
# Ignore values in certain fields if they aren't relevant. May want to
# split these into different models
def self.relevant_fields(expense_type)
fields = [:description, :amount, :expense_type, :vendor, :not_to_exceed,
:building_number, :office]
case expense_type
when "BA61"
fields + [:emergency]
when "BA80"
fields + [:rwa_number, :code]
end
end
def relevant_fields
Ncr::WorkOrder.relevant_fields(self.expense_type)
end
# Methods for Client Data interface
def fields_for_display
attributes = self.relevant_fields
attributes.map{|key| [WorkOrder.human_attribute_name(key), self[key]]}
end
def client
"ncr"
end
# @todo - this is pretty ugly
def public_identifier
self.cart.id
end
def total_price
self.amount || 0.0
end
# may be replaced with paper-trail or similar at some point
def version
self.updated_at.to_i
end
protected
def system_approvers
if self.expense_type == 'BA61'
[
ENV["NCR_BA61_TIER1_BUDGET_MAILBOX"] || '[email protected]',
ENV["NCR_BA61_TIER2_BUDGET_MAILBOX"] || '[email protected]'
]
else
[ENV["NCR_BA80_BUDGET_MAILBOX"] || '[email protected]']
end
end
end
end
| 1 | 12,966 | Minor: maybe move the above to a `#fiscal_year` method? | 18F-C2 | rb |
@@ -62,3 +62,13 @@ class BuildTest(QuiltTestCase):
'Expected dataframes to have same # columns'
del os.environ["QUILT_PACKAGE_FORMAT"]
# TODO add more integrity checks, incl. negative test cases
+
+ def test_generate_buildfile(self):
+ mydir = os.path.dirname(__file__)
+ path = os.path.join(mydir, 'data')
+ buildfilepath = os.path.join(path, 'build.yml')
+ assert not os.path.exists(buildfilepath)
+ build.generate_build_file(path)
+ assert os.path.exists(buildfilepath)
+ build.build_package('test_hdf5', 'generated', buildfilepath)
+ os.remove(buildfilepath) | 1 | """
Test the build process
"""
#TODO: we should really test the CLI interface itself, rather than
#the functions that cli calls
import os
try:
import fastparquet
except ImportError:
fastparquet = None
import pytest
from quilt.tools import build
from quilt.tools.const import FORMAT_PARQ
from .utils import QuiltTestCase
PACKAGE = 'groot'
class BuildTest(QuiltTestCase):
def test_build_hdf5(self):
"""
Test compilation
"""
mydir = os.path.dirname(__file__)
path = os.path.join(mydir, './build.yml')
build.build_package('test_hdf5', PACKAGE, path)
# TODO load DFs based on contents of .yml file at PATH
# not hardcoded vals (this will require loading modules from variable
# names, probably using __module__)
from quilt.data.test_hdf5.groot import csv, tsv, xls
rows = len(csv.index)
assert rows == len(tsv.index) and rows == len(xls.index), \
'Expected dataframes to have same # rows'
cols = len(csv.columns)
print(csv.columns, xls.columns, tsv.columns)
assert cols == len(tsv.columns) and cols == len(xls.columns), \
'Expected dataframes to have same # columns'
# TODO add more integrity checks, incl. negative test cases
@pytest.mark.skipif("fastparquet is None")
def test_build_parquet(self):
"""
Test compilation
"""
os.environ["QUILT_PACKAGE_FORMAT"] = FORMAT_PARQ
mydir = os.path.dirname(__file__)
path = os.path.join(mydir, './build.yml')
build.build_package('test_parquet', PACKAGE, path)
# TODO load DFs based on contents of .yml file at path
# not hardcoded vals (this will require loading modules from variable
# names, probably using __module__)
from quilt.data.test_parquet.groot import csv, tsv, xls
rows = len(csv.index)
assert rows == len(tsv.index) and rows == len(xls.index), \
'Expected dataframes to have same # rows'
cols = len(csv.columns)
print(csv.columns, xls.columns, tsv.columns)
assert cols == len(tsv.columns) and cols == len(xls.columns), \
'Expected dataframes to have same # columns'
del os.environ["QUILT_PACKAGE_FORMAT"]
# TODO add more integrity checks, incl. negative test cases
| 1 | 14,866 | You should use the current directory instead - it's a temporary directory that will get removed when the test is done. | quiltdata-quilt | py |
@@ -549,7 +549,7 @@ public class ContainerizedDispatchManagerTest {
this.containerizedDispatchManager.getExecutionDispatcher(this.flow1.getExecutionId()));
thread.start();
synchronized (thread) {
- thread.wait();
+ thread.join();
}
assertThat(flow1.getStatus()).isEqualTo(Status.FAILED);
verify(onExecutionEventListener).onExecutionEvent(this.flow1, Constants.RESTART_FLOW); | 1 | /*
* Copyright 2020 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.executor;
import static azkaban.Constants.ConfigurationKeys.AZKABAN_EXECUTOR_REVERSE_PROXY_HOSTNAME;
import static azkaban.Constants.ConfigurationKeys.AZKABAN_EXECUTOR_REVERSE_PROXY_PORT;
import static azkaban.executor.ExecutorApiClientTest.REVERSE_PROXY_HOST;
import static azkaban.executor.ExecutorApiClientTest.REVERSE_PROXY_PORT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import azkaban.Constants;
import azkaban.Constants.ConfigurationKeys;
import azkaban.Constants.ContainerizedDispatchManagerProperties;
import azkaban.Constants.FlowParameters;
import azkaban.DispatchMethod;
import azkaban.event.Event;
import azkaban.event.EventData;
import azkaban.event.EventListener;
import azkaban.executor.container.ContainerizedDispatchManager;
import azkaban.executor.container.ContainerizedImpl;
import azkaban.executor.container.ContainerizedImplType;
import azkaban.metrics.CommonMetrics;
import azkaban.metrics.ContainerizationMetrics;
import azkaban.metrics.DummyContainerizationMetricsImpl;
import azkaban.metrics.MetricsManager;
import azkaban.spi.EventType;
import azkaban.user.User;
import azkaban.utils.FileIOUtils.LogData;
import azkaban.utils.Pair;
import azkaban.utils.Props;
import azkaban.utils.TestUtils;
import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.concurrent.NotThreadSafe;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ContainerizedDispatchManagerTest {
private final CommonMetrics commonMetrics = new CommonMetrics(
new MetricsManager(new MetricRegistry()));
private Map<Integer, Pair<ExecutionReference, ExecutableFlow>> activeFlows = new HashMap<>();
private Map<Integer, Pair<ExecutionReference, ExecutableFlow>> unfinishedFlows = new
HashMap<>();
private List<Pair<ExecutionReference, ExecutableFlow>> queuedFlows = new
ArrayList<>();
private ExecutorLoader loader;
private ExecutorApiGateway apiGateway;
private ContainerizedImpl containerizedImpl;
private ContainerizedDispatchManager containerizedDispatchManager;
private Props props;
private User user;
private ExecutableFlow flow1;
private ExecutableFlow flow2;
private ExecutableFlow flow3;
private ExecutableFlow flow4;
private ExecutableFlow flow5;
private ExecutableFlow flow6;
private ExecutableFlow flow7;
private ExecutableFlow flow8;
private ExecutionReference ref1;
private ExecutionReference ref2;
private ExecutionReference ref3;
private EventListener eventListener;
private ContainerizationMetrics containerizationMetrics;
@Before
public void setup() throws Exception {
this.props = new Props();
this.user = TestUtils.getTestUser();
this.loader = mock(ExecutorLoader.class);
this.apiGateway = mock(ExecutorApiGateway.class);
this.containerizedImpl = mock(ContainerizedImpl.class);
this.props.put(Constants.ConfigurationKeys.MAX_CONCURRENT_RUNS_ONEFLOW, 1);
this.props.put(ContainerizedDispatchManagerProperties.CONTAINERIZED_IMPL_TYPE,
ContainerizedImplType.KUBERNETES.name());
this.flow1 = TestUtils.createTestExecutableFlow("exectest1", "exec1", DispatchMethod.CONTAINERIZED);
this.flow2 = TestUtils.createTestExecutableFlow("exectest1", "exec2", DispatchMethod.CONTAINERIZED);
this.flow3 = TestUtils.createTestExecutableFlow("exectest1", "exec2", DispatchMethod.CONTAINERIZED);
this.flow4 = TestUtils.createTestExecutableFlow("exectest1", "exec2", DispatchMethod.CONTAINERIZED);
this.flow5 = TestUtils.createTestExecutableFlowFromYaml("basicflowyamltest", "basic_flow");
this.flow6 = TestUtils.createTestExecutableFlow("exectest1", "exec2"
, DispatchMethod.POLL);
this.flow7 = TestUtils.createTestExecutableFlow("exectest1", "exec2"
, DispatchMethod.POLL);
this.flow8 = TestUtils.createTestExecutableFlow("exectest1", "exec2"
, DispatchMethod.CONTAINERIZED);
this.flow1.setExecutionId(1);
this.flow2.setExecutionId(2);
this.flow3.setExecutionId(3);
this.flow4.setExecutionId(4);
this.flow5.setExecutionId(5);
this.flow5.setDispatchMethod(DispatchMethod.CONTAINERIZED);
this.flow6.setExecutionId(6);
final ExecutionOptions options = new ExecutionOptions();
final Map<String, String> flowParam = new HashMap<>();
flowParam.put(FlowParameters.FLOW_PARAM_DISPATCH_EXECUTION_TO_CONTAINER, "true");
options.addAllFlowParameters(flowParam);
this.flow6.setExecutionOptions(options);
this.flow7.setExecutionId(7);
final ExecutionOptions options8 = new ExecutionOptions();
final Map<String, String> flowParam8 = new HashMap<>();
flowParam8.put(ExecutionOptions.USE_EXECUTOR, "1");
options8.addAllFlowParameters(flowParam8);
this.flow8.setExecutionOptions(options8);
this.flow8.setExecutionId(8);
this.ref1 = new ExecutionReference(this.flow1.getExecutionId(), null, DispatchMethod.CONTAINERIZED);
this.ref2 = new ExecutionReference(this.flow2.getExecutionId(), null, DispatchMethod.CONTAINERIZED);
this.ref3 = new ExecutionReference(this.flow3.getExecutionId(), null, DispatchMethod.CONTAINERIZED);
this.activeFlows = ImmutableMap
.of(this.flow2.getExecutionId(), new Pair<>(this.ref2, this.flow2),
this.flow3.getExecutionId(), new Pair<>(this.ref3, this.flow3));
when(this.loader.fetchActiveFlows()).thenReturn(this.activeFlows);
when(this.loader.fetchActiveFlowByExecId(flow1.getExecutionId())).thenReturn(
new Pair<ExecutionReference, ExecutableFlow>(new ExecutionReference(flow1.getExecutionId(), DispatchMethod.CONTAINERIZED), flow1));
this.queuedFlows = ImmutableList.of(new Pair<>(this.ref1, this.flow1));
when(this.loader.fetchQueuedFlows(Status.READY)).thenReturn(this.queuedFlows);
Pair<ExecutionReference, ExecutableFlow> executionReferencePair =
new Pair<ExecutionReference, ExecutableFlow>(new ExecutionReference(
flow1.getExecutionId(), new Executor(1, "host", 2021, true), DispatchMethod.CONTAINERIZED),
flow1);
when(this.loader.fetchUnfinishedFlows()).thenReturn(ImmutableMap.of(flow1.getExecutionId(),
executionReferencePair));
this.eventListener = new DummyEventListener();
this.containerizationMetrics = new DummyContainerizationMetricsImpl();
}
@Test
public void testRampUpDispatchMethod() throws Exception {
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(0);
for (int i = 0; i < 100; i++) {
DispatchMethod dispatchMethod = this.containerizedDispatchManager.getDispatchMethod();
this.flow5.setDispatchMethod(dispatchMethod);
Status startStatus = this.containerizedDispatchManager.getStartStatus(this.flow5);
assertThat(dispatchMethod).isEqualTo(DispatchMethod.POLL);
assertThat(startStatus).isEqualTo(Status.PREPARING);
}
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(100);
for (int i = 0; i < 100; i++) {
DispatchMethod dispatchMethod = this.containerizedDispatchManager.getDispatchMethod();
this.flow5.setDispatchMethod(dispatchMethod);
Status startStatus = this.containerizedDispatchManager.getStartStatus(this.flow5);
assertThat(dispatchMethod).isEqualTo(DispatchMethod.CONTAINERIZED);
assertThat(startStatus).isEqualTo(Status.READY);
}
}
/**
* This test case is verifying that if dispatch method is marked for containerization in flow
* parameter then it should be respected first. If not then it should follow rest of the
* criteria.
* @throws Exception
*/
@Test
public void testFlowParamForDispatchMethod() throws Exception {
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(0);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of("ALL"));
DispatchMethod dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow6);
Assert.assertEquals(DispatchMethod.CONTAINERIZED, dispatchMethod);
DispatchMethod dispatchMethodFor7 =
this.containerizedDispatchManager.getDispatchMethod(this.flow7);
Assert.assertEquals(DispatchMethod.POLL, dispatchMethodFor7);
}
/**
* This test case is verifying that if useExecutor flow param is set then dispatch method
* should be POLL.
* @throws Exception
*/
@Test
public void testFlowParamForUseExecutor() throws Exception {
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(0);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of("ALL"));
DispatchMethod dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow8);
Assert.assertEquals(DispatchMethod.POLL, dispatchMethod);
}
@Test
public void testAllowAndDenyList() throws Exception {
// Flow 5 comprises of "command" and "noop" jobtypes
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(10);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of("ALL"));
DispatchMethod dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
this.flow5.setDispatchMethod(dispatchMethod);
Status startStatus = this.containerizedDispatchManager.getStartStatus(this.flow5);
Assert.assertEquals(DispatchMethod.CONTAINERIZED, dispatchMethod);
Assert.assertEquals(Status.READY, startStatus);
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(0);
dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
this.flow5.setDispatchMethod(dispatchMethod);
startStatus = this.containerizedDispatchManager.getStartStatus(this.flow5);
Assert.assertEquals(DispatchMethod.POLL, dispatchMethod);
Assert.assertEquals(Status.PREPARING, startStatus);
this.containerizedDispatchManager.getContainerRampUpCriteria().setRampUp(100);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of("java", "command",
"noop"));
dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
Assert.assertEquals(DispatchMethod.CONTAINERIZED, dispatchMethod);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of("java", "command"));
dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
Assert.assertEquals(DispatchMethod.POLL, dispatchMethod);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of());
dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
Assert.assertEquals(DispatchMethod.POLL, dispatchMethod);
this.containerizedDispatchManager.getContainerJobTypeCriteria().updateAllowList(ImmutableSet.of("ALL"));
this.containerizedDispatchManager.getContainerProxyUserCriteria().appendDenyList(ImmutableSet.of(
"azktest", "azkdata"));
dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
Assert.assertEquals(DispatchMethod.CONTAINERIZED, dispatchMethod);
this.flow5.addAllProxyUsers(ImmutableSet.of("azktest"));
dispatchMethod = this.containerizedDispatchManager.getDispatchMethod(this.flow5);
Assert.assertEquals(DispatchMethod.POLL, dispatchMethod);
}
@Test
public void testFetchAllActiveFlows() throws Exception {
initializeContainerizedDispatchImpl();
initializeUnfinishedFlows();
final List<ExecutableFlow> flows = this.containerizedDispatchManager.getRunningFlows();
this.unfinishedFlows.values()
.forEach(pair -> assertThat(flows.contains(pair.getSecond())).isTrue());
}
@Test
public void testFetchAllActiveFlowIds() throws Exception {
initializeContainerizedDispatchImpl();
initializeUnfinishedFlows();
assertThat(this.containerizedDispatchManager.getRunningFlowIds())
.isEqualTo(new ArrayList<>(this.unfinishedFlows.keySet()));
}
@Test
public void testFetchAllQueuedFlowIds() throws Exception {
initializeContainerizedDispatchImpl();
assertThat(this.containerizedDispatchManager.getQueuedFlowIds())
.isEqualTo(ImmutableList.of(this.flow1.getExecutionId()));
}
@Test
public void testFetchQueuedFlowSize() throws Exception {
initializeContainerizedDispatchImpl();
assertThat(this.containerizedDispatchManager.getQueuedFlowSize())
.isEqualTo(this.queuedFlows.size());
}
@Test
public void testFetchActiveFlowByProject() throws Exception {
initializeContainerizedDispatchImpl();
initializeUnfinishedFlows();
final List<Integer> executions = this.containerizedDispatchManager
.getRunningFlows(this.flow2.getProjectId(), this.flow2.getFlowId());
assertThat(executions.contains(this.flow2.getExecutionId())).isTrue();
assertThat(executions.contains(this.flow3.getExecutionId())).isTrue();
assertThat(this.containerizedDispatchManager
.isFlowRunning(this.flow2.getProjectId(), this.flow2.getFlowId()))
.isTrue();
assertThat(this.containerizedDispatchManager
.isFlowRunning(this.flow3.getProjectId(), this.flow3.getFlowId()))
.isTrue();
}
@Test
public void testSubmitFlows() throws Exception {
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.submitExecutableFlow(this.flow1, this.user.getUserId());
Assert.assertEquals(this.containerizedDispatchManager.eventListener, this.eventListener);
this.containerizedDispatchManager.fireEventListeners(Event.create(flow1,
EventType.FLOW_STATUS_CHANGED,
new EventData(this.flow1)));
verify(this.loader).uploadExecutableFlow(this.flow1);
}
@Test
public void testSubmitFlowsExceedingMaxConcurrentRuns() throws Exception {
initializeContainerizedDispatchImpl();
this.props.put(ConfigurationKeys.CONCURRENT_RUNS_ONEFLOW_WHITELIST, "exectest1,"
+ "exec2,3");
submitFlow(this.flow2, this.ref2);
submitFlow(this.flow3, this.ref3);
assertThatThrownBy(() -> this.containerizedDispatchManager
.submitExecutableFlow(this.flow4, this.user.getUserId
())).isInstanceOf(ExecutorManagerException.class).hasMessageContaining("Flow " + this
.flow4.getId() + " has more than 1 concurrent runs. Skipping");
}
@Test
public void testSubmitFlowsConcurrentWhitelist() throws Exception {
initializeContainerizedDispatchImpl();
this.props.put(Constants.ConfigurationKeys.MAX_CONCURRENT_RUNS_ONEFLOW, 1);
submitFlow(this.flow2, this.ref2);
submitFlow(this.flow3, this.ref3);
assertThatThrownBy(() -> this.containerizedDispatchManager
.submitExecutableFlow(this.flow4, this.user.getUserId
())).isInstanceOf(ExecutorManagerException.class).hasMessageContaining("Flow " + this
.flow4.getId() + " has more than 1 concurrent runs. Skipping");
}
@Test
public void testSubmitFlowsWithSkipOption() throws Exception {
initializeContainerizedDispatchImpl();
submitFlow(this.flow2, this.ref2);
this.flow3.getExecutionOptions().setConcurrentOption(ExecutionOptions.CONCURRENT_OPTION_SKIP);
assertThatThrownBy(
() -> this.containerizedDispatchManager
.submitExecutableFlow(this.flow3, this.user.getUserId()))
.isInstanceOf(ExecutorManagerException.class).hasMessageContaining(
"Flow " + this.flow3.getId() + " is already running. Skipping execution.");
}
@Test
public void testSetFlowLock() throws Exception {
initializeContainerizedDispatchImpl();
// trying to execute a locked flow should raise an error
this.flow1.setLocked(true);
final String msg = this.containerizedDispatchManager
.submitExecutableFlow(this.flow1, this.user.getUserId());
assertThat(msg).isEqualTo("Flow derived-member-data for project flow is locked.");
// should succeed after unlocking the flow
this.flow1.setLocked(false);
this.containerizedDispatchManager.submitExecutableFlow(this.flow1, this.user.getUserId());
verify(this.loader).uploadExecutableFlow(this.flow1);
}
/* Test disabling queue process thread to pause dispatching */
@Test
public void testDisablingQueueProcessThread() throws Exception {
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.start();
Assert.assertEquals(this.containerizedDispatchManager.isQueueProcessorThreadActive(), true);
this.containerizedDispatchManager.disableQueueProcessorThread();
Assert.assertEquals(this.containerizedDispatchManager.isQueueProcessorThreadActive(), false);
this.containerizedDispatchManager.enableQueueProcessorThread();
}
/* Test renabling queue process thread to pause restart dispatching */
@Test
public void testEnablingQueueProcessThread() throws Exception {
initializeContainerizedDispatchImpl();
this.containerizedDispatchManager.start();
this.containerizedDispatchManager.disableQueueProcessorThread();
Assert.assertEquals(this.containerizedDispatchManager.isQueueProcessorThreadActive(), false);
this.containerizedDispatchManager.enableQueueProcessorThread();
Assert.assertEquals(this.containerizedDispatchManager.isQueueProcessorThreadActive(), true);
}
private void submitFlow(final ExecutableFlow flow, final ExecutionReference ref) throws
Exception {
when(this.loader.fetchUnfinishedFlows()).thenReturn(this.unfinishedFlows);
when(this.loader.fetchExecutableFlow(flow.getExecutionId())).thenReturn(flow);
this.containerizedDispatchManager.submitExecutableFlow(flow, this.user.getUserId());
this.unfinishedFlows.put(flow.getExecutionId(), new Pair<>(ref, flow));
}
private void initializeUnfinishedFlows() throws Exception {
this.unfinishedFlows = ImmutableMap
.of(this.flow1.getExecutionId(), new Pair<>(this.ref1, this.flow1),
this.flow2.getExecutionId(), new Pair<>(this.ref2, this.flow2),
this.flow3.getExecutionId(), new Pair<>(this.ref3, this.flow3));
when(this.loader.fetchUnfinishedFlows()).thenReturn(this.unfinishedFlows);
}
private void initializeContainerizedDispatchImpl() throws Exception{
this.containerizedDispatchManager =
new ContainerizedDispatchManager(this.props, this.loader,
this.commonMetrics,
this.apiGateway, this.containerizedImpl, null, null, this.eventListener,
this.containerizationMetrics);
}
@Test
public void testGetFlowLogs() throws Exception {
WrappedExecutorApiClient apiClient =
new WrappedExecutorApiClient(createContainerDispatchEnabledProps(this.props));
ContainerizedDispatchManager dispatchManager = createDefaultDispatchWithGateway(apiClient);
apiClient.setNextHttpPostResponse(WrappedExecutorApiClient.DEFAULT_LOG_JSON);
LogData logResponse = dispatchManager.getExecutableFlowLog(this.flow1, 0, 1024);
Assert.assertEquals(WrappedExecutorApiClient.DEFAULT_LOG_TEXT, logResponse.getData());
Assert.assertEquals(apiClient.getExpectedReverseProxyContainerizedURI(),
apiClient.getLastBuildExecutorUriRespone());
}
@Test
public void testGetJobLogs() throws Exception {
WrappedExecutorApiClient apiClient =
new WrappedExecutorApiClient(createContainerDispatchEnabledProps(this.props));
ContainerizedDispatchManager dispatchManager = createDefaultDispatchWithGateway(apiClient);
apiClient.setNextHttpPostResponse(WrappedExecutorApiClient.DEFAULT_LOG_JSON);
LogData logResponse = dispatchManager.getExecutionJobLog(this.flow1, "job1",0, 1, 1024);
Assert.assertEquals(WrappedExecutorApiClient.DEFAULT_LOG_TEXT, logResponse.getData());
Assert.assertEquals(apiClient.getExpectedReverseProxyContainerizedURI(),
apiClient.getLastBuildExecutorUriRespone());
}
@Test
public void testCancelPreparingFlow() throws Exception {
initializeContainerizedDispatchImpl();
testCancelUnreachableFlowHelper(Status.PREPARING);
}
@Test
public void testCancelDispatchingFlow() throws Exception {
initializeContainerizedDispatchImpl();
testCancelUnreachableFlowHelper(Status.DISPATCHING);
}
@Test
public void testCancelRunningFlow() throws Exception {
initializeContainerizedDispatchImpl();
testCancelUnreachableFlowHelper(Status.RUNNING);
}
private void testCancelUnreachableFlowHelper(Status initialStatus) throws Exception {
submitFlow(this.flow1, this.ref1);
this.flow1.setStatus(initialStatus);
try {
WrappedExecutorApiClient apiClient =
new WrappedExecutorApiClient(createContainerDispatchEnabledProps(this.props));
ContainerizedDispatchManager dispatchManager = createDefaultDispatchWithGateway(apiClient);
apiClient.setNextHttpPostResponse(WrappedExecutorApiClient.STATUS_ERROR_JSON);
dispatchManager.cancelFlow(this.flow1, this.user.getUserId());
} catch (ExecutorManagerException e) {
// Ignore if there is an exception.
}
// Verify that the status of flow1 is finalized.
assertThat(this.flow1.getStatus()).isEqualTo(Status.KILLED);
this.flow1.getExecutableNodes().forEach(node -> {
assertThat(node.getStatus()).isEqualTo(Status.KILLED);
});
}
@Test
public void testCancelFlow() throws Exception {
WrappedExecutorApiClient apiClient =
new WrappedExecutorApiClient(createContainerDispatchEnabledProps(this.props));
ContainerizedDispatchManager dispatchManager = createDefaultDispatchWithGateway(apiClient);
apiClient.setNextHttpPostResponse(WrappedExecutorApiClient.STATUS_SUCCESS_JSON);
dispatchManager.cancelFlow(flow1, this.user.getUserId());
Assert.assertEquals(apiClient.getExpectedReverseProxyContainerizedURI(),
apiClient.getLastBuildExecutorUriRespone());
//Verify that httpPost was requested with the 'cancel' param.
Pair cancelAction = new Pair<String, String> ("action", "cancel");
Assert.assertTrue(apiClient.getLastHttpPostParams().stream().anyMatch(pair -> cancelAction.equals(pair)));
}
@Test
public void testCancelFlowWithMissingExecutor() throws Exception {
// Return a null executor for the unfinished execution
Pair<ExecutionReference, ExecutableFlow> executionReferencePair =
new Pair<ExecutionReference, ExecutableFlow>(new ExecutionReference(flow1.getExecutionId(), DispatchMethod.CONTAINERIZED), flow1);
when(this.loader.fetchUnfinishedFlows()).thenReturn(ImmutableMap.of(flow1.getExecutionId(),
executionReferencePair));
WrappedExecutorApiClient apiClient =
new WrappedExecutorApiClient(createContainerDispatchEnabledProps(this.props));
ContainerizedDispatchManager dispatchManager = createDefaultDispatchWithGateway(apiClient);
apiClient.setNextHttpPostResponse(WrappedExecutorApiClient.STATUS_SUCCESS_JSON);
dispatchManager.cancelFlow(flow1, this.user.getUserId());
Assert.assertEquals(apiClient.getExpectedReverseProxyContainerizedURI(),
apiClient.getLastBuildExecutorUriRespone());
//Verify that httpPost was requested with the 'cancel' param.
Pair cancelAction = new Pair<String, String> ("action", "cancel");
Assert.assertTrue(apiClient.getLastHttpPostParams().stream().anyMatch(pair -> cancelAction.equals(pair)));
}
private Props createContainerDispatchEnabledProps(Props parentProps) {
Props containerProps = new Props(parentProps);
containerProps.put(ConfigurationKeys.AZKABAN_EXECUTOR_REVERSE_PROXY_ENABLED, "true");
containerProps.put(AZKABAN_EXECUTOR_REVERSE_PROXY_HOSTNAME, REVERSE_PROXY_HOST);
containerProps.put(AZKABAN_EXECUTOR_REVERSE_PROXY_PORT, REVERSE_PROXY_PORT);
containerProps.put(ConfigurationKeys.AZKABAN_EXECUTION_DISPATCH_METHOD,
DispatchMethod.CONTAINERIZED.name());
return containerProps;
}
private ContainerizedDispatchManager createDefaultDispatchWithGateway(ExecutorApiClient apiClient) throws Exception {
Props containerEnabledProps = createContainerDispatchEnabledProps(this.props);
ExecutorApiGateway executorApiGateway = new ExecutorApiGateway(apiClient, containerEnabledProps);
return createDispatchWithGateway(executorApiGateway, containerEnabledProps);
}
private ContainerizedDispatchManager createDispatchWithGateway(ExecutorApiGateway apiGateway,
Props containerEnabledProps) throws Exception {
ContainerizedDispatchManager dispatchManager =
new ContainerizedDispatchManager(containerEnabledProps, this.loader,
this.commonMetrics, apiGateway, this.containerizedImpl,null, null, this.eventListener,
this.containerizationMetrics);
dispatchManager.start();
return dispatchManager;
}
/**
* This test tries to verify the the flow is finalized and restarted if the dispatch fails.
* @throws Exception
*/
@Test
public void testRestartFlow() throws Exception {
initializeContainerizedDispatchImpl();
doAnswer(e -> {
throw new ExecutorManagerException("Unable to create container");
}).when(this.containerizedImpl).createContainer(this.flow1.getExecutionId());
when(this.loader.fetchExecutableFlow(this.flow1.getExecutionId())).thenReturn(this.flow1);
OnContainerizedExecutionEventListener onExecutionEventListener = mock(
OnContainerizedExecutionEventListener.class);
ExecutionControllerUtils.onExecutionEventListener = onExecutionEventListener;
Thread thread = new Thread(
this.containerizedDispatchManager.getExecutionDispatcher(this.flow1.getExecutionId()));
thread.start();
synchronized (thread) {
thread.wait();
}
assertThat(flow1.getStatus()).isEqualTo(Status.FAILED);
verify(onExecutionEventListener).onExecutionEvent(this.flow1, Constants.RESTART_FLOW);
}
@NotThreadSafe
private static class WrappedExecutorApiClient extends ExecutorApiClient {
private static String DEFAULT_LOG_TEXT = "line1";
private static String DEFAULT_LOG_JSON =
String.format("{\"length\":%d,\"offset\":0,\"data\":\"%s\"}",
DEFAULT_LOG_TEXT.length(),
DEFAULT_LOG_TEXT);
private static String STATUS_SUCCESS_JSON = "{\"status\":\"success\"}";
private static String STATUS_ERROR_JSON = "{\"error\":\"Unreachable\"}";
private URI lastBuildExecutorUriRespone = null;
private URI lastHttpPostUri = null;
private List<Pair<String, String>> lastHttpPostParams = null;
private String nextHttpPostResponse = DEFAULT_LOG_JSON;
public WrappedExecutorApiClient(Props azkProps) {
super(azkProps);
}
public URI getExpectedReverseProxyContainerizedURI() throws IOException {
return buildExecutorUri(null, 1, "container", false, DispatchMethod.CONTAINERIZED, (Pair<String, String>[]) null);
}
@Override
public URI buildExecutorUri(String host, int port, String path,
boolean isHttp, final DispatchMethod dispatchMethod, Pair<String, String>... params) throws IOException {
this.lastBuildExecutorUriRespone = super.buildExecutorUri(host, port, path, isHttp, dispatchMethod, params);
return lastBuildExecutorUriRespone;
}
@Override
public String httpPost(URI uri, List<Pair<String, String>> params)
throws IOException {
this.lastHttpPostUri = uri;
this.lastHttpPostParams = params;
return nextHttpPostResponse;
}
public void setNextHttpPostResponse(String nextHttpPostResponse) {
this.nextHttpPostResponse = nextHttpPostResponse;
}
public URI getLastBuildExecutorUriRespone() {
return lastBuildExecutorUriRespone;
}
public URI getLastHttpPostUri() {
return lastHttpPostUri;
}
public List<Pair<String, String>> getLastHttpPostParams() {
return lastHttpPostParams;
}
}
@After
public void shutdown() {
if(this.containerizedDispatchManager != null) {
this.containerizedDispatchManager.shutdown();
}
}
}
| 1 | 22,722 | I think we don't need synchronization here. | azkaban-azkaban | java |
@@ -92,7 +92,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
clientRegistrationId.flatMap(id -> Mono.error(new IllegalStateException(
"Unable to resolve the Authorized Client with registration identifier \""
+ id
- + "\". An \"authenticated\" or \"unauthenticated\" session is required. To allow for unauthenticated access, ensure ServerHttpSecurity.anonymous() is configured."))))
+ + "\". An \"authenticated\" or \"anonymous\" request is required. To allow for anonymous access, ensure ServerHttpSecurity.anonymous() is configured."))))
.flatMap(zipped -> {
String registrationId = zipped.getT1();
String username = zipped.getT2(); | 1 | /*
* Copyright 2002-2018 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
*
* 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.springframework.security.oauth2.client.web.reactive.result.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* An implementation of a {@link HandlerMethodArgumentResolver} that is capable
* of resolving a method parameter to an argument value of type {@link OAuth2AuthorizedClient}.
*
* <p>
* For example:
* <pre>
* @Controller
* public class MyController {
* @GetMapping("/authorized-client")
* public Mono<String> authorizedClient(@RegisteredOAuth2AuthorizedClient("login-client") OAuth2AuthorizedClient authorizedClient) {
* // do something with authorizedClient
* }
* }
* </pre>
*
* @author Rob Winch
* @since 5.1
* @see RegisteredOAuth2AuthorizedClient
*/
public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMethodArgumentResolver {
private final ReactiveOAuth2AuthorizedClientService authorizedClientService;
/**
* Constructs an {@code OAuth2AuthorizedClientArgumentResolver} using the provided parameters.
*
* @param authorizedClientService the authorized client service
*/
public OAuth2AuthorizedClientArgumentResolver(ReactiveOAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.authorizedClientService = authorizedClientService;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return AnnotatedElementUtils.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class) != null;
}
@Override
public Mono<Object> resolveArgument(
MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
return Mono.defer(() -> {
RegisteredOAuth2AuthorizedClient authorizedClientAnnotation = AnnotatedElementUtils
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
Mono<String> clientRegistrationId = Mono.justOrEmpty(authorizedClientAnnotation.registrationId())
.filter(id -> !StringUtils.isEmpty(id))
.switchIfEmpty(clientRegistrationId())
.switchIfEmpty(Mono.defer(() -> Mono.error(new IllegalArgumentException(
"Unable to resolve the Client Registration Identifier. It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or @RegisteredOAuth2AuthorizedClient(registrationId = \"client1\")."))));
Mono<String> principalName = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication).map(Authentication::getName);
Mono<OAuth2AuthorizedClient> authorizedClient = Mono
.zip(clientRegistrationId, principalName).switchIfEmpty(
clientRegistrationId.flatMap(id -> Mono.error(new IllegalStateException(
"Unable to resolve the Authorized Client with registration identifier \""
+ id
+ "\". An \"authenticated\" or \"unauthenticated\" session is required. To allow for unauthenticated access, ensure ServerHttpSecurity.anonymous() is configured."))))
.flatMap(zipped -> {
String registrationId = zipped.getT1();
String username = zipped.getT2();
return this.authorizedClientService
.loadAuthorizedClient(registrationId, username).switchIfEmpty(Mono.defer(() -> Mono
.error(new ClientAuthorizationRequiredException(
registrationId))));
}).cast(OAuth2AuthorizedClient.class);
return authorizedClient.cast(Object.class);
});
}
private Mono<String> clientRegistrationId() {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.filter(authentication -> authentication instanceof OAuth2AuthenticationToken)
.cast(OAuth2AuthenticationToken.class)
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
}
}
| 1 | 10,262 | I don't think this should be changed since on the reactive side we don't support anonymous users. | spring-projects-spring-security | java |
@@ -116,7 +116,7 @@ module Mongoid
before_destroy do
if record = __send__(name)
- record[cache_column] = (record[cache_column] || 0) - 1
+ record[cache_column] = (record[cache_column] || 0) - 1 unless record.frozen?
if record.persisted?
record.class.decrement_counter(cache_column, record._id) | 1 | # encoding: utf-8
module Mongoid
module Relations
module CounterCache
extend ActiveSupport::Concern
# Reset the given counter using the .count() query from the
# db. This method is usuful in case that a counter got
# corrupted, or a new counter was added to the collection.
#
# @example Reset the given counter cache
# post.reset_counters(:comments)
#
# @param [ Symbol, Array ] One or more counter caches to reset
#
# @since 4.0.0
def reset_counters(*counters)
self.class.reset_counters(self, *counters)
end
module ClassMethods
# Reset the given counter using the .count() query from the
# db. This method is usuful in case that a counter got
# corrupted, or a new counter was added to the collection.
#
# @example Reset the given counter cache
# Post.reset_counters('50e0edd97c71c17ea9000001', :comments)
#
# @param [ String ] The id of the object that will be reset.
# @param [ Symbol, Array ] One or more counter caches to reset
#
# @since 3.1.0
def reset_counters(id, *counters)
document = id.is_a?(Document) ? id : find(id)
counters.each do |name|
meta = reflect_on_association(name)
inverse = meta.klass.reflect_on_association(meta.inverse)
counter_name = inverse.counter_cache_column_name
document.update_attribute(counter_name, document.send(name).count)
end
end
# Update the given counters by the value factor. It uses the
# atomic $inc command.
#
# @example Add 5 to comments counter and remove 2 from likes
# counter.
# Post.update_counters('50e0edd97c71c17ea9000001',
# :comments_count => 5, :likes_count => -2)
#
# @param [ String ] The id of the object to update.
# @param [ Hash ] Key = counter_cache and Value = factor.
#
# @since 3.1.0
def update_counters(id, counters)
where(:_id => id).inc(counters)
end
# Increment the counter name from the entries that match the
# id by one. This method is used on associations callbacks
# when counter_cache is enabled
#
# @example Increment comments counter
# Post.increment_counter(:comments_count, '50e0edd97c71c17ea9000001')
#
# @param [ Symbol ] Counter cache name
# @param [ String ] The id of the object that will have its counter incremented.
#
# @since 3.1.0
def increment_counter(counter_name, id)
update_counters(id, counter_name.to_sym => 1)
end
# Decrement the counter name from the entries that match the
# id by one. This method is used on associations callbacks
# when counter_cache is enabled
#
# @example Decrement comments counter
# Post.decrement_counter(:comments_count, '50e0edd97c71c17ea9000001')
#
# @param [ Symbol ] Counter cache name
# @param [ String ] The id of the object that will have its counter decremented.
#
# @since 3.1.0
def decrement_counter(counter_name, id)
update_counters(id, counter_name.to_sym => -1)
end
private
# Add the callbacks responsible for update the counter cache field
#
# @api private
#
# @example Add the touchable.
# Person.add_counter_cache_callbacks(meta)
#
# @param [ Metadata ] metadata The metadata for the relation.
#
# @since 3.1.0
def add_counter_cache_callbacks(meta)
name = meta.name
cache_column = meta.counter_cache_column_name.to_sym
after_create do
if record = __send__(name)
record[cache_column] = (record[cache_column] || 0) + 1
if record.persisted?
record.class.increment_counter(cache_column, record._id)
record.remove_change(cache_column)
end
end
end
before_destroy do
if record = __send__(name)
record[cache_column] = (record[cache_column] || 0) - 1
if record.persisted?
record.class.decrement_counter(cache_column, record._id)
record.remove_change(cache_column)
end
end
end
end
end
end
end
end
| 1 | 11,004 | Maybe this `if` should be on line 118? | mongodb-mongoid | rb |
@@ -45,8 +45,8 @@ type (
// the less than equal bucket count for the pre-determined boundaries.
state struct {
bucketCounts []float64
- count metric.Number
sum metric.Number
+ count int64
}
)
| 1 | // 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.
package histogram // import "go.opentelemetry.io/otel/sdk/metric/aggregator/histogram"
import (
"context"
"sort"
"sync"
"go.opentelemetry.io/otel/api/metric"
export "go.opentelemetry.io/otel/sdk/export/metric"
"go.opentelemetry.io/otel/sdk/export/metric/aggregation"
"go.opentelemetry.io/otel/sdk/metric/aggregator"
)
// Note: This code uses a Mutex to govern access to the exclusive
// aggregator state. This is in contrast to a lock-free approach
// (as in the Go prometheus client) that was reverted here:
// https://github.com/open-telemetry/opentelemetry-go/pull/669
type (
// Aggregator observe events and counts them in pre-determined buckets.
// It also calculates the sum and count of all events.
Aggregator struct {
lock sync.Mutex
boundaries []float64
kind metric.NumberKind
state state
}
// state represents the state of a histogram, consisting of
// the sum and counts for all observed values and
// the less than equal bucket count for the pre-determined boundaries.
state struct {
bucketCounts []float64
count metric.Number
sum metric.Number
}
)
var _ export.Aggregator = &Aggregator{}
var _ aggregation.Sum = &Aggregator{}
var _ aggregation.Count = &Aggregator{}
var _ aggregation.Histogram = &Aggregator{}
// New returns a new aggregator for computing Histograms.
//
// A Histogram observe events and counts them in pre-defined buckets.
// And also provides the total sum and count of all observations.
//
// Note that this aggregator maintains each value using independent
// atomic operations, which introduces the possibility that
// checkpoints are inconsistent.
func New(cnt int, desc *metric.Descriptor, boundaries []float64) []Aggregator {
aggs := make([]Aggregator, cnt)
// Boundaries MUST be ordered otherwise the histogram could not
// be properly computed.
sortedBoundaries := make([]float64, len(boundaries))
copy(sortedBoundaries, boundaries)
sort.Float64s(sortedBoundaries)
for i := range aggs {
aggs[i] = Aggregator{
kind: desc.NumberKind(),
boundaries: sortedBoundaries,
state: emptyState(sortedBoundaries),
}
}
return aggs
}
// Aggregation returns an interface for reading the state of this aggregator.
func (c *Aggregator) Aggregation() aggregation.Aggregation {
return c
}
// Kind returns aggregation.HistogramKind.
func (c *Aggregator) Kind() aggregation.Kind {
return aggregation.HistogramKind
}
// Sum returns the sum of all values in the checkpoint.
func (c *Aggregator) Sum() (metric.Number, error) {
return c.state.sum, nil
}
// Count returns the number of values in the checkpoint.
func (c *Aggregator) Count() (int64, error) {
return int64(c.state.count), nil
}
// Histogram returns the count of events in pre-determined buckets.
func (c *Aggregator) Histogram() (aggregation.Buckets, error) {
return aggregation.Buckets{
Boundaries: c.boundaries,
Counts: c.state.bucketCounts,
}, nil
}
// SynchronizedMove saves the current state into oa and resets the current state to
// the empty set. Since no locks are taken, there is a chance that
// the independent Sum, Count and Bucket Count are not consistent with each
// other.
func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *metric.Descriptor) error {
o, _ := oa.(*Aggregator)
if o == nil {
return aggregator.NewInconsistentAggregatorError(c, oa)
}
c.lock.Lock()
o.state, c.state = c.state, emptyState(c.boundaries)
c.lock.Unlock()
return nil
}
func emptyState(boundaries []float64) state {
return state{
bucketCounts: make([]float64, len(boundaries)+1),
}
}
// Update adds the recorded measurement to the current data set.
func (c *Aggregator) Update(_ context.Context, number metric.Number, desc *metric.Descriptor) error {
kind := desc.NumberKind()
asFloat := number.CoerceToFloat64(kind)
bucketID := len(c.boundaries)
for i, boundary := range c.boundaries {
if asFloat < boundary {
bucketID = i
break
}
}
// Note: Binary-search was compared using the benchmarks. The following
// code is equivalent to the linear search above:
//
// bucketID := sort.Search(len(c.boundaries), func(i int) bool {
// return asFloat < c.boundaries[i]
// })
//
// The binary search wins for very large boundary sets, but
// the linear search performs better up through arrays between
// 256 and 512 elements, which is a relatively large histogram, so we
// continue to prefer linear search.
c.lock.Lock()
defer c.lock.Unlock()
c.state.count.AddInt64(1)
c.state.sum.AddNumber(kind, number)
c.state.bucketCounts[bucketID]++
return nil
}
// Merge combines two histograms that have the same buckets into a single one.
func (c *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error {
o, _ := oa.(*Aggregator)
if o == nil {
return aggregator.NewInconsistentAggregatorError(c, oa)
}
c.state.sum.AddNumber(desc.NumberKind(), o.state.sum)
c.state.count.AddNumber(metric.Uint64NumberKind, o.state.count)
for i := 0; i < len(c.state.bucketCounts); i++ {
c.state.bucketCounts[i] += o.state.bucketCounts[i]
}
return nil
}
| 1 | 12,766 | Cool. (I thought I had fixed this already in #812.) | open-telemetry-opentelemetry-go | go |
@@ -36,7 +36,7 @@ module Bolt
TRANSPORT_OPTIONS = %i[password run-as sudo-password extensions
private-key tty tmpdir user connect-timeout
- cacert token-file service-url].freeze
+ cacert token-file service-url interpreters].freeze
# TODO: move these to the transport themselves
TRANSPORT_SPECIFIC_DEFAULTS = { | 1 | # frozen_string_literal: true
require 'yaml'
require 'logging'
require 'concurrent'
require 'pathname'
require 'bolt/boltdir'
require 'bolt/transport/ssh'
require 'bolt/transport/winrm'
require 'bolt/transport/orch'
require 'bolt/transport/local'
require 'bolt/transport/docker'
require 'bolt/transport/remote'
module Bolt
TRANSPORTS = {
ssh: Bolt::Transport::SSH,
winrm: Bolt::Transport::WinRM,
pcp: Bolt::Transport::Orch,
local: Bolt::Transport::Local,
docker: Bolt::Transport::Docker,
remote: Bolt::Transport::Remote
}.freeze
class UnknownTransportError < Bolt::Error
def initialize(transport, uri = nil)
msg = uri.nil? ? "Unknown transport #{transport}" : "Unknown transport #{transport} found for #{uri}"
super(msg, 'bolt/unknown-transport')
end
end
class Config
attr_accessor :concurrency, :format, :trace, :log, :puppetdb, :color,
:transport, :transports, :inventoryfile, :compile_concurrency
attr_writer :modulepath
TRANSPORT_OPTIONS = %i[password run-as sudo-password extensions
private-key tty tmpdir user connect-timeout
cacert token-file service-url].freeze
# TODO: move these to the transport themselves
TRANSPORT_SPECIFIC_DEFAULTS = {
ssh: {
'connect-timeout' => 10,
'host-key-check' => true,
'tty' => false
},
winrm: {
'connect-timeout' => 10,
'ssl' => true,
'ssl-verify' => true
},
pcp: {
'task-environment' => 'production'
},
local: {},
docker: {},
remote: {
'run-on' => 'localhost'
}
}.freeze
def self.default
new(Bolt::Boltdir.new('.'), {})
end
def self.from_boltdir(boltdir, overrides = {})
data = Bolt::Util.read_config_file(nil, [boltdir.config_file], 'config') || {}
new(boltdir, data, overrides)
end
def self.from_file(configfile, overrides = {})
boltdir = Bolt::Boltdir.new(Pathname.new(configfile).expand_path.dirname)
data = Bolt::Util.read_config_file(configfile, [], 'config') || {}
new(boltdir, data, overrides)
end
def initialize(boltdir, config_data, overrides = {})
@logger = Logging.logger[self]
@boltdir = boltdir
@concurrency = 100
@compile_concurrency = Concurrent.processor_count
@transport = 'ssh'
@format = 'human'
@puppetdb = {}
@color = true
# add an entry for the default console logger
@log = { 'console' => {} }
@transports = {}
TRANSPORTS.each_key do |transport|
@transports[transport] = TRANSPORT_SPECIFIC_DEFAULTS[transport].dup
end
update_from_file(config_data)
apply_overrides(overrides)
validate
end
def overwrite_transport_data(transport, transports)
@transport = transport
@transports = transports
end
def transport_data_get
{ transport: @transport, transports: @transports }
end
def deep_clone
Bolt::Util.deep_clone(self)
end
def normalize_log(target)
return target if target == 'console'
target = target[5..-1] if target.start_with?('file:')
'file:' + File.expand_path(target)
end
def update_logs(logs)
logs.each_pair do |k, v|
log_name = normalize_log(k)
@log[log_name] ||= {}
log = @log[log_name]
next unless v.is_a?(Hash)
if v.key?('level')
log[:level] = v['level'].to_s
end
if v.key?('append')
log[:append] = v['append']
end
end
end
def update_from_file(data)
if data['log'].is_a?(Hash)
update_logs(data['log'])
end
# Expand paths relative to the Boltdir. Any settings that came from the
# CLI will already be absolute, so the expand will be skipped.
if data.key?('modulepath')
moduledirs = if data['modulepath'].is_a?(String)
data['modulepath'].split(File::PATH_SEPARATOR)
else
data['modulepath']
end
@modulepath = moduledirs.map do |moduledir|
File.expand_path(moduledir, @boltdir.path)
end
end
@inventoryfile = File.expand_path(data['inventoryfile'], @boltdir.path) if data.key?('inventoryfile')
@hiera_config = File.expand_path(data['hiera-config'], @boltdir.path) if data.key?('hiera-config')
@compile_concurrency = data['compile-concurrency'] if data.key?('compile-concurrency')
%w[concurrency format puppetdb color transport].each do |key|
send("#{key}=", data[key]) if data.key?(key)
end
TRANSPORTS.each do |key, impl|
if data[key.to_s]
selected = impl.filter_options(data[key.to_s])
@transports[key].merge!(selected)
end
end
end
private :update_from_file
def apply_overrides(options)
%i[concurrency transport format trace modulepath inventoryfile color].each do |key|
send("#{key}=", options[key]) if options.key?(key)
end
if options[:debug]
@log['console'][:level] = :debug
elsif options[:verbose]
@log['console'][:level] = :info
end
@compile_concurrency = options[:'compile-concurrency'] if options[:'compile-concurrency']
TRANSPORTS.each_key do |transport|
transport = @transports[transport]
TRANSPORT_OPTIONS.each do |key|
if options[key]
transport[key.to_s] = Bolt::Util.walk_keys(options[key], &:to_s)
end
end
end
if options.key?(:ssl) # this defaults to true so we need to check the presence of the key
@transports[:winrm]['ssl'] = options[:ssl]
end
if options.key?(:'ssl-verify') # this defaults to true so we need to check the presence of the key
@transports[:winrm]['ssl-verify'] = options[:'ssl-verify']
end
if options.key?(:'host-key-check') # this defaults to true so we need to check the presence of the key
@transports[:ssh]['host-key-check'] = options[:'host-key-check']
end
end
def update_from_inventory(data)
update_from_file(data)
if data['transport']
@transport = data['transport']
end
end
def transport_conf
{ transport: @transport,
transports: @transports }
end
def default_inventoryfile
[@boltdir.inventory_file]
end
def hiera_config
@hiera_config || @boltdir.hiera_config
end
def puppetfile
@boltdir.puppetfile
end
def modulepath
@modulepath || @boltdir.modulepath
end
def validate
@log.each_pair do |name, params|
if params.key?(:level) && !Bolt::Logger.valid_level?(params[:level])
raise Bolt::ValidationError,
"level of log #{name} must be one of: #{Bolt::Logger.levels.join(', ')}; received #{params[:level]}"
end
if params.key?(:append) && params[:append] != true && params[:append] != false
raise Bolt::ValidationError, "append flag of log #{name} must be a Boolean, received #{params[:append]}"
end
end
unless @concurrency.is_a?(Integer) && @concurrency > 0
raise Bolt::ValidationError, 'Concurrency must be a positive integer'
end
unless @compile_concurrency.is_a?(Integer) && @compile_concurrency > 0
raise Bolt::ValidationError, 'Compile concurrency must be a positive integer'
end
compile_limit = 2 * Concurrent.processor_count
unless @compile_concurrency < compile_limit
raise Bolt::ValidationError, "Compilation is CPU-intensive, set concurrency less than #{compile_limit}"
end
unless %w[human json].include? @format
raise Bolt::ValidationError, "Unsupported format: '#{@format}'"
end
if @hiera_config && !(File.file?(@hiera_config) && File.readable?(@hiera_config))
raise Bolt::FileError, "Could not read hiera-config file #{@hiera_config}", @hiera_config
end
unless @transport.nil? || Bolt::TRANSPORTS.include?(@transport.to_sym)
raise UnknownTransportError, @transport
end
TRANSPORTS.each do |transport, impl|
impl.validate(@transports[transport])
end
end
end
end
| 1 | 10,649 | I intend to do this as soon as I have tests passing. | puppetlabs-bolt | rb |
@@ -0,0 +1,7 @@
+#!/usr/bin/python3
+
+import sys
+import os
+sys.stdin.read()
+with open(os.environ['QUTE_FIFO'], 'wb') as fifo:
+ fifo.write(b':message-info "stdin closed"\n') | 1 | 1 | 18,000 | Please remove the `test_*` from the filename - otherwise pytest will try to collect tests from it. | qutebrowser-qutebrowser | py |
|
@@ -263,6 +263,11 @@ size_t wlr_session_find_gpus(struct wlr_session *session,
return explicit_find_gpus(session, ret_len, ret, explicit);
}
+#ifdef __FreeBSD__
+ // XXX: libudev-devd does not return any GPUs (yet?)
+ return explicit_find_gpus(session, ret_len, ret, "/dev/drm/0");
+#else
+
struct udev_enumerate *en = udev_enumerate_new(session->udev);
if (!en) {
wlr_log(L_ERROR, "Failed to create udev enumeration"); | 1 | #define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <libudev.h>
#include <wayland-server.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <wlr/backend/session.h>
#include <wlr/backend/session/interface.h>
#include <wlr/util/log.h>
extern const struct session_impl session_logind;
extern const struct session_impl session_direct;
static const struct session_impl *impls[] = {
#ifdef HAS_SYSTEMD
&session_logind,
#elif HAS_ELOGIND
&session_logind,
#endif
&session_direct,
NULL,
};
static int udev_event(int fd, uint32_t mask, void *data) {
struct wlr_session *session = data;
struct udev_device *udev_dev = udev_monitor_receive_device(session->mon);
if (!udev_dev) {
return 1;
}
const char *action = udev_device_get_action(udev_dev);
wlr_log(L_DEBUG, "udev event for %s (%s)",
udev_device_get_sysname(udev_dev), action);
if (!action || strcmp(action, "change") != 0) {
goto out;
}
dev_t devnum = udev_device_get_devnum(udev_dev);
struct wlr_device *dev;
wl_list_for_each(dev, &session->devices, link) {
if (dev->dev == devnum) {
wl_signal_emit(&dev->signal, session);
break;
}
}
out:
udev_device_unref(udev_dev);
return 1;
}
struct wlr_session *wlr_session_create(struct wl_display *disp) {
struct wlr_session *session = NULL;
const struct session_impl **iter;
for (iter = impls; !session && *iter; ++iter) {
session = (*iter)->create(disp);
}
if (!session) {
wlr_log(L_ERROR, "Failed to load session backend");
return NULL;
}
session->active = true;
wl_signal_init(&session->session_signal);
wl_list_init(&session->devices);
session->udev = udev_new();
if (!session->udev) {
wlr_log_errno(L_ERROR, "Failed to create udev context");
goto error_session;
}
session->mon = udev_monitor_new_from_netlink(session->udev, "udev");
if (!session->mon) {
wlr_log_errno(L_ERROR, "Failed to create udev monitor");
goto error_udev;
}
udev_monitor_filter_add_match_subsystem_devtype(session->mon, "drm", NULL);
udev_monitor_enable_receiving(session->mon);
struct wl_event_loop *event_loop = wl_display_get_event_loop(disp);
int fd = udev_monitor_get_fd(session->mon);
session->udev_event = wl_event_loop_add_fd(event_loop, fd,
WL_EVENT_READABLE, udev_event, session);
if (!session->udev_event) {
wlr_log_errno(L_ERROR, "Failed to create udev event source");
goto error_mon;
}
return session;
error_mon:
udev_monitor_unref(session->mon);
error_udev:
udev_unref(session->udev);
error_session:
wlr_session_destroy(session);
return NULL;
}
void wlr_session_destroy(struct wlr_session *session) {
if (!session) {
return;
}
wl_event_source_remove(session->udev_event);
udev_monitor_unref(session->mon);
udev_unref(session->udev);
session->impl->destroy(session);
}
int wlr_session_open_file(struct wlr_session *session, const char *path) {
int fd = session->impl->open(session, path);
if (fd < 0) {
return fd;
}
struct wlr_device *dev = malloc(sizeof(*dev));
if (!dev) {
wlr_log_errno(L_ERROR, "Allocation failed");
goto error;
}
struct stat st;
if (fstat(fd, &st) < 0) {
wlr_log_errno(L_ERROR, "Stat failed");
goto error;
}
dev->fd = fd;
dev->dev = st.st_rdev;
wl_signal_init(&dev->signal);
wl_list_insert(&session->devices, &dev->link);
return fd;
error:
free(dev);
return fd;
}
static struct wlr_device *find_device(struct wlr_session *session, int fd) {
struct wlr_device *dev;
wl_list_for_each(dev, &session->devices, link) {
if (dev->fd == fd) {
return dev;
}
}
wlr_log(L_ERROR, "Tried to use fd %d not opened by session", fd);
assert(0);
}
void wlr_session_close_file(struct wlr_session *session, int fd) {
struct wlr_device *dev = find_device(session, fd);
session->impl->close(session, fd);
wl_list_remove(&dev->link);
free(dev);
}
void wlr_session_signal_add(struct wlr_session *session, int fd,
struct wl_listener *listener) {
struct wlr_device *dev = find_device(session, fd);
wl_signal_add(&dev->signal, listener);
}
bool wlr_session_change_vt(struct wlr_session *session, unsigned vt) {
if (!session) {
return false;
}
return session->impl->change_vt(session, vt);
}
/* Tests if 'path' is KMS compatible by trying to open it.
* It leaves the open device in *fd_out it it succeeds.
*/
static int open_if_kms(struct wlr_session *restrict session, const char *restrict path) {
int fd;
if (!path) {
return -1;
}
fd = wlr_session_open_file(session, path);
if (fd < 0) {
return -1;
}
drmModeRes *res = drmModeGetResources(fd);
if (!res) {
goto out_fd;
}
if (res->count_crtcs <= 0 || res->count_connectors <= 0 ||
res->count_encoders <= 0) {
goto out_res;
}
drmModeFreeResources(res);
return fd;
out_res:
drmModeFreeResources(res);
out_fd:
wlr_session_close_file(session, fd);
return -1;
}
static size_t explicit_find_gpus(struct wlr_session *session,
size_t ret_len, int ret[static ret_len], const char *str) {
char *gpus = strdup(str);
if (!gpus) {
wlr_log_errno(L_ERROR, "Allocation failed");
return 0;
}
size_t i = 0;
char *save;
char *ptr = strtok_r(gpus, ":", &save);
do {
if (i >= ret_len) {
break;
}
ret[i] = open_if_kms(session, ptr);
if (ret[i] < 0) {
wlr_log(L_ERROR, "Unable to open %s as DRM device", ptr);
} else {
++i;
}
} while ((ptr = strtok_r(NULL, ":", &save)));
free(ptr);
return i;
}
/* Tries to find the primary GPU by checking for the "boot_vga" attribute.
* If it's not found, it returns the first valid GPU it finds.
*/
size_t wlr_session_find_gpus(struct wlr_session *session,
size_t ret_len, int ret[static ret_len]) {
const char *explicit = getenv("WLR_DRM_DEVICES");
if (explicit) {
return explicit_find_gpus(session, ret_len, ret, explicit);
}
struct udev_enumerate *en = udev_enumerate_new(session->udev);
if (!en) {
wlr_log(L_ERROR, "Failed to create udev enumeration");
return -1;
}
udev_enumerate_add_match_subsystem(en, "drm");
udev_enumerate_add_match_sysname(en, "card[0-9]*");
udev_enumerate_scan_devices(en);
struct udev_list_entry *entry;
size_t i = 0;
udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(en)) {
if (i == ret_len) {
break;
}
bool is_boot_vga = false;
const char *path = udev_list_entry_get_name(entry);
struct udev_device *dev = udev_device_new_from_syspath(session->udev, path);
if (!dev) {
continue;
}
const char *seat = udev_device_get_property_value(dev, "ID_SEAT");
if (!seat)
seat = "seat0";
if (session->seat[0] && strcmp(session->seat, seat) != 0) {
udev_device_unref(dev);
continue;
}
// This is owned by 'dev', so we don't need to free it
struct udev_device *pci =
udev_device_get_parent_with_subsystem_devtype(dev, "pci", NULL);
if (pci) {
const char *id = udev_device_get_sysattr_value(pci, "boot_vga");
if (id && strcmp(id, "1") == 0) {
is_boot_vga = true;
}
}
int fd = open_if_kms(session, udev_device_get_devnode(dev));
if (fd < 0) {
udev_device_unref(dev);
continue;
}
udev_device_unref(dev);
ret[i] = fd;
if (is_boot_vga) {
int tmp = ret[0];
ret[0] = ret[i];
ret[i] = tmp;
}
++i;
}
udev_enumerate_unref(en);
return i;
}
| 1 | 8,356 | Did you file a bug to follow up on this? | swaywm-wlroots | c |
@@ -156,10 +156,13 @@ class Reader implements DataSourceReader, SupportsScanColumnarBatch, SupportsPus
this.io = io;
this.encryptionManager = encryptionManager;
this.caseSensitive = caseSensitive;
-
- this.batchReadsEnabled = options.get("vectorization-enabled").map(Boolean::parseBoolean).orElseGet(() ->
- PropertyUtil.propertyAsBoolean(table.properties(),
- TableProperties.PARQUET_VECTORIZATION_ENABLED, TableProperties.PARQUET_VECTORIZATION_ENABLED_DEFAULT));
+ boolean batchReadsSparkSessionConf = SparkSession.active().sparkContext().getConf()
+ .getBoolean("read.parquet.vectorization.enabled", true);
+ boolean batchReadsEnabledTableProp = options.get("vectorization-enabled").map(Boolean::parseBoolean).orElseGet(() ->
+ PropertyUtil.propertyAsBoolean(table.properties(),
+ TableProperties.PARQUET_VECTORIZATION_ENABLED,
+ TableProperties.PARQUET_VECTORIZATION_ENABLED_DEFAULT));
+ this.batchReadsEnabled = !batchReadsSparkSessionConf ? false : batchReadsEnabledTableProp;
this.batchSize = options.get("batch-size").map(Integer::parseInt).orElseGet(() ->
PropertyUtil.propertyAsInt(table.properties(),
TableProperties.PARQUET_BATCH_SIZE, TableProperties.PARQUET_BATCH_SIZE_DEFAULT)); | 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.spark.source;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.iceberg.CombinedScanTask;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.FileScanTask;
import org.apache.iceberg.Schema;
import org.apache.iceberg.SchemaParser;
import org.apache.iceberg.SnapshotSummary;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableProperties;
import org.apache.iceberg.TableScan;
import org.apache.iceberg.encryption.EncryptionManager;
import org.apache.iceberg.exceptions.RuntimeIOException;
import org.apache.iceberg.exceptions.ValidationException;
import org.apache.iceberg.expressions.Expression;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.hadoop.HadoopFileIO;
import org.apache.iceberg.hadoop.Util;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.spark.SparkFilters;
import org.apache.iceberg.spark.SparkSchemaUtil;
import org.apache.iceberg.util.PropertyUtil;
import org.apache.iceberg.util.TableScanUtil;
import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.Filter;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.reader.DataSourceReader;
import org.apache.spark.sql.sources.v2.reader.InputPartition;
import org.apache.spark.sql.sources.v2.reader.InputPartitionReader;
import org.apache.spark.sql.sources.v2.reader.Statistics;
import org.apache.spark.sql.sources.v2.reader.SupportsPushDownFilters;
import org.apache.spark.sql.sources.v2.reader.SupportsPushDownRequiredColumns;
import org.apache.spark.sql.sources.v2.reader.SupportsReportStatistics;
import org.apache.spark.sql.sources.v2.reader.SupportsScanColumnarBatch;
import org.apache.spark.sql.types.StructType;
import org.apache.spark.sql.vectorized.ColumnarBatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.iceberg.TableProperties.DEFAULT_NAME_MAPPING;
class Reader implements DataSourceReader, SupportsScanColumnarBatch, SupportsPushDownFilters,
SupportsPushDownRequiredColumns, SupportsReportStatistics {
private static final Logger LOG = LoggerFactory.getLogger(Reader.class);
private static final Filter[] NO_FILTERS = new Filter[0];
private static final ImmutableSet<String> LOCALITY_WHITELIST_FS = ImmutableSet.of("hdfs");
private final Table table;
private final Long snapshotId;
private final Long startSnapshotId;
private final Long endSnapshotId;
private final Long asOfTimestamp;
private final Long splitSize;
private final Integer splitLookback;
private final Long splitOpenFileCost;
private final Broadcast<FileIO> io;
private final Broadcast<EncryptionManager> encryptionManager;
private final boolean caseSensitive;
private StructType requestedSchema = null;
private List<Expression> filterExpressions = null;
private Filter[] pushedFilters = NO_FILTERS;
private final boolean localityPreferred;
private final boolean batchReadsEnabled;
private final int batchSize;
// lazy variables
private Schema schema = null;
private StructType type = null; // cached because Spark accesses it multiple times
private List<CombinedScanTask> tasks = null; // lazy cache of tasks
private Boolean readUsingBatch = null;
Reader(Table table, Broadcast<FileIO> io, Broadcast<EncryptionManager> encryptionManager,
boolean caseSensitive, DataSourceOptions options) {
this.table = table;
this.snapshotId = options.get("snapshot-id").map(Long::parseLong).orElse(null);
this.asOfTimestamp = options.get("as-of-timestamp").map(Long::parseLong).orElse(null);
if (snapshotId != null && asOfTimestamp != null) {
throw new IllegalArgumentException(
"Cannot scan using both snapshot-id and as-of-timestamp to select the table snapshot");
}
this.startSnapshotId = options.get("start-snapshot-id").map(Long::parseLong).orElse(null);
this.endSnapshotId = options.get("end-snapshot-id").map(Long::parseLong).orElse(null);
if (snapshotId != null || asOfTimestamp != null) {
if (startSnapshotId != null || endSnapshotId != null) {
throw new IllegalArgumentException(
"Cannot specify start-snapshot-id and end-snapshot-id to do incremental scan when either snapshot-id or " +
"as-of-timestamp is specified");
}
} else {
if (startSnapshotId == null && endSnapshotId != null) {
throw new IllegalArgumentException("Cannot only specify option end-snapshot-id to do incremental scan");
}
}
// look for split behavior overrides in options
this.splitSize = options.get("split-size").map(Long::parseLong).orElse(null);
this.splitLookback = options.get("lookback").map(Integer::parseInt).orElse(null);
this.splitOpenFileCost = options.get("file-open-cost").map(Long::parseLong).orElse(null);
if (io.getValue() instanceof HadoopFileIO) {
String fsscheme = "no_exist";
try {
Configuration conf = SparkSession.active().sessionState().newHadoopConf();
// merge hadoop config set on table
mergeIcebergHadoopConfs(conf, table.properties());
// merge hadoop config passed as options and overwrite the one on table
mergeIcebergHadoopConfs(conf, options.asMap());
FileSystem fs = new Path(table.location()).getFileSystem(conf);
fsscheme = fs.getScheme().toLowerCase(Locale.ENGLISH);
} catch (IOException ioe) {
LOG.warn("Failed to get Hadoop Filesystem", ioe);
}
String scheme = fsscheme; // Makes an effectively final version of scheme
this.localityPreferred = options.get("locality").map(Boolean::parseBoolean)
.orElseGet(() -> LOCALITY_WHITELIST_FS.contains(scheme));
} else {
this.localityPreferred = false;
}
this.schema = table.schema();
this.io = io;
this.encryptionManager = encryptionManager;
this.caseSensitive = caseSensitive;
this.batchReadsEnabled = options.get("vectorization-enabled").map(Boolean::parseBoolean).orElseGet(() ->
PropertyUtil.propertyAsBoolean(table.properties(),
TableProperties.PARQUET_VECTORIZATION_ENABLED, TableProperties.PARQUET_VECTORIZATION_ENABLED_DEFAULT));
this.batchSize = options.get("batch-size").map(Integer::parseInt).orElseGet(() ->
PropertyUtil.propertyAsInt(table.properties(),
TableProperties.PARQUET_BATCH_SIZE, TableProperties.PARQUET_BATCH_SIZE_DEFAULT));
}
private Schema lazySchema() {
if (schema == null) {
if (requestedSchema != null) {
// the projection should include all columns that will be returned, including those only used in filters
this.schema = SparkSchemaUtil.prune(table.schema(), requestedSchema, filterExpression(), caseSensitive);
} else {
this.schema = table.schema();
}
}
return schema;
}
private Expression filterExpression() {
if (filterExpressions != null) {
return filterExpressions.stream().reduce(Expressions.alwaysTrue(), Expressions::and);
}
return Expressions.alwaysTrue();
}
private StructType lazyType() {
if (type == null) {
this.type = SparkSchemaUtil.convert(lazySchema());
}
return type;
}
@Override
public StructType readSchema() {
return lazyType();
}
/**
* This is called in the Spark Driver when data is to be materialized into {@link ColumnarBatch}
*/
@Override
public List<InputPartition<ColumnarBatch>> planBatchInputPartitions() {
Preconditions.checkState(enableBatchRead(), "Batched reads not enabled");
Preconditions.checkState(batchSize > 0, "Invalid batch size");
String tableSchemaString = SchemaParser.toJson(table.schema());
String expectedSchemaString = SchemaParser.toJson(lazySchema());
String nameMappingString = table.properties().get(DEFAULT_NAME_MAPPING);
ValidationException.check(tasks().stream().noneMatch(TableScanUtil::hasDeletes),
"Cannot scan table %s: cannot apply required delete files", table);
List<InputPartition<ColumnarBatch>> readTasks = Lists.newArrayList();
for (CombinedScanTask task : tasks()) {
readTasks.add(new ReadTask<>(
task, tableSchemaString, expectedSchemaString, nameMappingString, io, encryptionManager, caseSensitive,
localityPreferred, new BatchReaderFactory(batchSize)));
}
LOG.info("Batching input partitions with {} tasks.", readTasks.size());
return readTasks;
}
/**
* This is called in the Spark Driver when data is to be materialized into {@link InternalRow}
*/
@Override
public List<InputPartition<InternalRow>> planInputPartitions() {
String tableSchemaString = SchemaParser.toJson(table.schema());
String expectedSchemaString = SchemaParser.toJson(lazySchema());
String nameMappingString = table.properties().get(DEFAULT_NAME_MAPPING);
List<InputPartition<InternalRow>> readTasks = Lists.newArrayList();
for (CombinedScanTask task : tasks()) {
readTasks.add(new ReadTask<>(
task, tableSchemaString, expectedSchemaString, nameMappingString, io, encryptionManager, caseSensitive,
localityPreferred, InternalRowReaderFactory.INSTANCE));
}
return readTasks;
}
@Override
public Filter[] pushFilters(Filter[] filters) {
this.tasks = null; // invalidate cached tasks, if present
List<Expression> expressions = Lists.newArrayListWithExpectedSize(filters.length);
List<Filter> pushed = Lists.newArrayListWithExpectedSize(filters.length);
for (Filter filter : filters) {
Expression expr = SparkFilters.convert(filter);
if (expr != null) {
expressions.add(expr);
pushed.add(filter);
}
}
this.filterExpressions = expressions;
this.pushedFilters = pushed.toArray(new Filter[0]);
// invalidate the schema that will be projected
this.schema = null;
this.type = null;
// Spark doesn't support residuals per task, so return all filters
// to get Spark to handle record-level filtering
return filters;
}
@Override
public Filter[] pushedFilters() {
return pushedFilters;
}
@Override
public void pruneColumns(StructType newRequestedSchema) {
this.requestedSchema = newRequestedSchema;
// invalidate the schema that will be projected
this.schema = null;
this.type = null;
}
@Override
public Statistics estimateStatistics() {
// its a fresh table, no data
if (table.currentSnapshot() == null) {
return new Stats(0L, 0L);
}
// estimate stats using snapshot summary only for partitioned tables (metadata tables are unpartitioned)
if (!table.spec().isUnpartitioned() && filterExpression() == Expressions.alwaysTrue()) {
long totalRecords = PropertyUtil.propertyAsLong(table.currentSnapshot().summary(),
SnapshotSummary.TOTAL_RECORDS_PROP, Long.MAX_VALUE);
return new Stats(SparkSchemaUtil.estimateSize(lazyType(), totalRecords), totalRecords);
}
long sizeInBytes = 0L;
long numRows = 0L;
for (CombinedScanTask task : tasks()) {
for (FileScanTask file : task.files()) {
sizeInBytes += file.length();
numRows += file.file().recordCount();
}
}
return new Stats(sizeInBytes, numRows);
}
@Override
public boolean enableBatchRead() {
if (readUsingBatch == null) {
boolean allParquetFileScanTasks =
tasks().stream()
.allMatch(combinedScanTask -> !combinedScanTask.isDataTask() && combinedScanTask.files()
.stream()
.allMatch(fileScanTask -> fileScanTask.file().format().equals(
FileFormat.PARQUET)));
boolean allOrcFileScanTasks =
tasks().stream()
.allMatch(combinedScanTask -> !combinedScanTask.isDataTask() && combinedScanTask.files()
.stream()
.allMatch(fileScanTask -> fileScanTask.file().format().equals(
FileFormat.ORC)));
boolean atLeastOneColumn = lazySchema().columns().size() > 0;
boolean onlyPrimitives = lazySchema().columns().stream().allMatch(c -> c.type().isPrimitiveType());
boolean hasNoDeleteFiles = tasks().stream().noneMatch(TableScanUtil::hasDeletes);
this.readUsingBatch = batchReadsEnabled && hasNoDeleteFiles && (allOrcFileScanTasks ||
(allParquetFileScanTasks && atLeastOneColumn && onlyPrimitives));
}
return readUsingBatch;
}
private static void mergeIcebergHadoopConfs(
Configuration baseConf, Map<String, String> options) {
options.keySet().stream()
.filter(key -> key.startsWith("hadoop."))
.forEach(key -> baseConf.set(key.replaceFirst("hadoop.", ""), options.get(key)));
}
private List<CombinedScanTask> tasks() {
if (tasks == null) {
TableScan scan = table
.newScan()
.caseSensitive(caseSensitive)
.project(lazySchema());
if (snapshotId != null) {
scan = scan.useSnapshot(snapshotId);
}
if (asOfTimestamp != null) {
scan = scan.asOfTime(asOfTimestamp);
}
if (startSnapshotId != null) {
if (endSnapshotId != null) {
scan = scan.appendsBetween(startSnapshotId, endSnapshotId);
} else {
scan = scan.appendsAfter(startSnapshotId);
}
}
if (splitSize != null) {
scan = scan.option(TableProperties.SPLIT_SIZE, splitSize.toString());
}
if (splitLookback != null) {
scan = scan.option(TableProperties.SPLIT_LOOKBACK, splitLookback.toString());
}
if (splitOpenFileCost != null) {
scan = scan.option(TableProperties.SPLIT_OPEN_FILE_COST, splitOpenFileCost.toString());
}
if (filterExpressions != null) {
for (Expression filter : filterExpressions) {
scan = scan.filter(filter);
}
}
try (CloseableIterable<CombinedScanTask> tasksIterable = scan.planTasks()) {
this.tasks = Lists.newArrayList(tasksIterable);
} catch (IOException e) {
throw new RuntimeIOException(e, "Failed to close table scan: %s", scan);
}
}
return tasks;
}
@Override
public String toString() {
return String.format(
"IcebergScan(table=%s, type=%s, filters=%s, caseSensitive=%s, batchedReads=%s)",
table, lazySchema().asStruct(), filterExpressions, caseSensitive, enableBatchRead());
}
private static class ReadTask<T> implements Serializable, InputPartition<T> {
private final CombinedScanTask task;
private final String tableSchemaString;
private final String expectedSchemaString;
private final String nameMappingString;
private final Broadcast<FileIO> io;
private final Broadcast<EncryptionManager> encryptionManager;
private final boolean caseSensitive;
private final boolean localityPreferred;
private final ReaderFactory<T> readerFactory;
private transient Schema tableSchema = null;
private transient Schema expectedSchema = null;
private transient String[] preferredLocations = null;
private ReadTask(CombinedScanTask task, String tableSchemaString, String expectedSchemaString,
String nameMappingString, Broadcast<FileIO> io, Broadcast<EncryptionManager> encryptionManager,
boolean caseSensitive, boolean localityPreferred, ReaderFactory<T> readerFactory) {
this.task = task;
this.tableSchemaString = tableSchemaString;
this.expectedSchemaString = expectedSchemaString;
this.io = io;
this.encryptionManager = encryptionManager;
this.caseSensitive = caseSensitive;
this.localityPreferred = localityPreferred;
this.preferredLocations = getPreferredLocations();
this.readerFactory = readerFactory;
this.nameMappingString = nameMappingString;
}
@Override
public InputPartitionReader<T> createPartitionReader() {
return readerFactory.create(task, lazyTableSchema(), lazyExpectedSchema(), nameMappingString, io.value(),
encryptionManager.value(), caseSensitive);
}
@Override
public String[] preferredLocations() {
return preferredLocations;
}
private Schema lazyTableSchema() {
if (tableSchema == null) {
this.tableSchema = SchemaParser.fromJson(tableSchemaString);
}
return tableSchema;
}
private Schema lazyExpectedSchema() {
if (expectedSchema == null) {
this.expectedSchema = SchemaParser.fromJson(expectedSchemaString);
}
return expectedSchema;
}
@SuppressWarnings("checkstyle:RegexpSingleline")
private String[] getPreferredLocations() {
if (!localityPreferred) {
return new String[0];
}
Configuration conf = SparkSession.active().sparkContext().hadoopConfiguration();
return Util.blockLocations(task, conf);
}
}
private interface ReaderFactory<T> extends Serializable {
InputPartitionReader<T> create(CombinedScanTask task, Schema tableSchema, Schema expectedSchema,
String nameMapping, FileIO io,
EncryptionManager encryptionManager, boolean caseSensitive);
}
private static class InternalRowReaderFactory implements ReaderFactory<InternalRow> {
private static final InternalRowReaderFactory INSTANCE = new InternalRowReaderFactory();
private InternalRowReaderFactory() {
}
@Override
public InputPartitionReader<InternalRow> create(CombinedScanTask task, Schema tableSchema, Schema expectedSchema,
String nameMapping, FileIO io,
EncryptionManager encryptionManager, boolean caseSensitive) {
return new RowReader(task, tableSchema, expectedSchema, nameMapping, io, encryptionManager, caseSensitive);
}
}
private static class BatchReaderFactory implements ReaderFactory<ColumnarBatch> {
private final int batchSize;
BatchReaderFactory(int batchSize) {
this.batchSize = batchSize;
}
@Override
public InputPartitionReader<ColumnarBatch> create(CombinedScanTask task, Schema tableSchema, Schema expectedSchema,
String nameMapping, FileIO io,
EncryptionManager encryptionManager, boolean caseSensitive) {
return new BatchReader(task, expectedSchema, nameMapping, io, encryptionManager, caseSensitive, batchSize);
}
}
private static class RowReader extends RowDataReader implements InputPartitionReader<InternalRow> {
RowReader(CombinedScanTask task, Schema tableSchema, Schema expectedSchema, String nameMapping, FileIO io,
EncryptionManager encryptionManager, boolean caseSensitive) {
super(task, tableSchema, expectedSchema, nameMapping, io, encryptionManager, caseSensitive);
}
}
private static class BatchReader extends BatchDataReader implements InputPartitionReader<ColumnarBatch> {
BatchReader(CombinedScanTask task, Schema expectedSchema, String nameMapping, FileIO io,
EncryptionManager encryptionManager, boolean caseSensitive, int size) {
super(task, expectedSchema, nameMapping, io, encryptionManager, caseSensitive, size);
}
}
}
| 1 | 27,945 | Looks like these 4 lines didn't actually change. Can you revert the whitespace changes here? | apache-iceberg | java |
@@ -1,4 +1,6 @@
RSpec::Support.require_rspec_core "formatters/base_formatter"
+require 'pathname'
+
module RSpec
module Core | 1 | RSpec::Support.require_rspec_core "formatters/base_formatter"
module RSpec
module Core
module Formatters
# @private
class FailureListFormatter < BaseFormatter
Formatters.register self, :example_failed, :dump_profile, :message
def example_failed(failure)
output.puts "#{failure.example.location}:#{failure.example.description}"
end
# Discard profile and messages
#
# These outputs are not really relevant in the context of this failure
# list formatter.
def dump_profile(_profile); end
def message(_message); end
end
end
end
end
| 1 | 18,069 | This can't be merged with any usage of `require 'pathname'` in lib, it's not always available and we don't want false positives for people (where they don't realise they needed to requite it). Its also unnecessary, no other formatter uses it to look up failure locations. See the exception presenter etc for how we format lines. | rspec-rspec-core | rb |
@@ -1426,6 +1426,13 @@ public class DatasetsIT {
// This should fail, because we are attempting to link the dataset
// to its own dataverse:
+ Response publishTargetDataverse = UtilIT.publishDataverseViaNativeApi(dataverseAlias, apiToken);
+ publishTargetDataverse.prettyPrint();
+ publishTargetDataverse.then().assertThat()
+ .statusCode(OK.getStatusCode());
+
+ Response publishDatasetForLinking = UtilIT.publishDatasetViaNativeApi(datasetId, "major", apiToken);
+
Response createLinkingDatasetResponse = UtilIT.createDatasetLink(datasetId.longValue(), dataverseAlias, apiToken);
createLinkingDatasetResponse.prettyPrint();
createLinkingDatasetResponse.then().assertThat() | 1 | package edu.harvard.iq.dataverse.api;
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.given;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import java.util.logging.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
import com.jayway.restassured.path.json.JsonPath;
import java.util.List;
import java.util.Map;
import javax.json.JsonObject;
import static javax.ws.rs.core.Response.Status.CREATED;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.OK;
import static javax.ws.rs.core.Response.Status.UNAUTHORIZED;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.METHOD_NOT_ALLOWED;
import edu.harvard.iq.dataverse.DataFile;
import static edu.harvard.iq.dataverse.api.UtilIT.API_TOKEN_HTTP_HEADER;
import edu.harvard.iq.dataverse.authorization.DataverseRole;
import edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import java.util.UUID;
import static javax.ws.rs.core.Response.Status.NO_CONTENT;
import org.apache.commons.lang.StringUtils;
import com.jayway.restassured.parsing.Parser;
import static com.jayway.restassured.path.json.JsonPath.with;
import com.jayway.restassured.path.xml.XmlPath;
import static edu.harvard.iq.dataverse.api.UtilIT.equalToCI;
import edu.harvard.iq.dataverse.util.SystemConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObjectBuilder;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import org.junit.AfterClass;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DatasetsIT {
private static final Logger logger = Logger.getLogger(DatasetsIT.class.getCanonicalName());
@BeforeClass
public static void setUpClass() {
RestAssured.baseURI = UtilIT.getRestAssuredBaseUri();
Response removeIdentifierGenerationStyle = UtilIT.deleteSetting(SettingsServiceBean.Key.IdentifierGenerationStyle);
removeIdentifierGenerationStyle.then().assertThat()
.statusCode(200);
Response removeExcludeEmail = UtilIT.deleteSetting(SettingsServiceBean.Key.ExcludeEmailFromExport);
removeExcludeEmail.then().assertThat()
.statusCode(200);
Response removeDcmUrl = UtilIT.deleteSetting(SettingsServiceBean.Key.DataCaptureModuleUrl);
removeDcmUrl.then().assertThat()
.statusCode(200);
Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods);
removeUploadMethods.then().assertThat()
.statusCode(200);
}
@AfterClass
public static void afterClass() {
Response removeIdentifierGenerationStyle = UtilIT.deleteSetting(SettingsServiceBean.Key.IdentifierGenerationStyle);
removeIdentifierGenerationStyle.then().assertThat()
.statusCode(200);
Response removeExcludeEmail = UtilIT.deleteSetting(SettingsServiceBean.Key.ExcludeEmailFromExport);
removeExcludeEmail.then().assertThat()
.statusCode(200);
Response removeDcmUrl = UtilIT.deleteSetting(SettingsServiceBean.Key.DataCaptureModuleUrl);
removeDcmUrl.then().assertThat()
.statusCode(200);
Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods);
removeUploadMethods.then().assertThat()
.statusCode(200);
}
@Test
public void testCreateDataset() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
Response datasetAsJson = UtilIT.nativeGet(datasetId, apiToken);
datasetAsJson.then().assertThat()
.statusCode(OK.getStatusCode());
String identifier = JsonPath.from(datasetAsJson.getBody().asString()).getString("data.identifier");
assertEquals(10, identifier.length());
Response deleteDatasetResponse = UtilIT.deleteDatasetViaNativeApi(datasetId, apiToken);
deleteDatasetResponse.prettyPrint();
assertEquals(200, deleteDatasetResponse.getStatusCode());
Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken);
deleteDataverseResponse.prettyPrint();
assertEquals(200, deleteDataverseResponse.getStatusCode());
Response deleteUserResponse = UtilIT.deleteUser(username);
deleteUserResponse.prettyPrint();
assertEquals(200, deleteUserResponse.getStatusCode());
}
@Test
public void testAddUpdateDatasetViaNativeAPI() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
Response datasetAsJson = UtilIT.nativeGet(datasetId, apiToken);
datasetAsJson.then().assertThat()
.statusCode(OK.getStatusCode());
String identifier = JsonPath.from(datasetAsJson.getBody().asString()).getString("data.identifier");
//Test Add Data
Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonBeforePublishing.prettyPrint();
String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol");
String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority");
String datasetPersistentId = protocol + ":" + authority + "/" + identifier;
String pathToJsonFile = "doc/sphinx-guides/source/_static/api/dataset-add-metadata.json";
Response addSubjectViaNative = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFile, apiToken);
addSubjectViaNative.prettyPrint();
addSubjectViaNative.then().assertThat()
.statusCode(OK.getStatusCode());
RestAssured.registerParser("text/plain", Parser.JSON);
Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken);
exportDatasetAsJson.prettyPrint();
pathToJsonFile = "doc/sphinx-guides/source/_static/api/dataset-add-subject-metadata.json";
addSubjectViaNative = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFile, apiToken);
addSubjectViaNative.prettyPrint();
addSubjectViaNative.then().assertThat()
.statusCode(OK.getStatusCode());
String pathToJsonFileSingle = "doc/sphinx-guides/source/_static/api/dataset-simple-update-metadata.json";
Response addSubjectSingleViaNative = UtilIT.updateFieldLevelDatasetMetadataViaNative(datasetPersistentId, pathToJsonFileSingle, apiToken);
addSubjectSingleViaNative.prettyPrint();
addSubjectSingleViaNative.then().assertThat()
.statusCode(OK.getStatusCode());
//Trying to blank out required field should fail...
String pathToJsonFileBadData = "doc/sphinx-guides/source/_static/api/dataset-update-with-blank-metadata.json";
Response deleteTitleViaNative = UtilIT.updateFieldLevelDatasetMetadataViaNative(datasetPersistentId, pathToJsonFileBadData, apiToken);
deleteTitleViaNative.prettyPrint();
deleteTitleViaNative.then().assertThat().body("message", equalTo("Error parsing dataset update: Empty value for field: Title "));
Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken);
Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken);
assertEquals(200, publishDataset.getStatusCode());
//post publish update
String pathToJsonFilePostPub= "doc/sphinx-guides/source/_static/api/dataset-add-metadata-after-pub.json";
Response addDataToPublishedVersion = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFilePostPub, apiToken);
addDataToPublishedVersion.prettyPrint();
addDataToPublishedVersion.then().assertThat().statusCode(OK.getStatusCode());
publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken);
//post publish update
String pathToJsonFileBadDataSubtitle = "doc/sphinx-guides/source/_static/api/dataset-edit-metadata-subtitle.json";
Response addDataToBadData = UtilIT.updateFieldLevelDatasetMetadataViaNative(datasetPersistentId, pathToJsonFileBadDataSubtitle, apiToken);
addDataToBadData.prettyPrint();
addDataToBadData.then().assertThat()
.body("message", equalToCI("Error parsing dataset update: Invalid value submitted for Subtitle. It should be a single value."))
.statusCode(400);
addSubjectViaNative = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFile, apiToken);
addSubjectViaNative.prettyPrint();
addSubjectViaNative.then().assertThat()
.statusCode(OK.getStatusCode());
String pathToJsonDeleteFile = "doc/sphinx-guides/source/_static/api/dataset-delete-subject-metadata.json";
addSubjectViaNative = UtilIT.deleteDatasetMetadataViaNative(datasetPersistentId, pathToJsonDeleteFile, apiToken);
addSubjectViaNative.prettyPrint();
addSubjectViaNative.then().assertThat()
.statusCode(OK.getStatusCode());
pathToJsonDeleteFile = "doc/sphinx-guides/source/_static/api/dataset-delete-author-metadata.json";
addSubjectViaNative = UtilIT.deleteDatasetMetadataViaNative(datasetPersistentId, pathToJsonDeleteFile, apiToken);
addSubjectViaNative.prettyPrint();
addSubjectViaNative.then().assertThat()
.statusCode(OK.getStatusCode());
pathToJsonDeleteFile = "doc/sphinx-guides/source/_static/api/dataset-delete-author-no-match.json";
addSubjectViaNative = UtilIT.deleteDatasetMetadataViaNative(datasetPersistentId, pathToJsonDeleteFile, apiToken);
addSubjectViaNative.prettyPrint();
addSubjectViaNative.then().assertThat().body("message", equalTo("Delete metadata failed: Author: Spruce, Sabrina not found."))
.statusCode(400);
//"Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found."
}
/**
* This test requires the root dataverse to be published to pass.
*/
@Test
public void testCreatePublishDestroyDataset() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
assertEquals(200, createUser.getStatusCode());
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response makeSuperUser = UtilIT.makeSuperUser(username);
assertEquals(200, makeSuperUser.getStatusCode());
Response createNoAccessUser = UtilIT.createRandomUser();
createNoAccessUser.prettyPrint();
String apiTokenNoAccess= UtilIT.getApiTokenFromResponse(createNoAccessUser);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id");
Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonBeforePublishing.prettyPrint();
String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol");
String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority");
String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier");
String datasetPersistentId = protocol + ":" + authority + "/" + identifier;
Response datasetAsJsonNoAccess = UtilIT.nativeGet(datasetId, apiTokenNoAccess);
datasetAsJsonNoAccess.then().assertThat()
.statusCode(UNAUTHORIZED.getStatusCode());
Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken);
assertEquals(200, publishDataverse.getStatusCode());
Response attemptToPublishZeroDotOne = UtilIT.publishDatasetViaNativeApiDeprecated(datasetPersistentId, "minor", apiToken);
attemptToPublishZeroDotOne.prettyPrint();
attemptToPublishZeroDotOne.then().assertThat()
.body("message", equalTo("Cannot publish as minor version. Re-try as major release."))
.statusCode(403);
Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken);
assertEquals(200, publishDataset.getStatusCode());
Response getDatasetJsonAfterPublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonAfterPublishing.prettyPrint();
getDatasetJsonAfterPublishing.then().assertThat()
.body("data.latestVersion.versionNumber", equalTo(1))
.body("data.latestVersion.versionMinorNumber", equalTo(0))
// FIXME: make this less brittle by removing "2" and "0". See also test below.
.body("data.latestVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("[email protected]"))
.statusCode(OK.getStatusCode());
Response datasetAsJsonNoAccessPostPublish = UtilIT.nativeGet(datasetId, apiTokenNoAccess);
datasetAsJsonNoAccessPostPublish.then().assertThat()
.statusCode(OK.getStatusCode());
assertTrue(datasetAsJsonNoAccessPostPublish.body().asString().contains(identifier));
List<JsonObject> datasetContactsFromNativeGet = with(getDatasetJsonAfterPublishing.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("data.latestVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }");
Map firstDatasetContactFromNativeGet = datasetContactsFromNativeGet.get(0);
assertTrue(firstDatasetContactFromNativeGet.toString().contains("[email protected]"));
RestAssured.registerParser("text/plain", Parser.JSON);
Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken);
exportDatasetAsJson.prettyPrint();
exportDatasetAsJson.then().assertThat()
.body("datasetVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("[email protected]"))
.statusCode(OK.getStatusCode());
RestAssured.unregisterParser("text/plain");
// FIXME: It would be awesome if we could just get a JSON object back instead. :(
Map<String, Object> datasetContactFromExport = with(exportDatasetAsJson.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("datasetVersion.metadataBlocks.citation.fields.find { fields -> fields.typeName == datasetContact }");
System.out.println("datasetContactFromExport: " + datasetContactFromExport);
assertEquals("datasetContact", datasetContactFromExport.get("typeName"));
List valuesArray = (ArrayList) datasetContactFromExport.get("value");
// FIXME: it's brittle to rely on the first value but what else can we do, given our API?
Map<String, Object> firstValue = (Map<String, Object>) valuesArray.get(0);
// System.out.println("firstValue: " + firstValue);
Map firstValueMap = (HashMap) firstValue.get("datasetContactEmail");
// System.out.println("firstValueMap: " + firstValueMap);
assertEquals("[email protected]", firstValueMap.get("value"));
assertTrue(datasetContactFromExport.toString().contains("[email protected]"));
assertTrue(firstValue.toString().contains("[email protected]"));
Response citationBlock = UtilIT.getMetadataBlockFromDatasetVersion(datasetPersistentId, null, null, apiToken);
citationBlock.prettyPrint();
citationBlock.then().assertThat()
.body("data.fields[2].value[0].datasetContactEmail.value", equalTo("[email protected]"))
.statusCode(OK.getStatusCode());
Response exportFail = UtilIT.exportDataset(datasetPersistentId, "noSuchExporter", apiToken);
exportFail.prettyPrint();
exportFail.then().assertThat()
.body("message", equalTo("Export Failed"))
.statusCode(FORBIDDEN.getStatusCode());
Response exportDatasetAsDublinCore = UtilIT.exportDataset(datasetPersistentId, "oai_dc", apiToken);
exportDatasetAsDublinCore.prettyPrint();
exportDatasetAsDublinCore.then().assertThat()
// FIXME: Get this working. See https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation
// .body("oai_dc:dc.find { it == 'dc:title' }.item", hasItems("Darwin's Finches"))
.statusCode(OK.getStatusCode());
Response exportDatasetAsDdi = UtilIT.exportDataset(datasetPersistentId, "ddi", apiToken);
exportDatasetAsDdi.prettyPrint();
exportDatasetAsDdi.then().assertThat()
.statusCode(OK.getStatusCode());
/**
* The Native API allows you to create a dataset contact with an email
* but no name. The email should appear in the DDI export. SWORD may
* have the same behavior. Untested. This smells like a bug.
*/
boolean nameRequiredForContactToAppear = true;
if (nameRequiredForContactToAppear) {
assertEquals("Finch, Fiona", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact"));
} else {
assertEquals("[email protected]", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@email"));
}
assertEquals(datasetPersistentId, XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.docDscr.citation.titlStmt.IDNo"));
Response deleteDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken);
deleteDatasetResponse.prettyPrint();
assertEquals(200, deleteDatasetResponse.getStatusCode());
Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken);
deleteDataverseResponse.prettyPrint();
assertEquals(200, deleteDataverseResponse.getStatusCode());
Response deleteUserResponse = UtilIT.deleteUser(username);
deleteUserResponse.prettyPrint();
assertEquals(200, deleteUserResponse.getStatusCode());
}
/**
* This test requires the root dataverse to be published to pass.
*/
@Test
public void testExport() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
assertEquals(200, createUser.getStatusCode());
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response makeSuperUser = UtilIT.makeSuperUser(username);
assertEquals(200, makeSuperUser.getStatusCode());
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
String pathToJsonFile = "scripts/api/data/dataset-create-new.json";
Response createDatasetResponse = UtilIT.createDatasetViaNativeApi(dataverseAlias, pathToJsonFile, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id");
Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonBeforePublishing.prettyPrint();
String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol");
String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority");
String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier");
String datasetPersistentId = protocol + ":" + authority + "/" + identifier;
Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken);
assertEquals(200, publishDataverse.getStatusCode());
Response attemptToPublishZeroDotOne = UtilIT.publishDatasetViaNativeApiDeprecated(datasetPersistentId, "minor", apiToken);
attemptToPublishZeroDotOne.prettyPrint();
attemptToPublishZeroDotOne.then().assertThat()
.body("message", equalTo("Cannot publish as minor version. Re-try as major release."))
.statusCode(403);
Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken);
assertEquals(200, publishDataset.getStatusCode());
Response getDatasetJsonAfterPublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonAfterPublishing.prettyPrint();
getDatasetJsonAfterPublishing.then().assertThat()
.body("data.latestVersion.versionNumber", equalTo(1))
.body("data.latestVersion.versionMinorNumber", equalTo(0))
// FIXME: make this less brittle by removing "2" and "0". See also test below.
.body("data.latestVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("[email protected]"))
.statusCode(OK.getStatusCode());
List<JsonObject> datasetContactsFromNativeGet = with(getDatasetJsonAfterPublishing.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("data.latestVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }");
Map firstDatasetContactFromNativeGet = datasetContactsFromNativeGet.get(0);
assertTrue(firstDatasetContactFromNativeGet.toString().contains("[email protected]"));
RestAssured.registerParser("text/plain", Parser.JSON);
Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken);
exportDatasetAsJson.prettyPrint();
exportDatasetAsJson.then().assertThat()
.body("datasetVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("[email protected]"))
.statusCode(OK.getStatusCode());
RestAssured.unregisterParser("text/plain");
// FIXME: It would be awesome if we could just get a JSON object back instead. :(
Map<String, Object> datasetContactFromExport = with(exportDatasetAsJson.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("datasetVersion.metadataBlocks.citation.fields.find { fields -> fields.typeName == datasetContact }");
System.out.println("datasetContactFromExport: " + datasetContactFromExport);
assertEquals("datasetContact", datasetContactFromExport.get("typeName"));
List valuesArray = (ArrayList) datasetContactFromExport.get("value");
// FIXME: it's brittle to rely on the first value but what else can we do, given our API?
Map<String, Object> firstValue = (Map<String, Object>) valuesArray.get(0);
// System.out.println("firstValue: " + firstValue);
Map firstValueMap = (HashMap) firstValue.get("datasetContactEmail");
// System.out.println("firstValueMap: " + firstValueMap);
assertEquals("[email protected]", firstValueMap.get("value"));
assertTrue(datasetContactFromExport.toString().contains("[email protected]"));
assertTrue(firstValue.toString().contains("[email protected]"));
Response citationBlock = UtilIT.getMetadataBlockFromDatasetVersion(datasetPersistentId, null, null, apiToken);
citationBlock.prettyPrint();
citationBlock.then().assertThat()
.body("data.fields[2].value[0].datasetContactEmail.value", equalTo("[email protected]"))
.statusCode(OK.getStatusCode());
Response exportFail = UtilIT.exportDataset(datasetPersistentId, "noSuchExporter", apiToken);
exportFail.prettyPrint();
exportFail.then().assertThat()
.body("message", equalTo("Export Failed"))
.statusCode(FORBIDDEN.getStatusCode());
Response exportDatasetAsDublinCore = UtilIT.exportDataset(datasetPersistentId, "oai_dc", apiToken);
exportDatasetAsDublinCore.prettyPrint();
exportDatasetAsDublinCore.then().assertThat()
// FIXME: Get this working. See https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation
// .body("oai_dc:dc.find { it == 'dc:title' }.item", hasItems("Darwin's Finches"))
.statusCode(OK.getStatusCode());
Response exportDatasetAsDdi = UtilIT.exportDataset(datasetPersistentId, "ddi", apiToken);
exportDatasetAsDdi.prettyPrint();
exportDatasetAsDdi.then().assertThat()
.statusCode(OK.getStatusCode());
assertEquals("[email protected]", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@email"));
assertEquals(datasetPersistentId, XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.docDscr.citation.titlStmt.IDNo"));
Response deleteDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken);
deleteDatasetResponse.prettyPrint();
assertEquals(200, deleteDatasetResponse.getStatusCode());
Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken);
deleteDataverseResponse.prettyPrint();
assertEquals(200, deleteDataverseResponse.getStatusCode());
Response deleteUserResponse = UtilIT.deleteUser(username);
deleteUserResponse.prettyPrint();
assertEquals(200, deleteUserResponse.getStatusCode());
}
/**
* This test requires the root dataverse to be published to pass.
*/
@Test
public void testExcludeEmail() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
assertEquals(200, createUser.getStatusCode());
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response makeSuperUser = UtilIT.makeSuperUser(username);
assertEquals(200, makeSuperUser.getStatusCode());
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
String pathToJsonFile = "scripts/api/data/dataset-create-new.json";
Response createDatasetResponse = UtilIT.createDatasetViaNativeApi(dataverseAlias, pathToJsonFile, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id");
Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonBeforePublishing.prettyPrint();
String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol");
String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority");
String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier");
String datasetPersistentId = protocol + ":" + authority + "/" + identifier;
Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken);
assertEquals(200, publishDataverse.getStatusCode());
Response attemptToPublishZeroDotOne = UtilIT.publishDatasetViaNativeApiDeprecated(datasetPersistentId, "minor", apiToken);
attemptToPublishZeroDotOne.prettyPrint();
attemptToPublishZeroDotOne.then().assertThat()
.body("message", equalTo("Cannot publish as minor version. Re-try as major release."))
.statusCode(403);
Response setToExcludeEmailFromExport = UtilIT.setSetting(SettingsServiceBean.Key.ExcludeEmailFromExport, "true");
setToExcludeEmailFromExport.then().assertThat()
.statusCode(OK.getStatusCode());
Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken);
assertEquals(200, publishDataset.getStatusCode());
Response getDatasetJsonAfterPublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonAfterPublishing.prettyPrint();
getDatasetJsonAfterPublishing.then().assertThat()
.body("data.latestVersion.versionNumber", equalTo(1))
.body("data.latestVersion.versionMinorNumber", equalTo(0))
.statusCode(OK.getStatusCode());
Response exportDatasetAsDdi = UtilIT.exportDataset(datasetPersistentId, "ddi", apiToken);
exportDatasetAsDdi.prettyPrint();
exportDatasetAsDdi.then().assertThat()
.statusCode(OK.getStatusCode());
assertEquals("Dataverse, Admin", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact"));
// no "[email protected]" to be found https://github.com/IQSS/dataverse/issues/3443
assertEquals("[]", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@email"));
assertEquals("Sample Datasets, inc.", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@affiliation"));
assertEquals(datasetPersistentId, XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.docDscr.citation.titlStmt.IDNo"));
List<JsonObject> datasetContactsFromNativeGet = with(getDatasetJsonAfterPublishing.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("data.latestVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }");
// TODO: Assert that email can't be found.
assertEquals(1, datasetContactsFromNativeGet.size());
// TODO: Write test for DDI too.
Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken);
exportDatasetAsJson.prettyPrint();
exportDatasetAsJson.then().assertThat()
.statusCode(OK.getStatusCode());
RestAssured.unregisterParser("text/plain");
List<JsonObject> datasetContactsFromExport = with(exportDatasetAsJson.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("datasetVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }");
// TODO: Assert that email can't be found.
assertEquals(1, datasetContactsFromExport.size());
Response citationBlock = UtilIT.getMetadataBlockFromDatasetVersion(datasetPersistentId, null, null, apiToken);
citationBlock.prettyPrint();
citationBlock.then().assertThat()
.statusCode(OK.getStatusCode());
List<JsonObject> datasetContactsFromCitationBlock = with(citationBlock.body().asString()).param("datasetContact", "datasetContact")
.getJsonObject("data.fields.findAll { fields -> fields.typeName == datasetContact }");
// TODO: Assert that email can't be found.
assertEquals(1, datasetContactsFromCitationBlock.size());
Response deleteDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken);
deleteDatasetResponse.prettyPrint();
assertEquals(200, deleteDatasetResponse.getStatusCode());
Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken);
deleteDataverseResponse.prettyPrint();
assertEquals(200, deleteDataverseResponse.getStatusCode());
Response deleteUserResponse = UtilIT.deleteUser(username);
deleteUserResponse.prettyPrint();
assertEquals(200, deleteUserResponse.getStatusCode());
Response removeExcludeEmail = UtilIT.deleteSetting(SettingsServiceBean.Key.ExcludeEmailFromExport);
removeExcludeEmail.then().assertThat()
.statusCode(200);
}
@Test
public void testSequentialNumberAsIdentifierGenerationStyle() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response setSequentialNumberAsIdentifierGenerationStyle = UtilIT.setSetting(SettingsServiceBean.Key.IdentifierGenerationStyle, "sequentialNumber");
setSequentialNumberAsIdentifierGenerationStyle.then().assertThat()
.statusCode(OK.getStatusCode());
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
Response datasetAsJson = UtilIT.nativeGet(datasetId, apiToken);
datasetAsJson.then().assertThat()
.statusCode(OK.getStatusCode());
String identifier = JsonPath.from(datasetAsJson.getBody().asString()).getString("data.identifier");
System.out.println("identifier: " + identifier);
String numericPart = identifier.replace("FK2/", ""); //remove shoulder from identifier
assertTrue(StringUtils.isNumeric(numericPart));
Response deleteDatasetResponse = UtilIT.deleteDatasetViaNativeApi(datasetId, apiToken);
deleteDatasetResponse.prettyPrint();
assertEquals(200, deleteDatasetResponse.getStatusCode());
Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken);
deleteDataverseResponse.prettyPrint();
assertEquals(200, deleteDataverseResponse.getStatusCode());
Response deleteUserResponse = UtilIT.deleteUser(username);
deleteUserResponse.prettyPrint();
assertEquals(200, deleteUserResponse.getStatusCode());
Response remove = UtilIT.deleteSetting(SettingsServiceBean.Key.IdentifierGenerationStyle);
remove.then().assertThat()
.statusCode(200);
}
/**
* This test requires the root dataverse to be published to pass.
*/
@Test
public void testPrivateUrl() {
Response createUser = UtilIT.createRandomUser();
// createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response failToCreateWhenDatasetIdNotFound = UtilIT.privateUrlCreate(Integer.MAX_VALUE, apiToken);
failToCreateWhenDatasetIdNotFound.prettyPrint();
assertEquals(NOT_FOUND.getStatusCode(), failToCreateWhenDatasetIdNotFound.getStatusCode());
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id");
System.out.println("dataset id: " + datasetId);
Response createContributorResponse = UtilIT.createRandomUser();
String contributorUsername = UtilIT.getUsernameFromResponse(createContributorResponse);
String contributorApiToken = UtilIT.getApiTokenFromResponse(createContributorResponse);
UtilIT.getRoleAssignmentsOnDataverse(dataverseAlias, apiToken).prettyPrint();
Response grantRoleShouldFail = UtilIT.grantRoleOnDataverse(dataverseAlias, DataverseRole.EDITOR.toString(), "doesNotExist", apiToken);
grantRoleShouldFail.then().assertThat()
.statusCode(BAD_REQUEST.getStatusCode())
.body("message", equalTo("Assignee not found"));
/**
* editor (a.k.a. Contributor) has "ViewUnpublishedDataset",
* "EditDataset", "DownloadFile", and "DeleteDatasetDraft" per
* scripts/api/data/role-editor.json
*/
Response grantRole = UtilIT.grantRoleOnDataverse(dataverseAlias, DataverseRole.EDITOR.toString(), "@" + contributorUsername, apiToken);
grantRole.prettyPrint();
assertEquals(OK.getStatusCode(), grantRole.getStatusCode());
UtilIT.getRoleAssignmentsOnDataverse(dataverseAlias, apiToken).prettyPrint();
Response contributorDoesNotHavePermissionToCreatePrivateUrl = UtilIT.privateUrlCreate(datasetId, contributorApiToken);
contributorDoesNotHavePermissionToCreatePrivateUrl.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), contributorDoesNotHavePermissionToCreatePrivateUrl.getStatusCode());
Response getDatasetJson = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJson.prettyPrint();
String protocol1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.protocol");
String authority1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.authority");
String identifier1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.identifier");
String dataset1PersistentId = protocol1 + ":" + authority1 + "/" + identifier1;
Response uploadFileResponse = UtilIT.uploadRandomFile(dataset1PersistentId, apiToken);
uploadFileResponse.prettyPrint();
assertEquals(CREATED.getStatusCode(), uploadFileResponse.getStatusCode());
Response badApiKeyEmptyString = UtilIT.privateUrlGet(datasetId, "");
badApiKeyEmptyString.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), badApiKeyEmptyString.getStatusCode());
Response badApiKeyDoesNotExist = UtilIT.privateUrlGet(datasetId, "junk");
badApiKeyDoesNotExist.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), badApiKeyDoesNotExist.getStatusCode());
Response badDatasetId = UtilIT.privateUrlGet(Integer.MAX_VALUE, apiToken);
badDatasetId.prettyPrint();
assertEquals(NOT_FOUND.getStatusCode(), badDatasetId.getStatusCode());
Response pristine = UtilIT.privateUrlGet(datasetId, apiToken);
pristine.prettyPrint();
assertEquals(NOT_FOUND.getStatusCode(), pristine.getStatusCode());
Response createPrivateUrl = UtilIT.privateUrlCreate(datasetId, apiToken);
createPrivateUrl.prettyPrint();
assertEquals(OK.getStatusCode(), createPrivateUrl.getStatusCode());
Response userWithNoRoles = UtilIT.createRandomUser();
String userWithNoRolesApiToken = UtilIT.getApiTokenFromResponse(userWithNoRoles);
Response unAuth = UtilIT.privateUrlGet(datasetId, userWithNoRolesApiToken);
unAuth.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), unAuth.getStatusCode());
Response shouldExist = UtilIT.privateUrlGet(datasetId, apiToken);
shouldExist.prettyPrint();
assertEquals(OK.getStatusCode(), shouldExist.getStatusCode());
String tokenForPrivateUrlUser = JsonPath.from(shouldExist.body().asString()).getString("data.token");
logger.info("privateUrlToken: " + tokenForPrivateUrlUser);
String urlWithToken = JsonPath.from(shouldExist.body().asString()).getString("data.link");
logger.info("URL with token: " + urlWithToken);
assertEquals(tokenForPrivateUrlUser, urlWithToken.substring(urlWithToken.length() - UUID.randomUUID().toString().length()));
/**
* If you're getting a crazy error like this...
*
* javax.net.ssl.SSLHandshakeException:
* sun.security.validator.ValidatorException: PKIX path building failed:
* sun.security.provider.certpath.SunCertPathBuilderException: unable to
* find valid certification path to requested target
*
* ... you might do well to set "siteUrl" to localhost:8080 like this:
*
* asadmin create-jvm-options
* "-Ddataverse.siteUrl=http\://localhost\:8080"
*/
Response getDatasetAsUserWhoClicksPrivateUrl = given()
.header(API_TOKEN_HTTP_HEADER, apiToken)
.get(urlWithToken);
String title = getDatasetAsUserWhoClicksPrivateUrl.getBody().htmlPath().getString("html.head.title");
assertEquals("Darwin's Finches - " + dataverseAlias, title);
assertEquals(OK.getStatusCode(), getDatasetAsUserWhoClicksPrivateUrl.getStatusCode());
Response junkPrivateUrlToken = given()
.header(API_TOKEN_HTTP_HEADER, apiToken)
.get("/privateurl.xhtml?token=" + "junk");
assertEquals("404 Not Found", junkPrivateUrlToken.getBody().htmlPath().getString("html.head.title").substring(0, 13));
long roleAssignmentIdFromCreate = JsonPath.from(createPrivateUrl.body().asString()).getLong("data.roleAssignment.id");
logger.info("roleAssignmentIdFromCreate: " + roleAssignmentIdFromCreate);
Response badAnonLinkTokenEmptyString = UtilIT.nativeGet(datasetId, "");
badAnonLinkTokenEmptyString.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), badAnonLinkTokenEmptyString.getStatusCode());
Response getWithPrivateUrlToken = UtilIT.nativeGet(datasetId, tokenForPrivateUrlUser);
assertEquals(OK.getStatusCode(), getWithPrivateUrlToken.getStatusCode());
// getWithPrivateUrlToken.prettyPrint();
logger.info("http://localhost:8080/privateurl.xhtml?token=" + tokenForPrivateUrlUser);
Response swordStatement = UtilIT.getSwordStatement(dataset1PersistentId, apiToken);
assertEquals(OK.getStatusCode(), swordStatement.getStatusCode());
Integer fileId = UtilIT.getFileIdFromSwordStatementResponse(swordStatement);
Response downloadFile = UtilIT.downloadFile(fileId, tokenForPrivateUrlUser);
assertEquals(OK.getStatusCode(), downloadFile.getStatusCode());
Response downloadFileBadToken = UtilIT.downloadFile(fileId, "junk");
assertEquals(FORBIDDEN.getStatusCode(), downloadFileBadToken.getStatusCode());
Response notPermittedToListRoleAssignment = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, userWithNoRolesApiToken);
assertEquals(UNAUTHORIZED.getStatusCode(), notPermittedToListRoleAssignment.getStatusCode());
Response roleAssignments = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, apiToken);
roleAssignments.prettyPrint();
assertEquals(OK.getStatusCode(), roleAssignments.getStatusCode());
List<JsonObject> assignments = with(roleAssignments.body().asString()).param("member", "member").getJsonObject("data.findAll { data -> data._roleAlias == member }");
assertEquals(1, assignments.size());
PrivateUrlUser privateUrlUser = new PrivateUrlUser(datasetId);
assertEquals("Private URL Enabled", privateUrlUser.getDisplayInfo().getTitle());
List<JsonObject> assigneeShouldExistForPrivateUrlUser = with(roleAssignments.body().asString()).param("assigneeString", privateUrlUser.getIdentifier()).getJsonObject("data.findAll { data -> data.assignee == assigneeString }");
logger.info(assigneeShouldExistForPrivateUrlUser + " found for " + privateUrlUser.getIdentifier());
assertEquals(1, assigneeShouldExistForPrivateUrlUser.size());
Map roleAssignment = assignments.get(0);
int roleAssignmentId = (int) roleAssignment.get("id");
logger.info("role assignment id: " + roleAssignmentId);
assertEquals(roleAssignmentIdFromCreate, roleAssignmentId);
Response revoke = UtilIT.revokeRole(dataverseAlias, roleAssignmentId, apiToken);
revoke.prettyPrint();
assertEquals(OK.getStatusCode(), revoke.getStatusCode());
Response shouldNoLongerExist = UtilIT.privateUrlGet(datasetId, apiToken);
shouldNoLongerExist.prettyPrint();
assertEquals(NOT_FOUND.getStatusCode(), shouldNoLongerExist.getStatusCode());
Response createPrivateUrlUnauth = UtilIT.privateUrlCreate(datasetId, userWithNoRolesApiToken);
createPrivateUrlUnauth.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), createPrivateUrlUnauth.getStatusCode());
Response createPrivateUrlAgain = UtilIT.privateUrlCreate(datasetId, apiToken);
createPrivateUrlAgain.prettyPrint();
assertEquals(OK.getStatusCode(), createPrivateUrlAgain.getStatusCode());
Response shouldNotDeletePrivateUrl = UtilIT.privateUrlDelete(datasetId, userWithNoRolesApiToken);
shouldNotDeletePrivateUrl.prettyPrint();
assertEquals(UNAUTHORIZED.getStatusCode(), shouldNotDeletePrivateUrl.getStatusCode());
Response deletePrivateUrlResponse = UtilIT.privateUrlDelete(datasetId, apiToken);
deletePrivateUrlResponse.prettyPrint();
assertEquals(OK.getStatusCode(), deletePrivateUrlResponse.getStatusCode());
Response tryToDeleteAlreadyDeletedPrivateUrl = UtilIT.privateUrlDelete(datasetId, apiToken);
tryToDeleteAlreadyDeletedPrivateUrl.prettyPrint();
assertEquals(NOT_FOUND.getStatusCode(), tryToDeleteAlreadyDeletedPrivateUrl.getStatusCode());
Response createPrivateUrlOnceAgain = UtilIT.privateUrlCreate(datasetId, apiToken);
createPrivateUrlOnceAgain.prettyPrint();
assertEquals(OK.getStatusCode(), createPrivateUrlOnceAgain.getStatusCode());
Response tryToCreatePrivateUrlWhenExisting = UtilIT.privateUrlCreate(datasetId, apiToken);
tryToCreatePrivateUrlWhenExisting.prettyPrint();
assertEquals(FORBIDDEN.getStatusCode(), tryToCreatePrivateUrlWhenExisting.getStatusCode());
Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken);
assertEquals(OK.getStatusCode(), publishDataverse.getStatusCode());
Response publishDataset = UtilIT.publishDatasetViaSword(dataset1PersistentId, apiToken);
assertEquals(OK.getStatusCode(), publishDataset.getStatusCode());
Response privateUrlTokenShouldBeDeletedOnPublish = UtilIT.privateUrlGet(datasetId, apiToken);
privateUrlTokenShouldBeDeletedOnPublish.prettyPrint();
assertEquals(NOT_FOUND.getStatusCode(), privateUrlTokenShouldBeDeletedOnPublish.getStatusCode());
Response getRoleAssignmentsOnDatasetShouldFailUnauthorized = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, userWithNoRolesApiToken);
assertEquals(UNAUTHORIZED.getStatusCode(), getRoleAssignmentsOnDatasetShouldFailUnauthorized.getStatusCode());
Response publishingShouldHaveRemovedRoleAssignmentForPrivateUrlUser = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, apiToken);
publishingShouldHaveRemovedRoleAssignmentForPrivateUrlUser.prettyPrint();
List<JsonObject> noAssignmentsForPrivateUrlUser = with(publishingShouldHaveRemovedRoleAssignmentForPrivateUrlUser.body().asString()).param("member", "member").getJsonObject("data.findAll { data -> data._roleAlias == member }");
assertEquals(0, noAssignmentsForPrivateUrlUser.size());
Response tryToCreatePrivateUrlToPublishedVersion = UtilIT.privateUrlCreate(datasetId, apiToken);
tryToCreatePrivateUrlToPublishedVersion.prettyPrint();
assertEquals(FORBIDDEN.getStatusCode(), tryToCreatePrivateUrlToPublishedVersion.getStatusCode());
String newTitle = "I am changing the title";
Response updatedMetadataResponse = UtilIT.updateDatasetTitleViaSword(dataset1PersistentId, newTitle, apiToken);
updatedMetadataResponse.prettyPrint();
assertEquals(OK.getStatusCode(), updatedMetadataResponse.getStatusCode());
Response createPrivateUrlForPostVersionOneDraft = UtilIT.privateUrlCreate(datasetId, apiToken);
createPrivateUrlForPostVersionOneDraft.prettyPrint();
assertEquals(OK.getStatusCode(), createPrivateUrlForPostVersionOneDraft.getStatusCode());
// A Contributor has DeleteDatasetDraft
Response deleteDraftVersionAsContributor = UtilIT.deleteDatasetVersionViaNativeApi(datasetId, ":draft", contributorApiToken);
deleteDraftVersionAsContributor.prettyPrint();
deleteDraftVersionAsContributor.then().assertThat()
.statusCode(OK.getStatusCode())
.body("data.message", equalTo("Draft version of dataset " + datasetId + " deleted"));
Response privateUrlRoleAssignmentShouldBeGoneAfterDraftDeleted = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, apiToken);
privateUrlRoleAssignmentShouldBeGoneAfterDraftDeleted.prettyPrint();
assertEquals(false, privateUrlRoleAssignmentShouldBeGoneAfterDraftDeleted.body().asString().contains(privateUrlUser.getIdentifier()));
String newTitleAgain = "I am changing the title again";
Response draftCreatedAgainPostPub = UtilIT.updateDatasetTitleViaSword(dataset1PersistentId, newTitleAgain, apiToken);
draftCreatedAgainPostPub.prettyPrint();
assertEquals(OK.getStatusCode(), draftCreatedAgainPostPub.getStatusCode());
/**
* Making sure the Private URL is deleted when a dataset is destroyed is
* less of an issue now that a Private URL is now effectively only a
* specialized role assignment which is already known to be deleted when
* a dataset is destroy. Still, we'll keep this test in here in case we
* switch Private URL back to being its own table in the future.
*/
Response createPrivateUrlToMakeSureItIsDeletedWithDestructionOfDataset = UtilIT.privateUrlCreate(datasetId, apiToken);
createPrivateUrlToMakeSureItIsDeletedWithDestructionOfDataset.prettyPrint();
assertEquals(OK.getStatusCode(), createPrivateUrlToMakeSureItIsDeletedWithDestructionOfDataset.getStatusCode());
/**
* @todo What about deaccessioning? We can't test deaccessioning via API
* until https://github.com/IQSS/dataverse/issues/778 is worked on. If
* you deaccession a dataset, is the Private URL deleted? Probably not
* because in order to create a Private URL the dataset version must be
* a draft and for that draft to be deaccessioned it must be published
* first and publishing a version will delete the Private URL. So, we
* shouldn't need to worry about cleaning up Private URLs in the case of
* deaccessioning.
*/
Response makeSuperUser = UtilIT.makeSuperUser(username);
assertEquals(200, makeSuperUser.getStatusCode());
Response destroyDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken);
destroyDatasetResponse.prettyPrint();
assertEquals(200, destroyDatasetResponse.getStatusCode());
Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken);
deleteDataverseResponse.prettyPrint();
assertEquals(200, deleteDataverseResponse.getStatusCode());
Response deleteUserResponse = UtilIT.deleteUser(username);
deleteUserResponse.prettyPrint();
assertEquals(200, deleteUserResponse.getStatusCode());
/**
* @todo Should the Search API work with the Private URL token?
*/
}
@Test
public void testFileChecksum() {
Response createUser = UtilIT.createRandomUser();
// createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id");
System.out.println("dataset id: " + datasetId);
Response getDatasetJsonNoFiles = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonNoFiles.prettyPrint();
String protocol1 = JsonPath.from(getDatasetJsonNoFiles.getBody().asString()).getString("data.protocol");
String authority1 = JsonPath.from(getDatasetJsonNoFiles.getBody().asString()).getString("data.authority");
String identifier1 = JsonPath.from(getDatasetJsonNoFiles.getBody().asString()).getString("data.identifier");
String dataset1PersistentId = protocol1 + ":" + authority1 + "/" + identifier1;
Response makeSureSettingIsDefault = UtilIT.deleteSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm);
makeSureSettingIsDefault.prettyPrint();
makeSureSettingIsDefault.then().assertThat()
.statusCode(OK.getStatusCode())
.body("data.message", equalTo("Setting :FileFixityChecksumAlgorithm deleted."));
Response getDefaultSetting = UtilIT.getSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm);
getDefaultSetting.prettyPrint();
getDefaultSetting.then().assertThat()
.body("message", equalTo("Setting :FileFixityChecksumAlgorithm not found"));
Response uploadMd5File = UtilIT.uploadRandomFile(dataset1PersistentId, apiToken);
uploadMd5File.prettyPrint();
assertEquals(CREATED.getStatusCode(), uploadMd5File.getStatusCode());
Response getDatasetJsonAfterMd5File = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonAfterMd5File.prettyPrint();
getDatasetJsonAfterMd5File.then().assertThat()
.body("data.latestVersion.files[0].dataFile.md5", equalTo("0386269a5acb2c57b4eade587ff4db64"))
.body("data.latestVersion.files[0].dataFile.checksum.type", equalTo("MD5"))
.body("data.latestVersion.files[0].dataFile.checksum.value", equalTo("0386269a5acb2c57b4eade587ff4db64"));
int fileId = JsonPath.from(getDatasetJsonAfterMd5File.getBody().asString()).getInt("data.latestVersion.files[0].dataFile.id");
Response deleteFile = UtilIT.deleteFile(fileId, apiToken);
deleteFile.prettyPrint();
deleteFile.then().assertThat()
.statusCode(NO_CONTENT.getStatusCode());
Response setToSha1 = UtilIT.setSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm, DataFile.ChecksumType.SHA1.toString());
setToSha1.prettyPrint();
setToSha1.then().assertThat()
.statusCode(OK.getStatusCode());
Response getNonDefaultSetting = UtilIT.getSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm);
getNonDefaultSetting.prettyPrint();
getNonDefaultSetting.then().assertThat()
.body("data.message", equalTo("SHA-1"))
.statusCode(OK.getStatusCode());
Response uploadSha1File = UtilIT.uploadRandomFile(dataset1PersistentId, apiToken);
uploadSha1File.prettyPrint();
assertEquals(CREATED.getStatusCode(), uploadSha1File.getStatusCode());
Response getDatasetJsonAfterSha1File = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonAfterSha1File.prettyPrint();
getDatasetJsonAfterSha1File.then().assertThat()
.body("data.latestVersion.files[0].dataFile.md5", nullValue())
.body("data.latestVersion.files[0].dataFile.checksum.type", equalTo("SHA-1"))
.body("data.latestVersion.files[0].dataFile.checksum.value", equalTo("17ea9225aa0e96ae6ff61c256237d6add6c197d1"))
.statusCode(OK.getStatusCode());
}
@Test
public void testDeleteDatasetWhileFileIngesting() {
Response createUser = UtilIT.createRandomUser();
createUser.then().assertThat()
.statusCode(OK.getStatusCode());
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
createDataverseResponse.then().assertThat()
.statusCode(CREATED.getStatusCode());
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
createDatasetResponse.then().assertThat()
.statusCode(CREATED.getStatusCode());
Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id");
String persistentId = JsonPath.from(createDatasetResponse.body().asString()).getString("data.persistentId");
logger.info("Dataset created with id " + datasetId + " and persistent id " + persistentId);
String pathToFileThatGoesThroughIngest = "scripts/search/data/tabular/50by1000.dta";
Response uploadIngestableFile = UtilIT.uploadFileViaNative(datasetId.toString(), pathToFileThatGoesThroughIngest, apiToken);
uploadIngestableFile.then().assertThat()
.statusCode(OK.getStatusCode());
Response deleteDataset = UtilIT.deleteDatasetViaNativeApi(datasetId, apiToken);
deleteDataset.prettyPrint();
deleteDataset.then().assertThat()
.body("message", equalTo("Dataset cannot be edited due to dataset lock."))
.statusCode(FORBIDDEN.getStatusCode());
}
/**
* In order for this test to pass you must have the Data Capture Module (
* https://github.com/sbgrid/data-capture-module ) running. We assume that
* most developers haven't set up the DCM so the test is disabled.
*/
@Test
public void testCreateDatasetWithDcmDependency() {
boolean disabled = true;
if (disabled) {
return;
}
// TODO: Test this with a value like "junk" rather than a valid URL which would give `java.net.MalformedURLException: no protocol`.
// The DCM Vagrant box runs on port 8888: https://github.com/sbgrid/data-capture-module/blob/master/Vagrantfile
String dcmVagrantUrl = "http://localhost:8888";
// The DCM mock runs on port 5000: https://github.com/sbgrid/data-capture-module/blob/master/doc/mock.md
String dcmMockUrl = "http://localhost:5000";
String dcmUrl = dcmMockUrl;
Response setDcmUrl = UtilIT.setSetting(SettingsServiceBean.Key.DataCaptureModuleUrl, dcmUrl);
setDcmUrl.then().assertThat()
.statusCode(OK.getStatusCode());
Response setUploadMethods = UtilIT.setSetting(SettingsServiceBean.Key.UploadMethods, SystemConfig.FileUploadMethods.RSYNC.toString());
setUploadMethods.then().assertThat()
.statusCode(OK.getStatusCode());
Response urlConfigured = given()
// .header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken)
.get("/api/admin/settings/" + SettingsServiceBean.Key.DataCaptureModuleUrl.toString());
if (urlConfigured.getStatusCode() != 200) {
fail(SettingsServiceBean.Key.DataCaptureModuleUrl + " has not been not configured. This test cannot run without it.");
}
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
long userId = JsonPath.from(createUser.body().asString()).getLong("data.authenticatedUser.id");
/**
* @todo Query system to see which file upload mechanisms are available.
*/
// String dataverseAlias = "dv" + UtilIT.getRandomIdentifier();
// List<String> fileUploadMechanismsEnabled = Arrays.asList(Dataset.FileUploadMechanism.RSYNC.toString());
// Response createDataverseResponse = UtilIT.createDataverse(dataverseAlias, fileUploadMechanismsEnabled, apiToken);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
createDataverseResponse.then().assertThat()
// .body("data.alias", equalTo(dataverseAlias))
// .body("data.fileUploadMechanismsEnabled[0]", equalTo(Dataset.FileUploadMechanism.RSYNC.toString()))
.statusCode(201);
/**
* @todo Make this configurable at runtime similar to
* UtilIT.getRestAssuredBaseUri
*/
// Response createDatasetResponse = UtilIT.createDatasetWithDcmDependency(dataverseAlias, apiToken);
// Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
Response getDatasetJson = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJson.prettyPrint();
String protocol1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.protocol");
String authority1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.authority");
String identifier1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.identifier");
String datasetPersistentId = protocol1 + ":" + authority1 + "/" + identifier1;
Response getDatasetResponse = given()
.header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken)
.get("/api/datasets/" + datasetId);
getDatasetResponse.prettyPrint();
getDatasetResponse.then().assertThat()
.statusCode(200);
// final List<Map<String, ?>> dataTypeField = JsonPath.with(getDatasetResponse.body().asString())
// .get("data.latestVersion.metadataBlocks.citation.fields.findAll { it.typeName == 'dataType' }");
// logger.fine("dataTypeField: " + dataTypeField);
// assertThat(dataTypeField.size(), equalTo(1));
// assertEquals("dataType", dataTypeField.get(0).get("typeName"));
// assertEquals("controlledVocabulary", dataTypeField.get(0).get("typeClass"));
// assertEquals("X-Ray Diffraction", dataTypeField.get(0).get("value"));
// assertTrue(dataTypeField.get(0).get("multiple").equals(false));
String nullTokenToIndicateGuest = null;
Response getRsyncScriptPermErrorGuest = UtilIT.getRsyncScript(datasetPersistentId, nullTokenToIndicateGuest);
getRsyncScriptPermErrorGuest.prettyPrint();
getRsyncScriptPermErrorGuest.then().assertThat()
.contentType(ContentType.JSON)
.body("message", equalTo("User :guest is not permitted to perform requested action."))
.statusCode(UNAUTHORIZED.getStatusCode());
Response createNoPermsUser = UtilIT.createRandomUser();
String noPermsUsername = UtilIT.getUsernameFromResponse(createNoPermsUser);
String noPermsApiToken = UtilIT.getApiTokenFromResponse(createNoPermsUser);
Response getRsyncScriptPermErrorNonGuest = UtilIT.getRsyncScript(datasetPersistentId, noPermsApiToken);
getRsyncScriptPermErrorNonGuest.then().assertThat()
.contentType(ContentType.JSON)
.body("message", equalTo("User @" + noPermsUsername + " is not permitted to perform requested action."))
.statusCode(UNAUTHORIZED.getStatusCode());
boolean stopEarlyBecauseYouDoNotHaveDcmInstalled = true;
if (stopEarlyBecauseYouDoNotHaveDcmInstalled) {
return;
}
boolean stopEarlyToVerifyTheScriptWasCreated = false;
if (stopEarlyToVerifyTheScriptWasCreated) {
logger.info("On the DCM, does /deposit/gen/upload-" + datasetId + ".bash exist? It should! Creating the dataset should be enough to create it.");
return;
}
Response getRsyncScript = UtilIT.getRsyncScript(datasetPersistentId, apiToken);
getRsyncScript.prettyPrint();
System.out.println("content type: " + getRsyncScript.getContentType()); // text/html;charset=ISO-8859-1
getRsyncScript.then().assertThat()
.contentType(ContentType.TEXT)
.statusCode(200);
String rsyncScript = getRsyncScript.body().asString();
System.out.println("script:\n" + rsyncScript);
assertTrue(rsyncScript.startsWith("#!"));
assertTrue(rsyncScript.contains("placeholder")); // The DCM mock script has the word "placeholder" in it.
Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods);
removeUploadMethods.then().assertThat()
.statusCode(200);
Response createUser2 = UtilIT.createRandomUser();
String username2 = UtilIT.getUsernameFromResponse(createUser2);
String apiToken2 = UtilIT.getApiTokenFromResponse(createUser2);
Response createDataverseResponse2 = UtilIT.createRandomDataverse(apiToken2);
createDataverseResponse2.prettyPrint();
String dataverseAlias2 = UtilIT.getAliasFromResponse(createDataverseResponse2);
Response createDatasetResponse2 = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias2, apiToken2);
createDatasetResponse2.prettyPrint();
Integer datasetId2 = JsonPath.from(createDatasetResponse2.body().asString()).getInt("data.id");
System.out.println("dataset id: " + datasetId);
Response attemptToGetRsyncScriptForNonRsyncDataset = given()
.header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken2)
.get("/api/datasets/" + datasetId2 + "/dataCaptureModule/rsync");
attemptToGetRsyncScriptForNonRsyncDataset.prettyPrint();
attemptToGetRsyncScriptForNonRsyncDataset.then().assertThat()
.body("message", equalTo(":UploadMethods does not contain dcm/rsync+ssh."))
.statusCode(METHOD_NOT_ALLOWED.getStatusCode());
}
/**
* This test is just a test of notifications so a fully implemented dcm is
* not necessary
*/
@Test
public void testDcmChecksumValidationMessages() throws IOException, InterruptedException {
/*SEK 3/28/2018 This test needs more work
Currently it is failing at around line 1114
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
the CreateDatasetCommand is not getting the rsync script so the dataset is not being created
so the whole test is failing
*/
boolean disabled = true;
if (disabled) {
return;
}
// The DCM Vagrant box runs on port 8888: https://github.com/sbgrid/data-capture-module/blob/master/Vagrantfile
String dcmVagrantUrl = "http://localhost:8888";
// The DCM mock runs on port 5000: https://github.com/sbgrid/data-capture-module/blob/master/doc/mock.md
String dcmMockUrl = "http://localhost:5000";
String dcmUrl = dcmMockUrl;
Response setDcmUrl = UtilIT.setSetting(SettingsServiceBean.Key.DataCaptureModuleUrl, dcmUrl);
setDcmUrl.then().assertThat()
.statusCode(OK.getStatusCode());
Response setUploadMethods = UtilIT.setSetting(SettingsServiceBean.Key.UploadMethods, SystemConfig.FileUploadMethods.RSYNC.toString());
setUploadMethods.then().assertThat()
.statusCode(OK.getStatusCode());
Response urlConfigured = given()
.get("/api/admin/settings/" + SettingsServiceBean.Key.DataCaptureModuleUrl.toString());
if (urlConfigured.getStatusCode() != 200) {
fail(SettingsServiceBean.Key.DataCaptureModuleUrl + " has not been not configured. This test cannot run without it.");
}
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
long userId = JsonPath.from(createUser.body().asString()).getLong("data.authenticatedUser.id");
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
createDataverseResponse.then().assertThat()
.statusCode(201);
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
Response getDatasetJson = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJson.prettyPrint();
Response getDatasetResponse = given()
.header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken)
.get("/api/datasets/" + datasetId);
getDatasetResponse.prettyPrint();
getDatasetResponse.then().assertThat()
.statusCode(200);
boolean stopEarlyToVerifyTheScriptWasCreated = false;
if (stopEarlyToVerifyTheScriptWasCreated) {
logger.info("On the DCM, does /deposit/gen/upload-" + datasetId + ".bash exist? It should! Creating the dataset should be enough to create it.");
return;
}
Response createUser2 = UtilIT.createRandomUser();
String apiToken2 = UtilIT.getApiTokenFromResponse(createUser2);
Response createDataverseResponse2 = UtilIT.createRandomDataverse(apiToken2);
createDataverseResponse2.prettyPrint();
String dataverseAlias2 = UtilIT.getAliasFromResponse(createDataverseResponse2);
Response createDatasetResponse2 = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias2, apiToken2);
createDatasetResponse2.prettyPrint();
Integer datasetId2 = JsonPath.from(createDatasetResponse2.body().asString()).getInt("data.id");
Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken);
getDatasetJsonBeforePublishing.prettyPrint();
String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol");
String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority");
String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier");
String datasetPersistentId = protocol + ":" + authority + "/" + identifier;
/**
* Here we are pretending to be the Data Capture Module reporting on if
* checksum validation success or failure. Don't notify the user on
* success (too chatty) but do notify on failure.
*
* @todo On success a process should be kicked off to crawl the files so
* they are imported into Dataverse. Once the crawling and importing is
* complete, notify the user.
*
* @todo What authentication should be used here? The API token of the
* user? (If so, pass the token in the initial upload request payload.)
* This is suboptimal because of the security risk of having the Data
* Capture Module store the API token. Or should Dataverse be able to be
* configured so that it only will receive these messages from trusted
* IP addresses? Should there be a shared secret that's used for *all*
* requests from the Data Capture Module to Dataverse?
*/
/*
Can't find dataset - give bad dataset ID
*/
JsonObjectBuilder wrongDataset = Json.createObjectBuilder();
String fakeDatasetId = "78921457982457921";
wrongDataset.add("status", "validation passed");
Response createSuperuser = UtilIT.createRandomUser();
String superuserApiToken = UtilIT.getApiTokenFromResponse(createSuperuser);
String superuserUsername = UtilIT.getUsernameFromResponse(createSuperuser);
UtilIT.makeSuperUser(superuserUsername);
Response datasetNotFound = UtilIT.dataCaptureModuleChecksumValidation(fakeDatasetId, wrongDataset.build(), superuserApiToken);
datasetNotFound.prettyPrint();
datasetNotFound.then().assertThat()
.statusCode(404)
.body("message", equalTo("Dataset with ID " + fakeDatasetId + " not found."));
JsonObjectBuilder badNews = Json.createObjectBuilder();
// Status options are documented at https://github.com/sbgrid/data-capture-module/blob/master/doc/api.md#post-upload
badNews.add("status", "validation failed");
Response uploadFailed = UtilIT.dataCaptureModuleChecksumValidation(datasetPersistentId, badNews.build(), superuserApiToken);
uploadFailed.prettyPrint();
uploadFailed.then().assertThat()
/**
* @todo Double check that we're ok with 200 here. We're saying
* "Ok, the bad news was delivered." We had a success of
* informing the user of bad news.
*/
.statusCode(200)
.body("data.message", equalTo("User notified about checksum validation failure."));
Response authorsGetsBadNews = UtilIT.getNotifications(apiToken);
authorsGetsBadNews.prettyPrint();
authorsGetsBadNews.then().assertThat()
.body("data.notifications[0].type", equalTo("CHECKSUMFAIL"))
.statusCode(OK.getStatusCode());
Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods);
removeUploadMethods.then().assertThat()
.statusCode(200);
String uploadFolder = identifier;
/**
* The "extra testing" involves having this REST Assured test do two
* jobs done by the rsync script and the DCM. The rsync script creates
* "files.sha" and (if checksum validation succeeds) the DCM moves the
* files and the "files.sha" file into the uploadFolder.
*/
boolean doExtraTesting = false;
if (doExtraTesting) {
String SEP = java.io.File.separator;
// Set this to where you keep your files in dev. It might be nice to have an API to query to get this location from Dataverse.
String dsDir = "/Users/pdurbin/dataverse/files/10.5072/FK2";
java.nio.file.Files.createDirectories(java.nio.file.Paths.get(dsDir + SEP + identifier));
java.nio.file.Files.createDirectories(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder));
String checksumFilename = "files.sha";
String filename1 = "file1.txt";
String fileContent1 = "big data!";
java.nio.file.Files.write(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder + SEP + checksumFilename), fileContent1.getBytes());
// // This is actually the SHA-1 of a zero byte file. It doesn't seem to matter what you send to the DCM?
String checksumFileContent = "da39a3ee5e6b4b0d3255bfef95601890afd80709 " + filename1;
java.nio.file.Files.createFile(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder + SEP + filename1));
java.nio.file.Files.write(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder + SEP + checksumFilename), checksumFileContent.getBytes());
}
int totalSize = 1234567890;
/**
* @todo How can we test what the checksum validation notification looks
* like in the GUI? There is no API for retrieving notifications.
*
* @todo How can we test that the email notification looks ok?
*/
JsonObjectBuilder goodNews = Json.createObjectBuilder();
goodNews.add("status", "validation passed");
goodNews.add("uploadFolder", uploadFolder);
goodNews.add("totalSize", totalSize);
Response uploadSuccessful = UtilIT.dataCaptureModuleChecksumValidation(datasetPersistentId, goodNews.build(), superuserApiToken);
/**
* Errors here are expected unless you've set doExtraTesting to true to
* do the jobs of the rsync script and the DCM to create the files.sha
* file and put it and the data files in place. You might see stuff
* like: "message": "Uploaded files have passed checksum validation but
* something went wrong while attempting to put the files into
* Dataverse. Status code was 400 and message was 'Dataset directory is
* invalid.'."
*/
uploadSuccessful.prettyPrint();
if (doExtraTesting) {
uploadSuccessful.then().assertThat()
.body("data.message", equalTo("FileSystemImportJob in progress"))
.statusCode(200);
if (doExtraTesting) {
long millisecondsNeededForFileSystemImportJobToFinish = 1000;
Thread.sleep(millisecondsNeededForFileSystemImportJobToFinish);
Response datasetAsJson2 = UtilIT.nativeGet(datasetId, apiToken);
datasetAsJson2.prettyPrint();
datasetAsJson2.then().assertThat()
.body("data.latestVersion.files[0].dataFile.filename", equalTo(identifier))
.body("data.latestVersion.files[0].dataFile.contentType", equalTo("application/vnd.dataverse.file-package"))
.body("data.latestVersion.files[0].dataFile.filesize", equalTo(totalSize))
.body("data.latestVersion.files[0].dataFile.checksum.type", equalTo("SHA-1"))
.statusCode(OK.getStatusCode());
}
}
logger.info("username/password: " + username);
}
@Test
public void testCreateDeleteDatasetLink() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response superuserResponse = UtilIT.makeSuperUser(username);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
// This should fail, because we are attempting to link the dataset
// to its own dataverse:
Response createLinkingDatasetResponse = UtilIT.createDatasetLink(datasetId.longValue(), dataverseAlias, apiToken);
createLinkingDatasetResponse.prettyPrint();
createLinkingDatasetResponse.then().assertThat()
.body("message", equalTo("Can't link a dataset to its dataverse"))
.statusCode(FORBIDDEN.getStatusCode());
// OK, let's create a different random dataverse:
createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
// And link the dataset to this new dataverse:
createLinkingDatasetResponse = UtilIT.createDatasetLink(datasetId.longValue(), dataverseAlias, apiToken);
createLinkingDatasetResponse.prettyPrint();
createLinkingDatasetResponse.then().assertThat()
.body("data.message", equalTo("Dataset " + datasetId +" linked successfully to " + dataverseAlias))
.statusCode(200);
// And now test deleting it:
Response deleteLinkingDatasetResponse = UtilIT.deleteDatasetLink(datasetId.longValue(), dataverseAlias, apiToken);
deleteLinkingDatasetResponse.prettyPrint();
deleteLinkingDatasetResponse.then().assertThat()
.body("data.message", equalTo("Link from Dataset " + datasetId + " to linked Dataverse " + dataverseAlias + " deleted"))
.statusCode(200);
}
@Test
public void testDatasetLocksApi() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response superuserResponse = UtilIT.makeSuperUser(username);
Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken);
createDataverseResponse.prettyPrint();
String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse);
Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken);
createDatasetResponse.prettyPrint();
Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse);
// This should return an empty list, as the dataset should have no locks just yet:
Response checkDatasetLocks = UtilIT.checkDatasetLocks(datasetId.longValue(), null, apiToken);
checkDatasetLocks.prettyPrint();
JsonArray emptyArray = Json.createArrayBuilder().build();
checkDatasetLocks.then().assertThat()
.body("data", equalTo(emptyArray))
.statusCode(200);
// Lock the dataset with an ingest lock:
Response lockDatasetResponse = UtilIT.lockDataset(datasetId.longValue(), "Ingest", apiToken);
lockDatasetResponse.prettyPrint();
lockDatasetResponse.then().assertThat()
.body("data.message", equalTo("dataset locked with lock type Ingest"))
.statusCode(200);
// Check again:
// This should return an empty list, as the dataset should have no locks just yet:
checkDatasetLocks = UtilIT.checkDatasetLocks(datasetId.longValue(), "Ingest", apiToken);
checkDatasetLocks.prettyPrint();
checkDatasetLocks.then().assertThat()
.body("data[0].lockType", equalTo("Ingest"))
.statusCode(200);
// Try to lock the dataset with the same type lock, AGAIN
// (this should fail, of course!)
lockDatasetResponse = UtilIT.lockDataset(datasetId.longValue(), "Ingest", apiToken);
lockDatasetResponse.prettyPrint();
lockDatasetResponse.then().assertThat()
.body("message", equalTo("dataset already locked with lock type Ingest"))
.statusCode(FORBIDDEN.getStatusCode());
// And now test deleting the lock:
Response unlockDatasetResponse = UtilIT.unlockDataset(datasetId.longValue(), "Ingest", apiToken);
unlockDatasetResponse.prettyPrint();
unlockDatasetResponse.then().assertThat()
.body("data.message", equalTo("lock type Ingest removed"))
.statusCode(200);
// ... and check for the lock on the dataset again, this time by specific lock type:
// (should return an empty list, now that we have unlocked it)
checkDatasetLocks = UtilIT.checkDatasetLocks(datasetId.longValue(), "Ingest", apiToken);
checkDatasetLocks.prettyPrint();
checkDatasetLocks.then().assertThat()
.body("data", equalTo(emptyArray))
.statusCode(200);
}
}
| 1 | 38,719 | It would be nice to fix the indentation above. | IQSS-dataverse | java |
@@ -9334,8 +9334,8 @@ return [
'openssl_x509_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_x509_fingerprint' => ['string|false', 'certificate'=>'string|resource', 'digest_algo='=>'string', 'binary='=>'bool'],
'openssl_x509_free' => ['void', 'certificate'=>'resource'],
-'openssl_x509_parse' => ['array|false', 'certificate'=>'string|resource', 'short_names='=>'bool'],
-'openssl_x509_read' => ['resource|false', 'certificate'=>'string|resource'],
+'openssl_x509_parse' => ['array|false', 'certificate'=>'OpenSSLCertificate|string', 'short_names'=>'bool|null'],
+'openssl_x509_read' => ['OpenSSLCertificate|false', 'certificate'=>'OpenSSLCertificate|string'],
'ord' => ['int', 'character'=>'string'],
'OuterIterator::current' => ['mixed'],
'OuterIterator::getInnerIterator' => ['Iterator'], | 1 | <?php // phpcs:ignoreFile
namespace Phan\Language\Internal;
/**
* CURRENT PHP TARGET VERSION: 8.0
* The version above has to match Psalm\Internal\Codebase\InternalCallMapHandler::PHP_(MAJOR|MINOR)_VERSION
*
* 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', 'num'=>'int'],
'abs\'1' => ['float', 'num'=>'float'],
'abs\'2' => ['numeric', 'num'=>'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', 'num'=>'float'],
'acosh' => ['float', 'num'=>'float'],
'addcslashes' => ['string', 'string'=>'string', 'characters'=>'string'],
'addslashes' => ['string', 'string'=>'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' => ['list<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'],
'APCuIterator::getTotalCount' => ['int'],
'APCuIterator::getTotalHits' => ['int'],
'APCuIterator::getTotalSize' => ['int'],
'APCuIterator::key' => ['string'],
'APCuIterator::next' => ['void'],
'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' => ['list<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' => ['list<array<string,mixed>>'],
'ArithmeticError::getTraceAsString' => ['string'],
'array_change_key_case' => ['associative-array', 'array'=>'array', 'case='=>'int'],
'array_chunk' => ['list<array[]>', 'array'=>'array', 'length'=>'int', 'preserve_keys='=>'bool'],
'array_column' => ['array', 'array'=>'array', 'column_key'=>'mixed', 'index_key='=>'mixed'],
'array_combine' => ['associative-array', 'keys'=>'string[]|int[]', 'values'=>'array'],
'array_count_values' => ['associative-array<mixed,int>', 'array'=>'array'],
'array_diff' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_assoc' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_key' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_diff_ukey' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_ukey\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_fill' => ['array<int,mixed>', 'start_index'=>'int', 'count'=>'int', 'value'=>'mixed'],
'array_fill_keys' => ['array', 'keys'=>'array', 'value'=>'mixed'],
'array_filter' => ['associative-array', 'array'=>'array', 'callback='=>'callable(mixed,mixed=):scalar', 'mode='=>'int'],
'array_flip' => ['associative-array<mixed,int>|associative-array<mixed,string>', 'array'=>'array'],
'array_intersect' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_assoc' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_key' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_intersect_ukey' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_ukey\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_key_exists' => ['bool', 'key'=>'string|int', 'array'=>'array|ArrayObject'],
'array_key_first' => ['int|string|null', 'array'=>'array'],
'array_key_last' => ['int|string|null', 'array'=>'array'],
'array_keys' => ['list<string|int>', 'array'=>'array', 'filter_value='=>'mixed', 'strict='=>'bool'],
'array_map' => ['array', 'callback'=>'?callable', 'array'=>'array', '...arrays='=>'array'],
'array_merge' => ['array', 'arrays'=>'array', '...args='=>'array'],
'array_merge_recursive' => ['array', 'arrays'=>'array', '...args='=>'array'],
'array_multisort' => ['bool', '&rw_array'=>'array', 'rest='=>'array|int', 'array1_sort_flags='=>'array|int', '...args='=>'array|int'],
'array_pad' => ['array', 'array'=>'array', 'length'=>'int', 'value'=>'mixed'],
'array_pop' => ['mixed', '&rw_array'=>'array'],
'array_product' => ['int|float', 'array'=>'array'],
'array_push' => ['int', '&rw_array'=>'array', 'values'=>'mixed', '...vars='=>'mixed'],
'array_rand' => ['int|string|array<int,int>|array<int,string>', 'array'=>'non-empty-array', 'num'=>'int'],
'array_rand\'1' => ['int|string', 'array'=>'array'],
'array_reduce' => ['mixed', 'array'=>'array', 'callback'=>'callable(mixed,mixed):mixed', 'initial='=>'mixed'],
'array_replace' => ['array', 'array'=>'array', 'replacements'=>'array', '...args='=>'array'],
'array_replace_recursive' => ['array', 'array'=>'array', 'replacements'=>'array', '...args='=>'array'],
'array_reverse' => ['array', 'array'=>'array', 'preserve_keys='=>'bool'],
'array_search' => ['int|string|false', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'array_shift' => ['mixed|null', '&rw_array'=>'array'],
'array_slice' => ['array', 'array'=>'array', 'offset'=>'int', 'length='=>'?int', 'preserve_keys='=>'bool'],
'array_splice' => ['array', '&rw_array'=>'array', 'offset'=>'int', 'length='=>'int', 'replacement='=>'array|string'],
'array_sum' => ['int|float', 'array'=>'array'],
'array_udiff' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_assoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_assoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_assoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_assoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_unique' => ['associative-array', 'array'=>'array', 'flags='=>'int'],
'array_unshift' => ['int', '&rw_array'=>'array', 'values'=>'mixed', '...vars='=>'mixed'],
'array_values' => ['list<mixed>', 'array'=>'array'],
'array_walk' => ['bool', '&rw_array'=>'array', 'callback'=>'callable', 'arg='=>'mixed'],
'array_walk_recursive' => ['bool', '&rw_array'=>'array', 'callback'=>'callable', 'arg='=>'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'=>'array', 'flags='=>'int'],
'asin' => ['float', 'num'=>'float'],
'asinh' => ['float', 'num'=>'float'],
'asort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'assert' => ['bool', 'assertion'=>'string|bool|int', 'description='=>'string|Throwable|null'],
'assert_options' => ['mixed|false', 'option'=>'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', 'num'=>'float'],
'atan2' => ['float', 'y'=>'float', 'x'=>'float'],
'atanh' => ['float', 'num'=>'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'BadMethodCallException::getTraceAsString' => ['string'],
'base64_decode' => ['string|false', 'string'=>'string', 'strict='=>'bool'],
'base64_encode' => ['string', 'string'=>'string'],
'base_convert' => ['string', 'num'=>'string', 'from_base'=>'int', 'to_base'=>'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' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bccomp' => ['int', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bcdiv' => ['numeric-string|null', 'dividend'=>'numeric-string', 'divisor'=>'numeric-string', 'scale='=>'int|null'],
'bcmod' => ['numeric-string|null', 'dividend'=>'numeric-string', 'divisor'=>'numeric-string', 'scale='=>'int|null'],
'bcmul' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'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' => ['numeric-string', 'num'=>'numeric-string', 'exponent'=>'numeric-string', 'scale='=>'int|null'],
'bcpowmod' => ['numeric-string|false', 'base'=>'numeric-string', 'exponent'=>'numeric-string', 'modulus'=>'numeric-string', 'scale='=>'int|null'],
'bcscale' => ['int', 'scale='=>'int|null'],
'bcsqrt' => ['numeric-string|null', 'num'=>'numeric-string', 'scale='=>'int|null'],
'bcsub' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bin2hex' => ['string', 'string'=>'string'],
'bind_textdomain_codeset' => ['string', 'domain'=>'string', 'codeset'=>'string'],
'bindec' => ['float|int', 'binary_string'=>'string'],
'bindtextdomain' => ['string', 'domain'=>'string', 'directory'=>'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', 'value'=>'mixed'],
'bson_decode' => ['array', 'bson'=>'string'],
'bson_encode' => ['string', 'anything'=>'mixed'],
'bzclose' => ['bool', 'bz'=>'resource'],
'bzcompress' => ['string|int', 'data'=>'string', 'block_size='=>'int', 'work_factor='=>'int'],
'bzdecompress' => ['string|int', 'data'=>'string', 'use_less_memory='=>'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}', 'julian_day'=>'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', 'callback'=>'callable', '...args='=>'mixed'],
'call_user_func_array' => ['mixed|false', 'callback'=>'callable', 'args'=>'list<mixed>'],
'call_user_method' => ['mixed', 'method_name'=>'string', 'object'=>'object', 'parameter='=>'mixed', '...args='=>'mixed'],
'call_user_method_array' => ['mixed', 'method_name'=>'string', 'object'=>'object', 'params'=>'list<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', 'num'=>'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', 'hostname'=>'string', 'type='=>'string'],
'chgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'chmod' => ['bool', 'filename'=>'string', 'permissions'=>'int'],
'chop' => ['string', 'string'=>'string', 'characters='=>'string'],
'chown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'chr' => ['string', 'codepoint'=>'int'],
'chroot' => ['bool', 'directory'=>'string'],
'chunk_split' => ['string', 'string'=>'string', 'length='=>'int', 'separator='=>'string'],
'class_alias' => ['bool', 'class'=>'string', 'alias'=>'string', 'autoload='=>'bool'],
'class_exists' => ['bool', 'class'=>'string', 'autoload='=>'bool'],
'class_implements' => ['array<string,string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'class_parents' => ['array<string, class-string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'class_uses' => ['array<string,string>|false', 'object_or_class'=>'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', 'title'=>'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' => ['list<array<string,mixed>>'],
'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', 'string1'=>'string', 'string2'=>'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', 'string'=>'string'],
'Collator::getStrength' => ['int|false'],
'Collator::setAttribute' => ['bool', 'attr'=>'int', 'value'=>'int'],
'Collator::setStrength' => ['bool', 'strength'=>'int'],
'Collator::sort' => ['bool', '&rw_arr'=>'array', 'sort_flags='=>'int'],
'Collator::sortWithSortKeys' => ['bool', '&rw_arr'=>'array'],
'collator_asort' => ['bool', 'object'=>'collator', '&rw_array'=>'array', 'flags='=>'int'],
'collator_compare' => ['int', 'object'=>'collator', 'string1'=>'string', 'string2'=>'string'],
'collator_create' => ['Collator', 'locale'=>'string'],
'collator_get_attribute' => ['int|false', 'object'=>'collator', 'attribute'=>'int'],
'collator_get_error_code' => ['int', 'object'=>'collator'],
'collator_get_error_message' => ['string', 'object'=>'collator'],
'collator_get_locale' => ['string', 'object'=>'collator', 'type'=>'int'],
'collator_get_sort_key' => ['string', 'object'=>'collator', 'string'=>'string'],
'collator_get_strength' => ['int|false', 'object'=>'collator'],
'collator_set_attribute' => ['bool', 'object'=>'collator', 'attribute'=>'int', 'value'=>'int'],
'collator_set_strength' => ['bool', 'object'=>'collator', 'strength'=>'int'],
'collator_sort' => ['bool', 'object'=>'collator', '&rw_array'=>'array', 'flags='=>'int'],
'collator_sort_with_sort_keys' => ['bool', 'object'=>'collator', '&rw_array'=>'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', 'variant'=>'VARIANT', 'sink_object'=>'object', 'sink_interface='=>'mixed'],
'com_get_active_object' => ['VARIANT', 'prog_id'=>'string', 'codepage='=>'int'],
'com_isenum' => ['bool', 'com_module'=>'variant'],
'com_load_typelib' => ['bool', 'typelib_name'=>'string', 'case_insensitive='=>'true'],
'com_message_pump' => ['bool', 'timeout_milliseconds='=>'int'],
'com_print_typeinfo' => ['bool', 'variant'=>'object', 'dispatch_interface='=>'string', 'display_sink='=>'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<string, mixed>', 'var_name'=>'string|array', '...var_names='=>'string|array'],
'COMPersistHelper::__construct' => ['void', 'variant'=>'object'],
'COMPersistHelper::GetCurFile' => ['string'],
'COMPersistHelper::GetCurFileName' => ['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', 'name'=>'string'],
'convert_cyr_string' => ['string', 'string'=>'string', 'from'=>'string', 'to'=>'string'],
'convert_uudecode' => ['string', 'string'=>'string'],
'convert_uuencode' => ['string', 'string'=>'string'],
'copy' => ['bool', 'from'=>'string', 'to'=>'string', 'context='=>'resource'],
'cos' => ['float', 'num'=>'float'],
'cosh' => ['float', 'num'=>'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', 'value'=>'Countable|array|SimpleXMLElement|ResourceBundle', 'mode='=>'int'],
'count_chars' => ['array<int,int>|string', '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', 'string'=>'string'],
'crypt' => ['string', 'string'=>'string', 'salt='=>'string'],
'ctype_alnum' => ['bool', 'text'=>'string|int'],
'ctype_alpha' => ['bool', 'text'=>'string|int'],
'ctype_cntrl' => ['bool', 'text'=>'string|int'],
'ctype_digit' => ['bool', 'text'=>'string|int'],
'ctype_graph' => ['bool', 'text'=>'string|int'],
'ctype_lower' => ['bool', 'text'=>'string|int'],
'ctype_print' => ['bool', 'text'=>'string|int'],
'ctype_punct' => ['bool', 'text'=>'string|int'],
'ctype_space' => ['bool', 'text'=>'string|int'],
'ctype_upper' => ['bool', 'text'=>'string|int'],
'ctype_xdigit' => ['bool', 'text'=>'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', 'length'=>'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', 'handle'=>'CurlHandle'],
'curl_copy_handle' => ['CurlHandle', 'handle'=>'CurlHandle'],
'curl_errno' => ['int', 'handle'=>'CurlHandle'],
'curl_error' => ['string', 'handle'=>'CurlHandle'],
'curl_escape' => ['string|false', 'handle'=>'CurlHandle', 'string'=>'string'],
'curl_exec' => ['bool|string', 'handle'=>'CurlHandle'],
'curl_file_create' => ['CURLFile', 'filename'=>'string', 'mime_type='=>'string|null', 'posted_filename='=>'string|null'],
'curl_getinfo' => ['mixed', 'handle'=>'CurlHandle', 'option='=>'int'],
'curl_init' => ['CurlHandle|false', 'url='=>'string'],
'curl_multi_add_handle' => ['int', 'multi_handle'=>'CurlMultiHandle', 'handle'=>'CurlHandle'],
'curl_multi_close' => ['void', 'multi_handle'=>'CurlMultiHandle'],
'curl_multi_errno' => ['int', 'multi_handle'=>'CurlMultiHandle'],
'curl_multi_exec' => ['int', 'multi_handle'=>'CurlMultiHandle', '&w_still_running'=>'int'],
'curl_multi_getcontent' => ['string', 'handle'=>'CurlHandle'],
'curl_multi_info_read' => ['array|false', 'multi_handle'=>'CurlMultiHandle', '&w_queued_messages='=>'int'],
'curl_multi_init' => ['CurlMultiHandle|false'],
'curl_multi_remove_handle' => ['int', 'multi_handle'=>'CurlMultiHandle', 'handle'=>'CurlHandle'],
'curl_multi_select' => ['int', 'multi_handle'=>'CurlMultiHandle', 'timeout='=>'float'],
'curl_multi_setopt' => ['bool', 'multi_handle'=>'CurlMultiHandle', 'option'=>'int', 'value'=>'mixed'],
'curl_multi_strerror' => ['?string', 'error_code'=>'int'],
'curl_pause' => ['int', 'handle'=>'CurlHandle', 'flags'=>'int'],
'curl_reset' => ['void', 'handle'=>'CurlHandle'],
'curl_setopt' => ['bool', 'handle'=>'CurlHandle', 'option'=>'int', 'value'=>'callable|mixed'],
'curl_setopt_array' => ['bool', 'handle'=>'CurlHandle', 'options'=>'array'],
'curl_share_close' => ['void', 'share_handle'=>'CurlShareHandle'],
'curl_share_errno' => ['int', 'share_handle'=>'CurlShareHandle'],
'curl_share_init' => ['CurlShareHandle'],
'curl_share_setopt' => ['bool', 'share_handle'=>'CurlShareHandle', 'option'=>'int', 'value'=>'mixed'],
'curl_share_strerror' => ['?string', 'error_code'=>'int'],
'curl_strerror' => ['?string', 'error_code'=>'int'],
'curl_unescape' => ['string|false', 'handle'=>'CurlShareHandle', 'string'=>'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'=>'array|object'],
'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', 'format'=>'string', 'timestamp='=>'?int'],
'date_add' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_create' => ['DateTime|false', 'datetime='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_from_format' => ['DateTime|false', 'format'=>'string', 'datetime'=>'string', 'timezone='=>'?\DateTimeZone'],
'date_create_immutable' => ['DateTimeImmutable|false', 'datetime='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_immutable_from_format' => ['DateTimeImmutable|false', 'format'=>'string', 'datetime'=>'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', 'timezoneId'=>'string'],
'date_diff' => ['DateInterval|false', 'baseObject'=>'DateTimeInterface', 'targetObject'=>'DateTimeInterface', 'absolute='=>'bool'],
'date_format' => ['string', 'object'=>'DateTimeInterface', 'format'=>'string'],
'date_get_last_errors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'date_interval_create_from_date_string' => ['DateInterval', 'datetime'=>'string'],
'date_interval_format' => ['string', 'object'=>'DateInterval', 'format'=>'string'],
'date_isodate_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'week'=>'int', 'dayOfWeek='=>'int|mixed'],
'date_modify' => ['DateTime|false', 'object'=>'DateTime', 'modifier'=>'string'],
'date_offset_get' => ['int|false', 'object'=>'DateTimeInterface'],
'date_parse' => ['array|false', 'datetime'=>'string'],
'date_parse_from_format' => ['array', 'format'=>'string', 'datetime'=>'string'],
'date_sub' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_sun_info' => ['array|false', 'timestamp'=>'int', 'latitude'=>'float', 'longitude'=>'float'],
'date_sunrise' => ['mixed', 'timestamp'=>'int', 'returnFormat='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'utcOffset='=>'float'],
'date_sunset' => ['mixed', 'timestamp'=>'int', 'returnFormat='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'utcOffset='=>'float'],
'date_time_set' => ['DateTime|false', 'object'=>'', 'hour'=>'', 'minute'=>'', 'second='=>'', 'microsecond='=>''],
'date_timestamp_get' => ['int', 'object'=>'DateTimeInterface'],
'date_timestamp_set' => ['DateTime|false', 'object'=>'DateTime', 'timestamp'=>'int'],
'date_timezone_get' => ['DateTimeZone|false', 'object'=>'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', 'formatter'=>'IntlDateFormatter', 'datetime'=>'DateTime|IntlCalendar|array|int'],
'datefmt_format_object' => ['string|false', 'datetime'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'datefmt_get_calendar' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_calendar_object' => ['IntlCalendar', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_datetype' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_error_code' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_error_message' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_locale' => ['string|false', 'formatter'=>'IntlDateFormatter', 'type='=>'int'],
'datefmt_get_pattern' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_timetype' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_timezone' => ['IntlTimeZone|false'],
'datefmt_get_timezone_id' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_is_lenient' => ['bool', 'formatter'=>'IntlDateFormatter'],
'datefmt_localtime' => ['array|false', 'formatter'=>'IntlDateFormatter', 'string='=>'string', '&rw_offset='=>'int'],
'datefmt_parse' => ['int|false', 'formatter'=>'IntlDateFormatter', 'string='=>'string', '&rw_offset='=>'int'],
'datefmt_set_calendar' => ['bool', 'formatter'=>'IntlDateFormatter', 'calendar'=>'int'],
'datefmt_set_lenient' => ['?bool', 'formatter'=>'IntlDateFormatter', 'lenient'=>'bool'],
'datefmt_set_pattern' => ['bool', 'formatter'=>'IntlDateFormatter', 'pattern'=>'string'],
'datefmt_set_timezone' => ['bool', 'formatter'=>'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', 'object'=>'DateTimeImmutable'],
'DateTime::createFromInterface' => ['self', 'object' => 'DateTimeInterface'],
'DateTime::diff' => ['DateInterval|false', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTime::format' => ['string', 'format'=>'string'],
'DateTime::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'DateTime::getOffset' => ['int'],
'DateTime::getTimestamp' => ['int|false'],
'DateTime::getTimezone' => ['DateTimeZone|false'],
'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::createFromInterface' => ['self', 'object' => 'DateTimeInterface'],
'DateTimeImmutable::createFromMutable' => ['static', 'datetime'=>'DateTime'],
'DateTimeImmutable::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeImmutable::format' => ['string', 'format'=>'string'],
'DateTimeImmutable::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'DateTimeImmutable::getOffset' => ['int'],
'DateTimeImmutable::getTimestamp' => ['int|false'],
'DateTimeImmutable::getTimezone' => ['DateTimeZone|false'],
'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|false'],
'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' => ['list<array{ts: int, time: string, offset: int, isdst: bool, abbr: string}>|false', 'timestamp_begin='=>'int', 'timestamp_end='=>'int'],
'DateTimeZone::listAbbreviations' => ['array<string, list<array{dst: bool, offset: int, timezone_id: string|null}>>|false'],
'DateTimeZone::listIdentifiers' => ['list<string>', 'timezoneGroup='=>'int', 'countryCode='=>'string|null'],
'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', 'dba'=>'resource'],
'dba_delete' => ['bool', 'key'=>'string', 'dba'=>'resource'],
'dba_exists' => ['bool', 'key'=>'string', 'dba'=>'resource'],
'dba_fetch' => ['string|false', 'key'=>'string', 'skip'=>'int', 'dba'=>'resource'],
'dba_fetch\'1' => ['string|false', 'key'=>'string', 'skip'=>'resource'],
'dba_firstkey' => ['string', 'dba'=>'resource'],
'dba_handlers' => ['array', 'full_info='=>'bool'],
'dba_insert' => ['bool', 'key'=>'string', 'value'=>'string', 'dba'=>'resource'],
'dba_key_split' => ['array|false', 'key'=>'string'],
'dba_list' => ['array'],
'dba_nextkey' => ['string', 'dba'=>'resource'],
'dba_open' => ['resource', 'path'=>'string', 'mode'=>'string', 'handler='=>'string', '...handler_params='=>'string'],
'dba_optimize' => ['bool', 'dba'=>'resource'],
'dba_popen' => ['resource', 'path'=>'string', 'mode'=>'string', 'handler='=>'string', '...handler_params='=>'string'],
'dba_replace' => ['bool', 'key'=>'string', 'value'=>'string', 'dba'=>'resource'],
'dba_sync' => ['bool', 'dba'=>'resource'],
'dbase_add_record' => ['bool', 'dbase_identifier'=>'resource', 'record'=>'array'],
'dbase_close' => ['bool', 'dbase_identifier'=>'resource'],
'dbase_create' => ['resource|false', 'filename'=>'string', 'fields'=>'array'],
'dbase_delete_record' => ['bool', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_get_header_info' => ['array', 'dbase_identifier'=>'resource'],
'dbase_get_record' => ['array', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_get_record_with_names' => ['array', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_numfields' => ['int', 'dbase_identifier'=>'resource'],
'dbase_numrecords' => ['int', 'dbase_identifier'=>'resource'],
'dbase_open' => ['resource|false', 'filename'=>'string', 'mode'=>'int'],
'dbase_pack' => ['bool', 'dbase_identifier'=>'resource'],
'dbase_replace_record' => ['bool', 'dbase_identifier'=>'resource', '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'=>'string', 'message'=>'string', 'category'=>'int'],
'dcngettext' => ['string', 'domain'=>'string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int', 'category'=>'int'],
'deaggregate' => ['', 'object'=>'object', 'class_name='=>'string'],
'debug_backtrace' => ['list<array{file:string,line:int,function:string,class?:class-string,object?:object,type?:string,args?:list}>', 'options='=>'int', 'limit='=>'int'],
'debug_print_backtrace' => ['void', 'options='=>'int', 'limit='=>'int'],
'debug_zval_dump' => ['void', '...value'=>'mixed'],
'debugger_connect' => [''],
'debugger_connector_pid' => [''],
'debugger_get_server_start_time' => [''],
'debugger_print' => [''],
'debugger_start_debug' => [''],
'decbin' => ['string', 'num'=>'int'],
'dechex' => ['string', 'num'=>'int'],
'decoct' => ['string', 'num'=>'int'],
'define' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'case_insensitive='=>'bool'],
'define_syslog_variables' => ['void'],
'defined' => ['bool', 'constant_name'=>'string'],
'deflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'deflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'deg2rad' => ['float', 'num'=>'float'],
'dgettext' => ['string', 'domain'=>'string', 'message'=>'string'],
'dio_close' => ['void', 'fd'=>'resource'],
'dio_fcntl' => ['mixed', 'fd'=>'resource', 'cmd'=>'int', 'args='=>'mixed'],
'dio_open' => ['resource|false', 'filename'=>'string', 'flags'=>'int', 'mode='=>'int'],
'dio_read' => ['string', 'fd'=>'resource', 'length='=>'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', 'length='=>'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', 'directory'=>'string'],
'disk_total_space' => ['float|false', 'directory'=>'string'],
'diskfreespace' => ['float|false', 'directory'=>'string'],
'display_disabled_function' => [''],
'dl' => ['bool', 'extension_filename'=>'string'],
'dngettext' => ['string', 'domain'=>'string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int'],
'dns_check_record' => ['bool', 'hostname'=>'string', 'type='=>'string'],
'dns_get_mx' => ['bool', 'hostname'=>'string', '&w_hosts'=>'array', '&w_weights'=>'array'],
'dns_get_record' => ['list<array>|false', 'hostname'=>'string', 'type='=>'int', '&w_authoritative_name_servers='=>'array', '&w_additional_records='=>'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' => ['list<array<string,mixed>>'],
'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|false', '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', 'string'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_version' => ['string'],
'domxml_xmltree' => ['DomDocument', 'string'=>'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', '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', 'datatype_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', 'value'=>'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', 'object'=>'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'],
'easter_date' => ['int', 'year='=>'int'],
'easter_days' => ['int', 'year='=>'int', 'mode='=>'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', 'string'=>'string', 'length='=>'int', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'empty' => ['bool', 'value'=>'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', 'dictionary'=>'resource'],
'enchant_broker_get_dict_path' => ['string', 'broker'=>'resource', 'type'=>'int'],
'enchant_broker_get_error' => ['string|false', 'broker'=>'resource'],
'enchant_broker_init' => ['resource|false'],
'enchant_broker_list_dicts' => ['array<int,array{lang_tag:string,provider_name:string,provider_desc:string,provider_file:string}>|false', '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', 'type'=>'int', 'path'=>'string'],
'enchant_broker_set_ordering' => ['bool', 'broker'=>'resource', 'tag'=>'string', 'ordering'=>'string'],
'enchant_dict_add_to_personal' => ['void', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_add_to_session' => ['void', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_check' => ['bool', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_describe' => ['array', 'dictionary'=>'resource'],
'enchant_dict_get_error' => ['string', 'dictionary'=>'resource'],
'enchant_dict_is_in_session' => ['bool', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_quick_check' => ['bool', 'dictionary'=>'resource', 'word'=>'string', '&w_suggestions='=>'array<int,string>'],
'enchant_dict_store_replacement' => ['void', 'dictionary'=>'resource', 'misspelled'=>'string', 'correct'=>'string'],
'enchant_dict_suggest' => ['array', 'dictionary'=>'resource', 'word'=>'string'],
'end' => ['mixed|false', '&r_array'=>'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' => ['list<array<string,mixed>>'],
'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', 'additional_headers='=>'string'],
'error_reporting' => ['int', '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' => ['list<array<string,mixed>>'],
'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', 'length'=>'int'],
'EventBuffer::copyout' => ['int', '&w_data'=>'string', 'max_bytes'=>'int'],
'EventBuffer::drain' => ['bool', 'length'=>'int'],
'EventBuffer::enableLocking' => ['void'],
'EventBuffer::expand' => ['bool', 'length'=>'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' => ['list<array<string,mixed>>'],
'Exception::getTraceAsString' => ['string'],
'exec' => ['string|false', 'command'=>'string', '&w_output='=>'array', '&w_result_code='=>'int'],
'exif_imagetype' => ['int|false', 'filename'=>'string'],
'exif_read_data' => ['array|false', 'file'=>'string|resource', 'required_sections='=>'string', 'as_arrays='=>'bool', 'read_thumbnail='=>'bool'],
'exif_tagname' => ['string|false', 'index'=>'int'],
'exif_thumbnail' => ['string|false', 'file'=>'string', '&w_width='=>'int', '&w_height='=>'int', '&w_image_type='=>'int'],
'exit' => ['', 'status'=>'string|int'],
'exp' => ['float', 'num'=>'float'],
'expect_expectl' => ['int', 'expect'=>'resource', 'cases'=>'array', 'match='=>'array'],
'expect_popen' => ['resource|false', 'command'=>'string'],
'explode' => ['list<string>', 'separator'=>'string', 'string'=>'string', 'limit='=>'int'],
'expm1' => ['float', 'num'=>'float'],
'extension_loaded' => ['bool', 'extension'=>'string'],
'extract' => ['int', '&rw_array'=>'array', 'flags='=>'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|false', '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', 'stream'=>'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|false', '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', 'string1'=>'string', 'string2'=>'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'],
'fdiv' => ['float', 'num1'=>'float', 'num2'=>'float'],
'feof' => ['bool', 'stream'=>'resource'],
'fflush' => ['bool', 'stream'=>'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', 'stream'=>'resource'],
'fgetcsv' => ['list<string>|array{0: null}|false|null', 'stream'=>'resource', 'length='=>'int', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fgets' => ['string|false', 'stream'=>'resource', 'length='=>'int'],
'fgetss' => ['string|false', 'fp'=>'resource', 'length='=>'int', 'allowable_tags='=>'string'],
'file' => ['list<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', 'length='=>'int'],
'file_put_contents' => ['int|false', 'filename'=>'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', 'input_type'=>'int', 'var_name'=>'string'],
'filter_id' => ['int|false', 'name'=>'string'],
'filter_input' => ['mixed|false', 'type'=>'int', 'var_name'=>'string', 'filter='=>'int', 'options='=>'array|int'],
'filter_input_array' => ['mixed|false', 'type'=>'int', 'options='=>'int|array', 'add_empty='=>'bool'],
'filter_list' => ['array'],
'filter_var' => ['mixed|false', 'value'=>'mixed', 'filter='=>'int', 'options='=>'mixed'],
'filter_var_array' => ['mixed|false', 'array'=>'array', 'options='=>'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::finfo' => ['void', 'options='=>'int', 'magic_file='=>'string'],
'finfo::set_flags' => ['bool', 'options'=>'int'],
'finfo_buffer' => ['string|false', 'finfo'=>'resource', 'string'=>'string', 'flags='=>'int', 'context='=>'resource'],
'finfo_close' => ['bool', 'finfo'=>'resource'],
'finfo_file' => ['string|false', 'finfo'=>'resource', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'finfo_open' => ['resource|false', 'flags='=>'int', 'magic_database='=>'string'],
'finfo_set_flags' => ['bool', 'finfo'=>'resource', 'flags'=>'int'],
'floatval' => ['float', 'value'=>'mixed'],
'flock' => ['bool', 'stream'=>'resource', 'operation'=>'int', '&w_would_block='=>'int'],
'floor' => ['float', 'num'=>'float'],
'flush' => ['void'],
'fmod' => ['float', 'num1'=>'float', 'num2'=>'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', 'callback'=>'callable', '...args='=>'mixed'],
'forward_static_call_array' => ['mixed|false', 'callback'=>'callable', 'args'=>'list<mixed>'],
'fpassthru' => ['int|false', 'stream'=>'resource'],
'fpm_get_status' => ['array|false'],
'fprintf' => ['int', 'stream'=>'resource', 'format'=>'string', '...values='=>'string|int|float'],
'fputcsv' => ['int|false', 'stream'=>'resource', 'fields'=>'array<array-key, null|scalar|Stringable>', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fputs' => ['int|false', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'fread' => ['string|false', 'stream'=>'resource', 'length'=>'int'],
'frenchtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'fribidi_log2vis' => ['string', 'string'=>'string', 'direction'=>'string', 'charset'=>'int'],
'fscanf' => ['list<mixed>', 'stream'=>'resource', 'format'=>'string'],
'fscanf\'1' => ['int', 'stream'=>'resource', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'fseek' => ['int', 'stream'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'fsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float'],
'fstat' => ['array|false', 'stream'=>'resource'],
'ftell' => ['int|false', 'stream'=>'resource'],
'ftok' => ['int', 'filename'=>'string', 'project_id'=>'string'],
'ftp_alloc' => ['bool', 'ftp'=>'resource', 'size'=>'int', '&w_response='=>'string'],
'ftp_append' => ['bool', 'ftp'=>'resource', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int'],
'ftp_cdup' => ['bool', 'ftp'=>'resource'],
'ftp_chdir' => ['bool', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_chmod' => ['int|false', 'ftp'=>'resource', 'permissions'=>'int', 'filename'=>'string'],
'ftp_close' => ['bool', 'ftp'=>'resource'],
'ftp_connect' => ['resource|false', 'hostname'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_delete' => ['bool', 'ftp'=>'resource', 'filename'=>'string'],
'ftp_exec' => ['bool', 'ftp'=>'resource', 'command'=>'string'],
'ftp_fget' => ['bool', 'ftp'=>'resource', 'stream'=>'resource', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_fput' => ['bool', 'ftp'=>'resource', 'remote_filename'=>'string', 'stream'=>'resource', 'mode='=>'int', 'offset='=>'int'],
'ftp_get' => ['bool', 'ftp'=>'resource', 'local_filename'=>'string', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_get_option' => ['mixed|false', 'ftp'=>'resource', 'option'=>'int'],
'ftp_login' => ['bool', 'ftp'=>'resource', 'username'=>'string', 'password'=>'string'],
'ftp_mdtm' => ['int', 'ftp'=>'resource', 'filename'=>'string'],
'ftp_mkdir' => ['string|false', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_mlsd' => ['array|false', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_nb_continue' => ['int', 'ftp'=>'resource'],
'ftp_nb_fget' => ['int', 'ftp'=>'resource', 'stream'=>'resource', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_fput' => ['int', 'ftp'=>'resource', 'remote_filename'=>'string', 'stream'=>'resource', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_get' => ['int', 'ftp'=>'resource', 'local_filename'=>'string', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_put' => ['int', 'ftp'=>'resource', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nlist' => ['array|false', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_pasv' => ['bool', 'ftp'=>'resource', 'enable'=>'bool'],
'ftp_put' => ['bool', 'ftp'=>'resource', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_pwd' => ['string|false', 'ftp'=>'resource'],
'ftp_quit' => ['bool', 'ftp'=>'resource'],
'ftp_raw' => ['array', 'ftp'=>'resource', 'command'=>'string'],
'ftp_rawlist' => ['array|false', 'ftp'=>'resource', 'directory'=>'string', 'recursive='=>'bool'],
'ftp_rename' => ['bool', 'ftp'=>'resource', 'from'=>'string', 'to'=>'string'],
'ftp_rmdir' => ['bool', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_set_option' => ['bool', 'ftp'=>'resource', 'option'=>'int', 'value'=>'mixed'],
'ftp_site' => ['bool', 'ftp'=>'resource', 'command'=>'string'],
'ftp_size' => ['int', 'ftp'=>'resource', 'filename'=>'string'],
'ftp_ssl_connect' => ['resource|false', 'hostname'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_systype' => ['string|false', 'ftp'=>'resource'],
'ftruncate' => ['bool', 'stream'=>'resource', 'size'=>'int'],
'func_get_arg' => ['mixed|false', 'position'=>'int'],
'func_get_args' => ['list<mixed>'],
'func_num_args' => ['int'],
'function_exists' => ['bool', 'function'=>'string'],
'fwrite' => ['int|false', 'stream'=>'resource', 'data'=>'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'],
'GEOSGeometry::__toString' => ['string'],
'GEOSGeometry::project' => ['float', 'other'=>'GEOSGeometry', 'normalized'=>'bool'],
'GEOSGeometry::interpolate' => ['GEOSGeometry', 'dist'=>'float', 'normalized'=>'bool'],
'GEOSGeometry::buffer' => ['GEOSGeometry', 'dist'=>'float', 'styleArray'=>'array'],
'GEOSGeometry::offsetCurve' => ['GEOSGeometry', 'dist'=>'float', 'styleArray'=>'array'],
'GEOSGeometry::envelope' => ['GEOSGeometry'],
'GEOSGeometry::intersection' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::convexHull' => ['GEOSGeometry'],
'GEOSGeometry::difference' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::symDifference' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::boundary' => ['GEOSGeometry'],
'GEOSGeometry::union' => ['GEOSGeometry', 'otherGeom='=>'GEOSGeometry'],
'GEOSGeometry::pointOnSurface' => ['GEOSGeometry'],
'GEOSGeometry::centroid' => ['GEOSGeometry'],
'GEOSGeometry::relate' => ['string|bool', 'otherGeom'=>'GEOSGeometry', 'pattern'=>'string'],
'GEOSGeometry::relateBoundaryNodeRule' => ['string', 'otherGeom'=>'GEOSGeometry', 'rule'=>'int'],
'GEOSGeometry::simplify' => ['GEOSGeometry', 'tolerance'=>'float', 'preserveTopology'=>'bool'],
'GEOSGeometry::normalize' => ['GEOSGeometry'],
'GEOSGeometry::extractUniquePoints' => ['GEOSGeometry'],
'GEOSGeometry::disjoint' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::touches' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::intersects' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::crosses' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::within' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::contains' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::overlaps' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::covers' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::coveredBy' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::equals' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::equalsExact' => ['bool', 'geom'=>'GEOSGeometry', 'tolerance'=>'float'],
'GEOSGeometry::isEmpty' => ['bool'],
'GEOSGeometry::checkValidity' => ['array{valid: bool, reason?: string, location?: GEOSGeometry}'],
'GEOSGeometry::isSimple' => ['bool'],
'GEOSGeometry::isRing' => ['bool'],
'GEOSGeometry::hasZ' => ['bool'],
'GEOSGeometry::isClosed' => ['bool'],
'GEOSGeometry::typeName' => ['string'],
'GEOSGeometry::typeId' => ['int'],
'GEOSGeometry::getSRID' => ['int'],
'GEOSGeometry::setSRID' => ['void', 'srid'=>'int'],
'GEOSGeometry::numGeometries' => ['int'],
'GEOSGeometry::geometryN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::numInteriorRings' => ['int'],
'GEOSGeometry::numPoints' => ['int'],
'GEOSGeometry::getX' => ['float'],
'GEOSGeometry::getY' => ['float'],
'GEOSGeometry::interiorRingN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::exteriorRing' => ['GEOSGeometry'],
'GEOSGeometry::numCoordinates' => ['int'],
'GEOSGeometry::dimension' => ['int'],
'GEOSGeometry::coordinateDimension' => ['int'],
'GEOSGeometry::pointN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::startPoint' => ['GEOSGeometry'],
'GEOSGeometry::endPoint' => ['GEOSGeometry'],
'GEOSGeometry::area' => ['float'],
'GEOSGeometry::length' => ['float'],
'GEOSGeometry::distance' => ['float', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::hausdorffDistance' => ['float', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::snapTo' => ['GEOSGeometry', 'geom'=>'GEOSGeometry', 'tolerance'=>'float'],
'GEOSGeometry::node' => ['GEOSGeometry'],
'GEOSGeometry::delaunayTriangulation' => ['GEOSGeometry', 'tolerance'=>'float', 'onlyEdges'=>'bool'],
'GEOSGeometry::voronoiDiagram' => ['GEOSGeometry', 'tolerance'=>'float', 'onlyEdges'=>'bool', 'extent'=>'GEOSGeometry|null'],
'GEOSLineMerge' => ['array', 'geom'=>'GEOSGeometry'],
'GEOSPolygonize' => ['array{rings: GEOSGeometry[], cut_edges?: GEOSGeometry[], dangles: GEOSGeometry[], invalid_rings: GEOSGeometry[]}', 'geom'=>'GEOSGeometry'],
'GEOSRelateMatch' => ['bool', 'matrix'=>'string', 'pattern'=>'string'],
'GEOSSharedPaths' => ['GEOSGeometry', 'geom1'=>'GEOSGeometry', 'geom2'=>'GEOSGeometry'],
'GEOSVersion' => ['string'],
'GEOSWKBReader::__construct' => ['void'],
'GEOSWKBReader::read' => ['GEOSGeometry', 'wkb'=>'string'],
'GEOSWKBReader::readHEX' => ['GEOSGeometry', 'wkb'=>'string'],
'GEOSWKBWriter::__construct' => ['void'],
'GEOSWKBWriter::getOutputDimension' => ['int'],
'GEOSWKBWriter::setOutputDimension' => ['void', 'dim'=>'int'],
'GEOSWKBWriter::getByteOrder' => ['int'],
'GEOSWKBWriter::setByteOrder' => ['void', 'byteOrder'=>'int'],
'GEOSWKBWriter::getIncludeSRID' => ['bool'],
'GEOSWKBWriter::setIncludeSRID' => ['void', 'inc'=>'bool'],
'GEOSWKBWriter::write' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKBWriter::writeHEX' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKTReader::__construct' => ['void'],
'GEOSWKTReader::read' => ['GEOSGeometry', 'wkt'=>'string'],
'GEOSWKTWriter::__construct' => ['void'],
'GEOSWKTWriter::write' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKTWriter::setTrim' => ['void', 'trim'=>'bool'],
'GEOSWKTWriter::setRoundingPrecision' => ['void', 'prec'=>'int'],
'GEOSWKTWriter::setOutputDimension' => ['void', 'dim'=>'int'],
'GEOSWKTWriter::getOutputDimension' => ['int'],
'GEOSWKTWriter::setOld3D' => ['void', 'val'=>'bool'],
'get_browser' => ['array|object|false', 'user_agent='=>'string', 'return_array='=>'bool'],
'get_call_stack' => [''],
'get_called_class' => ['class-string'],
'get_cfg_var' => ['string|false', 'option'=>'string'],
'get_class' => ['class-string|false', 'object='=>'object'],
'get_class_methods' => ['list<string>|null', 'object_or_class'=>'mixed'],
'get_class_vars' => ['array<string,mixed>', 'class'=>'string'],
'get_current_user' => ['string'],
'get_debug_type' => ['string', 'value'=>'mixed'],
'get_declared_classes' => ['list<class-string>'],
'get_declared_interfaces' => ['list<class-string>'],
'get_declared_traits' => ['list<class-string>|null'],
'get_defined_constants' => ['array<string,int|string|float|bool|null|array|resource>', 'categorize='=>'bool'],
'get_defined_functions' => ['array<string,list<callable-string>>', 'exclude_disabled='=>'bool'],
'get_defined_vars' => ['array'],
'get_extension_funcs' => ['list<callable-string>|false', 'extension'=>'string'],
'get_headers' => ['array|false', 'url'=>'string', 'associative='=>'int', 'context='=>'resource'],
'get_html_translation_table' => ['array', 'table='=>'int', 'flags='=>'int', 'encoding='=>'string'],
'get_include_path' => ['string'],
'get_included_files' => ['list<string>'],
'get_loaded_extensions' => ['list<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>', 'object'=>'object'],
'get_parent_class' => ['class-string|false', 'object_or_class='=>'mixed'],
'get_required_files' => ['list<string>'],
'get_resource_id' => ['int', 'resource'=>'resource'],
'get_resource_type' => ['string', 'resource'=>'resource'],
'get_resources' => ['array<int,resource>', 'type='=>'string'],
'getallheaders' => ['array|false'],
'getcwd' => ['string|false'],
'getdate' => ['array', 'timestamp='=>'int'],
'getenv' => ['string|false', 'name'=>'string', 'local_only='=>'bool'],
'getenv\'1' => ['array<string,string>'],
'gethostbyaddr' => ['string|false', 'ip'=>'string'],
'gethostbyname' => ['string', 'hostname'=>'string'],
'gethostbynamel' => ['list<string>|false', 'hostname'=>'string'],
'gethostname' => ['string|false'],
'getimagesize' => ['array|false', 'filename'=>'string', '&w_image_info='=>'array'],
'getimagesizefromstring' => ['array|false', 'string'=>'string', '&w_image_info='=>'array'],
'getlastmod' => ['int|false'],
'getmxrr' => ['bool', 'hostname'=>'string', '&w_hosts'=>'array', '&w_weights='=>'array'],
'getmygid' => ['int|false'],
'getmyinode' => ['int|false'],
'getmypid' => ['int|false'],
'getmyuid' => ['int|false'],
'getopt' => ['array<string,string>|array<string,false>|array<string,list<mixed>>|false', 'short_options'=>'string', 'long_options='=>'array', '&w_rest_index='=>'int'],
'getprotobyname' => ['int|false', 'protocol'=>'string'],
'getprotobynumber' => ['string', 'protocol'=>'int'],
'getrandmax' => ['int'],
'getrusage' => ['array', 'mode='=>'int'],
'getservbyname' => ['int|false', 'service'=>'string', 'protocol'=>'string'],
'getservbyport' => ['string|false', 'port'=>'int', 'protocol'=>'string'],
'gettext' => ['string', 'message'=>'string'],
'gettimeofday' => ['array<string, int>'],
'gettimeofday\'1' => ['float', 'as_float='=>'true'],
'gettype' => ['string', 'value'=>'mixed'],
'glob' => ['list<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', 'format'=>'string', 'timestamp='=>'int|null'],
'gmmktime' => ['int|false', 'hour'=>'int', 'minute='=>'int|null', 'second='=>'int|null', 'month='=>'int|null', 'day='=>'int|null', 'year='=>'int|null'],
'GMP::__construct' => ['void'],
'GMP::__toString' => ['numeric-string'],
'GMP::serialize' => ['string'],
'GMP::unserialize' => ['void', 'serialized'=>'string'],
'gmp_abs' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_add' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_and' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_binomial' => ['GMP', 'n'=>'GMP|string|int', 'k'=>'int'],
'gmp_clrbit' => ['void', 'num'=>'GMP|string|int', 'index'=>'int'],
'gmp_cmp' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_com' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_div' => ['GMP', 'num1'=>'GMP|resource|string', 'num2'=>'GMP|resource|string', 'rounding_mode='=>'int'],
'gmp_div_q' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_div_qr' => ['array{0: GMP, 1: GMP}', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_div_r' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_divexact' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_export' => ['string|false', 'num'=>'GMP|string|int', 'word_size='=>'int', 'flags='=>'int'],
'gmp_fact' => ['GMP', 'num'=>'int'],
'gmp_gcd' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_gcdext' => ['array<string,GMP>', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_hamdist' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_import' => ['GMP|false', 'data'=>'string', 'word_size='=>'int', 'flags='=>'int'],
'gmp_init' => ['GMP', 'num'=>'int|string', 'base='=>'int'],
'gmp_intval' => ['int', 'num'=>'GMP|string|int'],
'gmp_invert' => ['GMP|false', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_jacobi' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_kronecker' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_lcm' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_legendre' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_mod' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_mul' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_neg' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_nextprime' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_or' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_perfect_power' => ['bool', 'num'=>'GMP|string|int'],
'gmp_perfect_square' => ['bool', 'num'=>'GMP|string|int'],
'gmp_popcount' => ['int', 'num'=>'GMP|string|int'],
'gmp_pow' => ['GMP', 'num'=>'GMP|string|int', 'exponent'=>'int'],
'gmp_powm' => ['GMP', 'num'=>'GMP|string|int', 'exponent'=>'GMP|string|int', 'modulus'=>'GMP|string|int'],
'gmp_prob_prime' => ['int', 'num'=>'GMP|string|int', 'repetitions='=>'int'],
'gmp_random_bits' => ['GMP', 'bits'=>'int'],
'gmp_random_range' => ['GMP', 'min'=>'GMP|string|int', 'max'=>'GMP|string|int'],
'gmp_random_seed' => ['void', 'seed'=>'GMP|string|int'],
'gmp_root' => ['GMP', 'num'=>'GMP|string|int', 'nth'=>'int'],
'gmp_rootrem' => ['array{0: GMP, 1: GMP}', 'num'=>'GMP|string|int', 'nth'=>'int'],
'gmp_scan0' => ['int', 'num1'=>'GMP|string|int', 'start'=>'int'],
'gmp_scan1' => ['int', 'num1'=>'GMP|string|int', 'start'=>'int'],
'gmp_setbit' => ['void', 'num'=>'GMP|string|int', 'index'=>'int', 'value='=>'bool'],
'gmp_sign' => ['int', 'num'=>'GMP|string|int'],
'gmp_sqrt' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_sqrtrem' => ['array{0: GMP, 1: GMP}', 'num'=>'GMP|string|int'],
'gmp_strval' => ['numeric-string', 'num'=>'GMP|string|int', 'base='=>'int'],
'gmp_sub' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_testbit' => ['bool', 'num'=>'GMP|string|int', 'index'=>'int'],
'gmp_xor' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'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', 'haystack'=>'string', 'size'=>'int', 'type='=>'int', 'offset='=>'int', '&w_next='=>'int'],
'grapheme_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'beforeNeedle='=>'bool'],
'grapheme_strlen' => ['int|false|null', 'string'=>'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', 'beforeNeedle='=>'bool'],
'grapheme_substr' => ['string|false', 'string'=>'string', 'offset'=>'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', 'stream'=>'resource'],
'gzcompress' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzdecode' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzdeflate' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzencode' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzeof' => ['bool|int', 'stream'=>'resource'],
'gzfile' => ['list<string>', 'filename'=>'string', 'use_include_path='=>'int'],
'gzgetc' => ['string|false', 'stream'=>'resource'],
'gzgets' => ['string|false', 'stream'=>'resource', 'length='=>'int'],
'gzinflate' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'int'],
'gzpassthru' => ['int|false', 'stream'=>'resource'],
'gzputs' => ['int', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'gzread' => ['string|false', 'stream'=>'resource', 'length'=>'int'],
'gzrewind' => ['bool', 'stream'=>'resource'],
'gzseek' => ['int', 'stream'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'gztell' => ['int|false', 'stream'=>'resource'],
'gzuncompress' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzwrite' => ['int', 'stream'=>'resource', 'data'=>'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|false', 'algo'=>'string', 'data'=>'string', 'binary='=>'bool'],
'hash_algos' => ['list<string>'],
'hash_copy' => ['HashContext', 'context'=>'HashContext'],
'hash_equals' => ['bool', 'known_string'=>'string', 'user_string'=>'string'],
'hash_file' => ['string|false', 'algo'=>'string', 'filename'=>'string', 'binary='=>'bool'],
'hash_final' => ['string', 'context'=>'HashContext', 'binary='=>'bool'],
'hash_hkdf' => ['string|false', 'algo'=>'string', 'key'=>'string', 'length='=>'int', 'info='=>'string', 'salt='=>'string'],
'hash_hmac' => ['string|false', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'binary='=>'bool'],
'hash_hmac_algos' => ['list<string>'],
'hash_hmac_file' => ['string|false', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'binary='=>'bool'],
'hash_init' => ['HashContext', 'algo'=>'string', 'flags='=>'int', 'key='=>'string'],
'hash_pbkdf2' => ['string', 'algo'=>'string', 'password'=>'string', 'salt'=>'string', 'iterations'=>'int', 'length='=>'int', 'binary='=>'bool'],
'hash_update' => ['bool', 'context'=>'HashContext', 'data'=>'string'],
'hash_update_file' => ['bool', 'context'=>'HashContext', 'filename'=>'string', 'stream_context='=>'?resource'],
'hash_update_stream' => ['int', 'context'=>'HashContext', 'stream'=>'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', 'response_code='=>'int'],
'header_register_callback' => ['bool', 'callback'=>'callable():void'],
'header_remove' => ['void', 'name='=>'string'],
'headers_list' => ['list<string>'],
'headers_sent' => ['bool', '&w_filename='=>'string', '&w_line='=>'int'],
'hebrev' => ['string', 'string'=>'string', 'max_chars_per_line='=>'int'],
'hebrevc' => ['string', 'string'=>'string', 'max_chars_per_line='=>'int'],
'hex2bin' => ['string|false', 'string'=>'string'],
'hexdec' => ['int|float', 'hex_string'=>'string'],
'highlight_file' => ['string|bool', 'filename'=>'string', 'return='=>'bool'],
'highlight_string' => ['string|bool', 'string'=>'string', 'return='=>'bool'],
'hrtime' => ['array{0:int,1:int}|false', 'as_number='=>'false'],
'hrtime\'1' => ['int|float|false', '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', 'flags='=>'int', 'encoding='=>'string'],
'htmlentities' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string', 'double_encode='=>'bool'],
'htmlspecialchars' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string|null', 'double_encode='=>'bool'],
'htmlspecialchars_decode' => ['string', 'string'=>'string', 'flags='=>'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', 'data'=>'array|object', 'numeric_prefix='=>'string', 'arg_separator='=>'string', 'encoding_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', 'length'=>'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', 'x'=>'float', 'y'=>'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', 'length'=>'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|false', 'link_identifier'=>'', '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', 'from_encoding'=>'string', 'to_encoding'=>'string', 'string'=>'string'],
'iconv_get_encoding' => ['mixed', 'type='=>'string'],
'iconv_mime_decode' => ['string|false', 'string'=>'string', 'mode='=>'int', 'encoding='=>'string'],
'iconv_mime_decode_headers' => ['array|false', 'headers'=>'string', 'mode='=>'int', 'encoding='=>'string'],
'iconv_mime_encode' => ['string|false', 'field_name'=>'string', 'field_value'=>'string', 'options='=>'array'],
'iconv_set_encoding' => ['bool', 'type'=>'string', 'encoding'=>'string'],
'iconv_strlen' => ['int|false', 'string'=>'string', 'encoding='=>'string'],
'iconv_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'iconv_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string'],
'iconv_substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int', 'encoding='=>'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', 'flags='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'idn_to_utf8' => ['string|false', 'domain'=>'string', 'flags='=>'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', 'string'=>'string'],
'ignore_user_abort' => ['int', 'enable='=>'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'],
'image_type_to_extension' => ['string', 'image_type'=>'int', 'include_dot='=>'bool'],
'image_type_to_mime_type' => ['string', 'image_type'=>'int'],
'imageaffine' => ['false|GdImage', 'image'=>'GdImage', 'affine'=>'array', 'clip='=>'?array'],
'imageaffinematrixconcat' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'matrix1'=>'array', 'matrix2'=>'array'],
'imageaffinematrixget' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'type'=>'int', 'options'=>'array|float'],
'imagealphablending' => ['bool', 'image'=>'GdImage', 'enable'=>'bool'],
'imageantialias' => ['bool', 'image'=>'GdImage', 'enable'=>'bool'],
'imagearc' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'start_angle'=>'int', 'end_angle'=>'int', 'color'=>'int'],
'imagebmp' => ['bool', 'image'=>'GdImage', 'file='=>'resource|string|null', 'compressed='=>'bool'],
'imagechar' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'char'=>'string', 'color'=>'int'],
'imagecharup' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'char'=>'string', 'color'=>'int'],
'imagecolorallocate' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorallocatealpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorat' => ['int|false', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int'],
'imagecolorclosest' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorclosestalpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorclosesthwb' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolordeallocate' => ['bool', 'image'=>'GdImage', 'color'=>'int'],
'imagecolorexact' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorexactalpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolormatch' => ['bool', 'image1'=>'GdImage', 'image2'=>'GdImage'],
'imagecolorresolve' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorresolvealpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorset' => ['void', 'image'=>'GdImage', 'color'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'imagecolorsforindex' => ['array|false', 'image'=>'GdImage', 'color'=>'int'],
'imagecolorstotal' => ['int|false', 'image'=>'GdImage'],
'imagecolortransparent' => ['int|false', 'image'=>'GdImage', 'color='=>'int'],
'imageconvolution' => ['bool', 'image'=>'GdImage', 'matrix'=>'array', 'divisor'=>'float', 'offset'=>'float'],
'imagecopy' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecopymerge' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int', 'pct'=>'int'],
'imagecopymergegray' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int', 'pct'=>'int'],
'imagecopyresampled' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_width'=>'int', 'dst_height'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecopyresized' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_width'=>'int', 'dst_height'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecreate' => ['false|GdImage', 'width'=>'int', 'height'=>'int'],
'imagecreatefrombmp' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromgd' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromgd2' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromgd2part' => ['false|GdImage', 'filename'=>'string', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int'],
'imagecreatefromgif' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromjpeg' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefrompng' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromstring' => ['false|GdImage', 'data'=>'string'],
'imagecreatefromwbmp' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromwebp' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromxbm' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromxpm' => ['false|GdImage', 'filename'=>'string'],
'imagecreatetruecolor' => ['false|GdImage', 'width'=>'int', 'height'=>'int'],
'imagecrop' => ['false|GdImage', 'image'=>'GdImage', 'rectangle'=>'array'],
'imagecropauto' => ['false|GdImage', 'image'=>'GdImage', 'mode'=>'int', 'threshold'=>'float', 'color'=>'int'],
'imagedashedline' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imagedestroy' => ['bool', 'image'=>'GdImage'],
'imageellipse' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'color'=>'int'],
'imagefill' => ['bool', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int', 'color'=>'int'],
'imagefilledarc' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'start_angle'=>'int', 'end_angle'=>'int', 'color'=>'int', 'style'=>'int'],
'imagefilledellipse' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'color'=>'int'],
'imagefilledpolygon' => ['bool', 'image'=>'GdImage', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagefilledrectangle' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imagefilltoborder' => ['bool', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int', 'border_color'=>'int', 'color'=>'int'],
'imagefilter' => ['bool', 'image'=>'GdImage', 'filter'=>'int', 'args='=>'int', 'arg2='=>'int', 'arg3='=>'int', 'arg4='=>'int'],
'imageflip' => ['bool', 'image'=>'GdImage', 'mode'=>'int'],
'imagefontheight' => ['int', 'font'=>'int'],
'imagefontwidth' => ['int', 'font'=>'int'],
'imageftbbox' => ['array|false', 'size'=>'float', 'angle'=>'float', 'font_filename'=>'string', 'string'=>'string', 'options='=>'array'],
'imagefttext' => ['array|false', 'image'=>'GdImage', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'color'=>'int', 'font_filename'=>'string', 'text'=>'string', 'options='=>'array'],
'imagegammacorrect' => ['bool', 'image'=>'GdImage', 'input_gamma'=>'float', 'output_gamma'=>'float'],
'imagegd' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null'],
'imagegd2' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'chunk_size='=>'int', 'mode='=>'int'],
'imagegetclip' => ['array<int,int>', 'image'=>'GdImage'],
'imagegetinterpolation' => ['int', 'image'=>'GdImage'],
'imagegif' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null'],
'imagegrabscreen' => ['false|GdImage'],
'imagegrabwindow' => ['false|GdImage', 'handle'=>'int', 'client_area='=>'int'],
'imageinterlace' => ['int|false', 'image'=>'GdImage', 'enable='=>'int'],
'imageistruecolor' => ['bool', 'image'=>'GdImage'],
'imagejpeg' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'quality='=>'int'],
'imagelayereffect' => ['bool', 'image'=>'GdImage', 'effect'=>'int'],
'imageline' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'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'=>'GdImage', 'points'=>'array', 'num_points'=>'int', 'color'=>'int'],
'imagepalettecopy' => ['void', 'dst'=>'GdImage', 'src'=>'GdImage'],
'imagepalettetotruecolor' => ['bool', 'image'=>'GdImage'],
'imagepng' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'quality='=>'int', 'filters='=>'int'],
'imagepolygon' => ['bool', 'image'=>'GdImage', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagerectangle' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imageresolution' => ['array|bool', 'image'=>'GdImage', 'resolution_x='=>'int', 'resolution_y='=>'int'],
'imagerotate' => ['false|GdImage', 'image'=>'GdImage', 'angle'=>'float', 'background_color'=>'int', 'ignore_transparent='=>'int'],
'imagesavealpha' => ['bool', 'image'=>'GdImage', 'enable'=>'bool'],
'imagescale' => ['false|GdImage', 'image'=>'GdImage', 'width'=>'int', 'height='=>'int', 'mode='=>'int'],
'imagesetbrush' => ['bool', 'image'=>'GdImage', 'brush'=>'GdImage'],
'imagesetclip' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'x2'=>'int', 'y1'=>'int', 'y2'=>'int'],
'imagesetinterpolation' => ['bool', 'image'=>'GdImage', 'method'=>'int'],
'imagesetpixel' => ['bool', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int', 'color'=>'int'],
'imagesetstyle' => ['bool', 'image'=>'GdImage', 'style'=>'non-empty-array'],
'imagesetthickness' => ['bool', 'image'=>'GdImage', 'thickness'=>'int'],
'imagesettile' => ['bool', 'image'=>'GdImage', 'tile'=>'GdImage'],
'imagestring' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'string'=>'string', 'color'=>'int'],
'imagestringup' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'string'=>'string', 'color'=>'int'],
'imagesx' => ['int|false', 'image'=>'GdImage'],
'imagesy' => ['int|false', 'image'=>'GdImage'],
'imagetruecolortopalette' => ['bool', 'image'=>'GdImage', 'dither'=>'bool', 'num_colors'=>'int'],
'imagettfbbox' => ['false|array', 'size'=>'float', 'angle'=>'float', 'font_filename'=>'string', 'string'=>'string'],
'imagettftext' => ['false|array', 'image'=>'GdImage', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'color'=>'int', 'font_filename'=>'string', 'text'=>'string'],
'imagetypes' => ['int'],
'imagewbmp' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'foreground_color='=>'int'],
'imagewebp' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'quality='=>'int'],
'imagexbm' => ['bool', 'image'=>'GdImage', 'filename='=>'?string', 'foreground_color='=>'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{Imagick, float}', 'image'=>'Imagick', 'channeltype'=>'int', 'metrictype'=>'int'],
'Imagick::compareImageLayers' => ['Imagick', 'method'=>'int'],
'Imagick::compareImages' => ['array{Imagick, float}', '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', 'legacy='=>'bool'],
'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' => ['list<int>', '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{x:float, y:float}'],
'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{minima:int, maxima:int}', 'channel'=>'int'],
'Imagick::getImageChannelKurtosis' => ['array{kurtosis:float, skewness:float}', 'channel='=>'int'],
'Imagick::getImageChannelMean' => ['array{mean:float, standardDeviation:float}', 'channel'=>'int'],
'Imagick::getImageChannelRange' => ['array{minima:float, maxima:float}', 'channel'=>'int'],
'Imagick::getImageChannelStatistics' => ['array<int, array{mean:float, minima:float, maxima:float, standardDeviation:float, depth:int}>'],
'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{min:int, max:int}'],
'Imagick::getImageFilename' => ['string'],
'Imagick::getImageFormat' => ['string'],
'Imagick::getImageGamma' => ['float'],
'Imagick::getImageGeometry' => ['array{width:int, height:int}'],
'Imagick::getImageGravity' => ['int'],
'Imagick::getImageGreenPrimary' => ['array{x:float, y:float}'],
'Imagick::getImageHeight' => ['int'],
'Imagick::getImageHistogram' => ['list<ImagickPixel>'],
'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{width:int, height:int, x:int, y:int}'],
'Imagick::getImagePixelColor' => ['ImagickPixel', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageProfile' => ['string', 'name'=>'string'],
'Imagick::getImageProfiles' => ['array', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperties' => ['array<int|string, string>', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperty' => ['string|false', 'name'=>'string'],
'Imagick::getImageRedPrimary' => ['array{x:float, y:float}'],
'Imagick::getImageRegion' => ['Imagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageRenderingIntent' => ['int'],
'Imagick::getImageResolution' => ['array{x:float, y:float}'],
'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{x:float, y:float}'],
'Imagick::getImageWidth' => ['int'],
'Imagick::getInterlaceScheme' => ['int'],
'Imagick::getIteratorIndex' => ['int'],
'Imagick::getNumberImages' => ['int'],
'Imagick::getOption' => ['string', 'key'=>'string'],
'Imagick::getPackageName' => ['string'],
'Imagick::getPage' => ['array{width:int, height:int, x:int, y:int}'],
'Imagick::getPixelIterator' => ['ImagickPixelIterator'],
'Imagick::getPixelRegionIterator' => ['ImagickPixelIterator', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'Imagick::getPointSize' => ['float'],
'Imagick::getQuantum' => ['int'],
'Imagick::getQuantumDepth' => ['array{quantumDepthLong:int, quantumDepthString:string}'],
'Imagick::getQuantumRange' => ['array{quantumRangeLong:int, quantumRangeString:string}'],
'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{columns:int, rows: int}'],
'Imagick::getSizeOffset' => ['int'],
'Imagick::getVersion' => ['array{versionNumber: int, versionString:string}'],
'Imagick::haldClutImage' => ['bool', 'clut'=>'Imagick', 'channel='=>'int'],
'Imagick::hasNextImage' => ['bool'],
'Imagick::hasPreviousImage' => ['bool'],
'Imagick::identifyFormat' => ['string|false', 'embedText'=>'string'],
'Imagick::identifyImage' => ['array<string, mixed>', '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'=>'list<int>'],
'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' => ['list<string>', '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'=>'list<float>'],
'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'=>'list<string>'],
'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', 'legacy='=>'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<string, float>'],
'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'=>'list<array{x:float, y:float}>'],
'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'=>'list<array{x:float, y:float}>'],
'ImagickDraw::polyline' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'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'=>'list<int|float>'],
'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'=>'list<list<float>>', 'origin='=>'array'],
'ImagickKernel::getMatrix' => ['list<list<float|false>>'],
'ImagickKernel::scale' => ['void'],
'ImagickKernel::separate' => ['ImagickKernel[]'],
'ImagickKernel::seperate' => ['void'],
'ImagickPixel::__construct' => ['void', 'color='=>'string'],
'ImagickPixel::clear' => ['bool'],
'ImagickPixel::clone' => ['void'],
'ImagickPixel::destroy' => ['bool'],
'ImagickPixel::getColor' => ['array{r: int|float, g: int|float, b: int|float, a: int|float}', 'normalized='=>'int'],
'ImagickPixel::getColorAsString' => ['string'],
'ImagickPixel::getColorCount' => ['int'],
'ImagickPixel::getColorQuantum' => ['mixed'],
'ImagickPixel::getColorValue' => ['float', 'color'=>'int'],
'ImagickPixel::getColorValueQuantum' => ['mixed'],
'ImagickPixel::getHSL' => ['array{hue: float, saturation: float, luminosity: float}'],
'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', 'string'=>'string'],
'imap_alerts' => ['array|false'],
'imap_append' => ['bool', 'imap'=>'resource', 'folder'=>'string', 'message'=>'string', 'options='=>'string', 'internal_date='=>'string'],
'imap_base64' => ['string|false', 'string'=>'string'],
'imap_binary' => ['string|false', 'string'=>'string'],
'imap_body' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_bodystruct' => ['stdClass|false', 'imap'=>'resource', 'message_num'=>'int', 'section'=>'string'],
'imap_check' => ['stdClass|false', 'imap'=>'resource'],
'imap_clearflag_full' => ['bool', 'imap'=>'resource', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_close' => ['bool', 'imap'=>'resource', 'flags='=>'int'],
'imap_create' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_createmailbox' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_delete' => ['bool', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_deletemailbox' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_errors' => ['array|false'],
'imap_expunge' => ['bool', 'imap'=>'resource'],
'imap_fetch_overview' => ['array|false', 'imap'=>'resource', 'sequence'=>'string', 'flags='=>'int'],
'imap_fetchbody' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'section'=>'string', 'flags='=>'int'],
'imap_fetchheader' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_fetchmime' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'section'=>'string', 'flags='=>'int'],
'imap_fetchstructure' => ['stdClass|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_fetchtext' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_gc' => ['bool', 'imap'=>'resource', 'flags'=>'int'],
'imap_get_quota' => ['array|false', 'imap'=>'resource', 'quota_root'=>'string'],
'imap_get_quotaroot' => ['array|false', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_getacl' => ['array|false', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_getmailboxes' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_getsubscribed' => ['array|false', 'imap'=>'resource', 'reference'=>'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', 'imap'=>'resource', 'message_num'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string|null'],
'imap_headers' => ['array|false', 'imap'=>'resource'],
'imap_last_error' => ['string|false'],
'imap_list' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_listmailbox' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_listscan' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_listsubscribed' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_lsub' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string', 'cc='=>'string', 'bcc='=>'string', 'return_path='=>'string'],
'imap_mail_compose' => ['string|false', 'envelope'=>'array', 'bodies'=>'array'],
'imap_mail_copy' => ['bool', 'imap'=>'resource', 'message_nums'=>'string', 'mailbox'=>'string', 'flags='=>'int'],
'imap_mail_move' => ['bool', 'imap'=>'resource', 'message_nums'=>'string', 'mailbox'=>'string', 'flags='=>'int'],
'imap_mailboxmsginfo' => ['stdClass|false', 'imap'=>'resource'],
'imap_mime_header_decode' => ['array|false', 'string'=>'string'],
'imap_msgno' => ['int|false', 'imap'=>'resource', 'message_uid'=>'int'],
'imap_mutf7_to_utf8' => ['string|false', 'string'=>'string'],
'imap_num_msg' => ['int|false', 'imap'=>'resource'],
'imap_num_recent' => ['int|false', 'imap'=>'resource'],
'imap_open' => ['resource|false', 'mailbox'=>'string', 'user'=>'string', 'password'=>'string', 'flags='=>'int', 'retries='=>'int', 'options='=>'?array'],
'imap_ping' => ['bool', 'imap'=>'resource'],
'imap_qprint' => ['string|false', 'string'=>'string'],
'imap_rename' => ['bool', 'imap'=>'resource', 'from'=>'string', 'to'=>'string'],
'imap_renamemailbox' => ['bool', 'imap'=>'resource', 'from'=>'string', 'to'=>'string'],
'imap_reopen' => ['bool', 'imap'=>'resource', 'mailbox'=>'string', 'flags='=>'int', 'retries='=>'int'],
'imap_rfc822_parse_adrlist' => ['array', 'string'=>'string', 'default_hostname'=>'string'],
'imap_rfc822_parse_headers' => ['stdClass', 'headers'=>'string', 'default_hostname='=>'string'],
'imap_rfc822_write_address' => ['string|false', 'mailbox'=>'?string', 'hostname'=>'?string', 'personal'=>'?string'],
'imap_savebody' => ['bool', 'imap'=>'resource', 'file'=>'string|resource', 'message_num'=>'int', 'section='=>'string', 'flags='=>'int'],
'imap_scan' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_scanmailbox' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_search' => ['array|false', 'imap'=>'resource', 'criteria'=>'string', 'flags='=>'int', 'charset='=>'string'],
'imap_set_quota' => ['bool', 'imap'=>'resource', 'quota_root'=>'string', 'mailbox_size'=>'int'],
'imap_setacl' => ['bool', 'imap'=>'resource', 'mailbox'=>'string', 'user_id'=>'string', 'rights'=>'string'],
'imap_setflag_full' => ['bool', 'imap'=>'resource', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_sort' => ['array|false', 'imap'=>'resource', 'criteria'=>'int', 'reverse'=>'int', 'flags='=>'int', 'search_criteria='=>'string', 'charset='=>'string'],
'imap_status' => ['stdClass|false', 'imap'=>'resource', 'mailbox'=>'string', 'flags'=>'int'],
'imap_subscribe' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_thread' => ['array|false', 'imap'=>'resource', 'flags='=>'int'],
'imap_timeout' => ['int|bool', 'timeout_type'=>'int', 'timeout='=>'int'],
'imap_uid' => ['int|false', 'imap'=>'resource', 'message_num'=>'int'],
'imap_undelete' => ['bool', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_unsubscribe' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_utf7_decode' => ['string|false', 'string'=>'string'],
'imap_utf7_encode' => ['string', 'string'=>'string'],
'imap_utf8' => ['string', 'mime_encoded_text'=>'string'],
'imap_utf8_to_mutf7' => ['string|false', 'string'=>'string'],
'implode' => ['string', 'separator'=>'string', 'array'=>'array'],
'implode\'1' => ['string', 'separator'=>'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', 'ip'=>'string'],
'inet_pton' => ['string|false', 'ip'=>'string'],
'InfiniteIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'InfiniteIterator::current' => ['mixed'],
'InfiniteIterator::getInnerIterator' => ['Iterator'],
'InfiniteIterator::key' => ['bool|float|int|string'],
'InfiniteIterator::next' => ['void'],
'InfiniteIterator::rewind' => ['void'],
'InfiniteIterator::valid' => ['bool'],
'inflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'inflate_get_read_len' => ['int|false', 'context'=>'resource'],
'inflate_get_status' => ['int|false', 'context'=>'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', 'option'=>'string', 'value'=>'string'],
'ini_get' => ['string|false', 'option'=>'string'],
'ini_get_all' => ['array|false', 'extension='=>'?string', 'details='=>'bool'],
'ini_restore' => ['void', 'option'=>'string'],
'ini_set' => ['string|false', 'option'=>'string', 'value'=>'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', 'num1'=>'int', 'num2'=>'int'],
'interface_exists' => ['bool', 'interface'=>'string', 'autoload='=>'bool'],
'intl_error_name' => ['string', 'errorCode'=>'int'],
'intl_get_error_code' => ['int'],
'intl_get_error_message' => ['string'],
'intl_is_failure' => ['bool', 'errorCode'=>'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', 'calendar'=>'IntlCalendar', 'field'=>'int', 'value'=>'int'],
'intlcal_after' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_before' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_clear' => ['bool', 'calendar'=>'IntlCalendar', 'field='=>'int'],
'intlcal_create_instance' => ['IntlCalendar', 'timezone='=>'mixed', 'locale='=>'string'],
'intlcal_equals' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_field_difference' => ['int', 'calendar'=>'IntlCalendar', 'timestamp'=>'float', 'field'=>'int'],
'intlcal_from_date_time' => ['IntlCalendar', 'datetime'=>'DateTime|string'],
'intlcal_get' => ['mixed', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_maximum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_available_locales' => ['array'],
'intlcal_get_day_of_week_type' => ['int', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_get_first_day_of_week' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_greatest_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_keyword_values_for_locale' => ['Iterator|false', 'keyword'=>'string', 'locale'=>'string', 'onlyCommon'=>'bool'],
'intlcal_get_least_maximum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_locale' => ['string', 'calendar'=>'IntlCalendar', 'type'=>'int'],
'intlcal_get_maximum' => ['int|false', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_minimal_days_in_first_week' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_now' => ['float'],
'intlcal_get_repeated_wall_time_option' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_skipped_wall_time_option' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_time' => ['float', 'calendar'=>'IntlCalendar'],
'intlcal_get_time_zone' => ['IntlTimeZone', 'calendar'=>'IntlCalendar'],
'intlcal_get_type' => ['string', 'calendar'=>'IntlCalendar'],
'intlcal_get_weekend_transition' => ['int', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'string'],
'intlcal_in_daylight_time' => ['bool', 'calendar'=>'IntlCalendar'],
'intlcal_is_equivalent_to' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_is_lenient' => ['bool', 'calendar'=>'IntlCalendar'],
'intlcal_is_set' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_is_weekend' => ['bool', 'calendar'=>'IntlCalendar', 'timestamp='=>'float'],
'intlcal_roll' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int', 'value'=>'mixed'],
'intlcal_set' => ['bool', 'calendar'=>'IntlCalendar', 'year'=>'int', 'month'=>'int'],
'intlcal_set\'1' => ['bool', 'calendar'=>'IntlCalendar', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'intlcal_set_first_day_of_week' => ['bool', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_set_lenient' => ['bool', 'calendar'=>'IntlCalendar', 'lenient'=>'bool'],
'intlcal_set_repeated_wall_time_option' => ['bool', 'calendar'=>'IntlCalendar', 'option'=>'int'],
'intlcal_set_skipped_wall_time_option' => ['bool', 'calendar'=>'IntlCalendar', 'option'=>'int'],
'intlcal_set_time' => ['bool', 'calendar'=>'IntlCalendar', 'timestamp'=>'float'],
'intlcal_set_time_zone' => ['bool', 'calendar'=>'IntlCalendar', 'timezone'=>'mixed'],
'intlcal_to_date_time' => ['DateTime|false', 'calendar'=>'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', 'value'=>'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' => ['list<array<string,mixed>>'],
'IntlException::getTraceAsString' => ['string'],
'intlgregcal_create_instance' => ['IntlGregorianCalendar', 'timezoneOrYear='=>'mixed', 'localeOrMonth='=>'string'],
'intlgregcal_get_gregorian_change' => ['float', 'calendar'=>'IntlGregorianCalendar'],
'intlgregcal_is_leap_year' => ['bool', 'calendar'=>'int'],
'intlgregcal_set_gregorian_change' => ['void', 'calendar'=>'IntlGregorianCalendar', 'timestamp'=>'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', 'timezoneId'=>'string'],
'intltz_create_enumeration' => ['IntlIterator', 'countryOrRawOffset'=>'mixed'],
'intltz_create_time_zone' => ['IntlTimeZone', 'timezoneId'=>'string'],
'intltz_from_date_time_zone' => ['IntlTimeZone', 'timezone'=>'DateTimeZone'],
'intltz_get_canonical_id' => ['string', 'timezoneId'=>'string', '&isSystemId'=>'bool'],
'intltz_get_display_name' => ['string', 'timezone'=>'IntlTimeZone', 'dst'=>'bool', 'style'=>'int', 'locale'=>'string'],
'intltz_get_dst_savings' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_equivalent_id' => ['string', 'timezoneId'=>'string', 'offset'=>'int'],
'intltz_get_error_code' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_error_message' => ['string', 'timezone'=>'IntlTimeZone'],
'intltz_get_id' => ['string', 'timezone'=>'IntlTimeZone'],
'intltz_get_offset' => ['int', 'timezone'=>'IntlTimeZone', 'timestamp'=>'float', 'local'=>'bool', '&rawOffset'=>'int', '&dstOffset'=>'int'],
'intltz_get_raw_offset' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_tz_data_version' => ['string', 'object'=>'IntlTimeZone'],
'intltz_getGMT' => ['IntlTimeZone'],
'intltz_has_same_rules' => ['bool', 'timezone'=>'IntlTimeZone', 'other'=>'IntlTimeZone'],
'intltz_to_date_time_zone' => ['DateTimeZone', 'timezone'=>'IntlTimeZone'],
'intltz_use_daylight_time' => ['bool', 'timezone'=>'IntlTimeZone'],
'intlz_create_default' => ['IntlTimeZone'],
'intval' => ['int', 'value'=>'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' => ['list<array<string,mixed>>'],
'InvalidArgumentException::getTraceAsString' => ['string'],
'ip2long' => ['int|false', 'ip'=>'string'],
'iptcembed' => ['string|bool', 'iptc_data'=>'string', 'filename'=>'string', 'spool='=>'int'],
'iptcparse' => ['array|false', 'iptc_block'=>'string'],
'is_a' => ['bool', 'object_or_class'=>'mixed', 'class'=>'string', 'allow_string='=>'bool'],
'is_array' => ['bool', 'value'=>'mixed'],
'is_bool' => ['bool', 'value'=>'mixed'],
'is_callable' => ['bool', 'value'=>'callable|mixed', 'syntax_only='=>'bool', '&w_callable_name='=>'string'],
'is_countable' => ['bool', 'value'=>'mixed'],
'is_dir' => ['bool', 'filename'=>'string'],
'is_double' => ['bool', 'value'=>'mixed'],
'is_executable' => ['bool', 'filename'=>'string'],
'is_file' => ['bool', 'filename'=>'string'],
'is_finite' => ['bool', 'num'=>'float'],
'is_float' => ['bool', 'value'=>'mixed'],
'is_infinite' => ['bool', 'num'=>'float'],
'is_int' => ['bool', 'value'=>'mixed'],
'is_integer' => ['bool', 'value'=>'mixed'],
'is_iterable' => ['bool', 'value'=>'mixed'],
'is_link' => ['bool', 'filename'=>'string'],
'is_long' => ['bool', 'value'=>'mixed'],
'is_nan' => ['bool', 'num'=>'float'],
'is_null' => ['bool', 'value'=>'mixed'],
'is_numeric' => ['bool', 'value'=>'mixed'],
'is_object' => ['bool', 'value'=>'mixed'],
'is_readable' => ['bool', 'filename'=>'string'],
'is_real' => ['bool', 'value'=>'mixed'],
'is_resource' => ['bool', 'value'=>'mixed'],
'is_scalar' => ['bool', 'value'=>'mixed'],
'is_soap_fault' => ['bool', 'object'=>'mixed'],
'is_string' => ['bool', 'value'=>'mixed'],
'is_subclass_of' => ['bool', 'object_or_class'=>'object|string', 'class'=>'class-string', 'allow_string='=>'bool'],
'is_tainted' => ['bool', 'string'=>'string'],
'is_uploaded_file' => ['bool', 'filename'=>'string'],
'is_writable' => ['bool', 'filename'=>'string'],
'is_writeable' => ['bool', 'filename'=>'string'],
'isset' => ['bool', 'value'=>'mixed', '...rest='=>'mixed'],
'Iterator::current' => ['mixed'],
'Iterator::key' => ['mixed'],
'Iterator::next' => ['void'],
'Iterator::rewind' => ['void'],
'Iterator::valid' => ['bool'],
'iterator_apply' => ['int', 'iterator'=>'Traversable', 'callback'=>'callable(mixed):bool', 'args='=>'array'],
'iterator_count' => ['int', 'iterator'=>'Traversable'],
'iterator_to_array' => ['array', 'iterator'=>'Traversable', 'preserve_keys='=>'bool'],
'IteratorAggregate::getIterator' => ['Traversable'],
'IteratorIterator::__construct' => ['void', 'it'=>'Traversable'],
'IteratorIterator::current' => ['mixed'],
'IteratorIterator::getInnerIterator' => ['Iterator'],
'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', 'julian_day'=>'int', 'mode='=>'int'],
'jdmonthname' => ['string', 'julian_day'=>'int', 'mode'=>'int'],
'jdtofrench' => ['string', 'julian_day'=>'int'],
'jdtogregorian' => ['string', 'julian_day'=>'int'],
'jdtojewish' => ['string', 'julian_day'=>'int', 'hebrew='=>'bool', 'flags='=>'int'],
'jdtojulian' => ['string', 'julian_day'=>'int'],
'jdtounix' => ['int|false', 'julian_day'=>'int'],
'jewishtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'jobqueue_license_info' => ['array'],
'join' => ['string', 'separator'=>'string', 'array'=>'array'],
'join\'1' => ['string', 'separator'=>'array'],
'json_decode' => ['mixed', 'json'=>'string', 'associative='=>'bool', 'depth='=>'int', 'flags='=>'int'],
'json_encode' => ['string|false', 'value'=>'mixed', 'flags='=>'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' => ['list<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'=>'array|object'],
'key_exists' => ['bool', 'key'=>'string|int', 'array'=>'array'],
'krsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'ksort' => ['bool', '&rw_array'=>'array', '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', 'string'=>'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', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_add_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_bind' => ['bool', 'ldap'=>'resource', 'dn='=>'string|null', 'password='=>'string|null'],
'ldap_bind_ext' => ['resource|false', 'ldap'=>'resource', 'dn='=>'string|null', 'password='=>'string|null', 'controls='=>'array'],
'ldap_close' => ['bool', 'ldap'=>'resource'],
'ldap_compare' => ['bool|int', 'ldap'=>'resource', 'dn'=>'string', 'attribute'=>'string', 'value'=>'string'],
'ldap_connect' => ['resource|false', 'uri='=>'string', 'port='=>'int', 'wallet='=>'string', 'password='=>'string', 'auth_mode='=>'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', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_delete' => ['bool', 'ldap'=>'resource', 'dn'=>'string'],
'ldap_delete_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'controls='=>'array'],
'ldap_dn2ufn' => ['string', 'dn'=>'string'],
'ldap_err2str' => ['string', 'errno'=>'int'],
'ldap_errno' => ['int', 'ldap'=>'resource'],
'ldap_error' => ['string', 'ldap'=>'resource'],
'ldap_escape' => ['string', 'value'=>'string', 'ignore='=>'string', 'flags='=>'int'],
'ldap_exop' => ['mixed', 'ldap'=>'resource', 'reqoid'=>'string', 'reqdata='=>'string', 'serverctrls='=>'array|null', '&w_response_data='=>'string', '&w_response_oid='=>'string'],
'ldap_exop_passwd' => ['bool|string', 'ldap'=>'resource', 'user='=>'string', 'old_password='=>'string', 'new_password='=>'string', '&w_controls='=>'array|null'],
'ldap_exop_refresh' => ['int|false', 'ldap'=>'resource', 'dn'=>'string', 'ttl'=>'int'],
'ldap_exop_whoami' => ['string|false', 'ldap'=>'resource'],
'ldap_explode_dn' => ['array|false', 'dn'=>'string', 'with_attrib'=>'int'],
'ldap_first_attribute' => ['string|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_first_entry' => ['resource|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_first_reference' => ['resource|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_free_result' => ['bool', 'ldap'=>'resource'],
'ldap_get_attributes' => ['array|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_get_dn' => ['string|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_get_entries' => ['array|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_get_option' => ['bool', 'ldap'=>'resource', 'option'=>'int', '&w_value'=>'mixed'],
'ldap_get_values' => ['array|false', 'ldap'=>'resource', 'entry'=>'resource', 'attribute'=>'string'],
'ldap_get_values_len' => ['array|false', 'ldap'=>'resource', 'entry'=>'resource', 'attribute'=>'string'],
'ldap_list' => ['resource|false', 'ldap'=>'resource|array', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_mod_add' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_add_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_mod_del' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_del_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_mod_replace' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_replace_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_modify' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_modify_batch' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'modifications_info'=>'array'],
'ldap_next_attribute' => ['string|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_next_entry' => ['resource|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_next_reference' => ['resource|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_parse_exop' => ['bool', 'ldap'=>'resource', 'result'=>'resource', '&w_response_data='=>'string', '&w_response_oid='=>'string'],
'ldap_parse_reference' => ['bool', 'ldap'=>'resource', 'entry'=>'resource', 'referrals'=>'array'],
'ldap_parse_result' => ['bool', 'ldap'=>'resource', 'result'=>'resource', '&w_error_code'=>'int', '&w_matched_dn='=>'string', '&w_error_message='=>'string', '&w_referrals='=>'array', '&w_controls='=>'array'],
'ldap_read' => ['resource|false', 'ldap'=>'resource|array', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_rename' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'new_rdn'=>'string', 'new_parent'=>'string', 'delete_old_rdn'=>'bool'],
'ldap_rename_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'new_rdn'=>'string', 'new_parent'=>'string', 'delete_old_rdn'=>'bool', 'controls='=>'array'],
'ldap_sasl_bind' => ['bool', 'ldap'=>'resource', 'dn='=>'string', 'password='=>'string', 'mech='=>'string', 'realm='=>'string', 'authc_id='=>'string', 'authz_id='=>'string', 'props='=>'string'],
'ldap_search' => ['resource|false', 'ldap'=>'resource|resource[]', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_set_option' => ['bool', 'ldap'=>'resource|null', 'option'=>'int', 'value'=>'mixed'],
'ldap_set_rebind_proc' => ['bool', 'ldap'=>'resource', 'callback'=>'string'],
'ldap_start_tls' => ['bool', 'ldap'=>'resource'],
'ldap_t61_to_8859' => ['string', 'value'=>'string'],
'ldap_unbind' => ['bool', 'ldap'=>'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' => ['list<array<string,mixed>>'],
'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', 'string1'=>'string', 'string2'=>'string'],
'levenshtein\'1' => ['int', 'string1'=>'string', 'string2'=>'string', 'insertion_cost'=>'int', 'repetition_cost'=>'int', 'deletion_cost'=>'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', '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', 'path'=>'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', 'locale'=>'string'],
'locale_compose' => ['string|false', 'subtags'=>'array'],
'locale_filter_matches' => ['bool', 'languageTag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'locale_get_all_variants' => ['array', 'locale'=>'string'],
'locale_get_default' => ['string'],
'locale_get_display_language' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_name' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_region' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_script' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_variant' => ['string', 'locale'=>'string', 'displayLocale='=>'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', 'languageTag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'defaultLocale='=>'string'],
'locale_parse' => ['array', 'locale'=>'string'],
'locale_set_default' => ['bool', 'locale'=>'string'],
'localeconv' => ['array'],
'localtime' => ['array', 'timestamp='=>'int', 'associative='=>'bool'],
'log' => ['float', 'num'=>'float', 'base='=>'float'],
'log10' => ['float', 'num'=>'float'],
'log1p' => ['float', 'num'=>'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' => ['list<array<string,mixed>>'],
'LogicException::getTraceAsString' => ['string'],
'long2ip' => ['string', 'ip'=>'string|int'],
'lstat' => ['array|false', 'filename'=>'string'],
'ltrim' => ['string', 'string'=>'string', 'characters='=>'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_params='=>'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', 'value'=>'non-empty-array'],
'max\'1' => ['mixed', 'value'=>'', 'values'=>'', '...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', 'value='=>'array|string|null', 'encoding='=>'string|null'],
'mb_chr' => ['string|false', 'codepoint'=>'int', 'encoding='=>'string|null'],
'mb_convert_case' => ['string', 'string'=>'string', 'mode'=>'int', 'encoding='=>'string|null'],
'mb_convert_encoding' => ['string|false', 'string'=>'string', 'to_encoding'=>'string', 'from_encoding='=>'array|string|null'],
'mb_convert_encoding\'1' => ['array<int, string>', 'string'=>'array<int, string>', 'to_encoding'=>'string', 'from_encoding='=>'array|string|null'],
'mb_convert_kana' => ['string', 'string'=>'string', 'mode='=>'string', 'encoding='=>'string|null'],
'mb_convert_variables' => ['string|false', 'to_encoding'=>'string', 'from_encoding'=>'array|string', '&rw_var'=>'string|array|object', '&...rw_vars='=>'string|array|object'],
'mb_decode_mimeheader' => ['string', 'string'=>'string'],
'mb_decode_numericentity' => ['string', 'string'=>'string', 'map'=>'array', 'encoding='=>'string|null'],
'mb_detect_encoding' => ['string|false', 'string'=>'string', 'encodings='=>'array|string|null', 'strict='=>'bool'],
'mb_detect_order' => ['bool|list<string>', 'encoding='=>'array|string|null'],
'mb_encode_mimeheader' => ['string', 'string'=>'string', 'charset='=>'string|null', 'transfer_encoding='=>'string|null', 'newline='=>'string', 'indent='=>'int'],
'mb_encode_numericentity' => ['string', 'string'=>'string', 'map'=>'array', 'encoding='=>'string|null', 'hex='=>'bool'],
'mb_encoding_aliases' => ['list<string>|false', 'encoding'=>'string'],
'mb_ereg' => ['bool', 'pattern'=>'string', 'string'=>'string', '&w_matches='=>'array|null'],
'mb_ereg_match' => ['bool', 'pattern'=>'string', 'string'=>'string', 'options='=>'string|null'],
'mb_ereg_replace' => ['string|false|null', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'options='=>'string|null'],
'mb_ereg_replace_callback' => ['string|false', 'pattern'=>'string', 'callback'=>'callable', 'string'=>'string', 'options='=>'string|null'],
'mb_ereg_search' => ['bool', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_getpos' => ['int'],
'mb_ereg_search_getregs' => ['string[]|false'],
'mb_ereg_search_init' => ['bool', 'string'=>'string', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_pos' => ['int[]|false', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_regs' => ['string[]|false', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_setpos' => ['bool', 'offset'=>'int'],
'mb_eregi' => ['bool', 'pattern'=>'string', 'string'=>'string', '&w_matches='=>'array|null'],
'mb_eregi_replace' => ['string|false|null', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'options='=>'string|null'],
'mb_get_info' => ['array|string|int|false', 'type='=>'string'],
'mb_http_input' => ['array|string|false', 'type='=>'string|null'],
'mb_http_output' => ['string|bool', 'encoding='=>'string|null'],
'mb_internal_encoding' => ['string|bool', 'encoding='=>'string|null'],
'mb_language' => ['string|bool', 'language='=>'string|null'],
'mb_list_encodings' => ['list<string>'],
'mb_ord' => ['int|false', 'string'=>'string', 'encoding='=>'string|null'],
'mb_output_handler' => ['string', 'string'=>'string', 'status'=>'int'],
'mb_parse_str' => ['bool', 'string'=>'string', '&w_result'=>'array'],
'mb_preferred_mime_name' => ['string|false', 'encoding'=>'string'],
'mb_regex_encoding' => ['string|bool', 'encoding='=>'string|null'],
'mb_regex_set_options' => ['string', 'options='=>'string|null'],
'mb_scrub' => ['string', 'string'=>'string', 'encoding='=>'string|null'],
'mb_send_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array', 'additional_params='=>'string|null'],
'mb_split' => ['list<string>', 'pattern'=>'string', 'string'=>'string', 'limit='=>'int'],
'mb_str_split' => ['non-empty-list<string>', 'string'=>'string', 'length='=>'positive-int', 'encoding='=>'string|null'],
'mb_strcut' => ['string', 'string'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string|null'],
'mb_strimwidth' => ['string', 'string'=>'string', 'start'=>'int', 'width'=>'int', 'trim_marker='=>'string', 'encoding='=>'string|null'],
'mb_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strlen' => ['int', 'string'=>'string', 'encoding='=>'string|null'],
'mb_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strrichr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strtolower' => ['lowercase-string', 'string'=>'string', 'encoding='=>'string|null'],
'mb_strtoupper' => ['string', 'string'=>'string', 'encoding='=>'string|null'],
'mb_strwidth' => ['int', 'string'=>'string', 'encoding='=>'string|null'],
'mb_substitute_character' => ['bool|int|string', 'substitute_character='=>'int|string|null'],
'mb_substr' => ['string', 'string'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string|null'],
'mb_substr_count' => ['int', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string|null'],
'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', 'string'=>'string', 'binary='=>'bool'],
'md5_file' => ['string|false', 'filename'=>'string', 'binary='=>'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' => ['bool', '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' => ['string|array|false', 'key'=>'string', 'flags='=>'array', 'keys='=>'array'],
'Memcache::get\'1' => ['array', 'key'=>'string[]', 'flags='=>'int[]'],
'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' => ['bool', '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' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_add_server' => ['bool', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable', 'timeoutms='=>'int'],
'memcache_append' => ['', 'memcache_obj'=>'Memcache'],
'memcache_cas' => ['', 'memcache_obj'=>'Memcache'],
'memcache_close' => ['bool', 'memcache_obj'=>'Memcache'],
'memcache_connect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'memcache_debug' => ['bool', 'on_off'=>'bool'],
'memcache_decrement' => ['int', 'memcache_obj'=>'Memcache', 'key'=>'string', 'value='=>'int'],
'memcache_delete' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'timeout='=>'int'],
'memcache_flush' => ['bool', 'memcache_obj'=>'Memcache'],
'memcache_get' => ['string', 'memcache_obj'=>'Memcache', 'key'=>'string', 'flags='=>'int'],
'memcache_get\'1' => ['array', 'memcache_obj'=>'Memcache', 'key'=>'string[]', 'flags='=>'int[]'],
'memcache_get_extended_stats' => ['array', 'memcache_obj'=>'Memcache', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'memcache_get_server_status' => ['int', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int'],
'memcache_get_stats' => ['array', 'memcache_obj'=>'Memcache', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'memcache_get_version' => ['string', 'memcache_obj'=>'Memcache'],
'memcache_increment' => ['int', 'memcache_obj'=>'Memcache', 'key'=>'string', 'value='=>'int'],
'memcache_pconnect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'memcache_prepend' => ['string', 'memcache_obj'=>'Memcache'],
'memcache_replace' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_set' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_set_compress_threshold' => ['bool', 'memcache_obj'=>'Memcache', 'threshold'=>'int', 'min_savings='=>'float'],
'memcache_set_failure_callback' => ['', 'memcache_obj'=>'Memcache'],
'memcache_set_server_params' => ['bool', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable'],
'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', 'string'=>'string', 'max_phonemes='=>'int'],
'method_exists' => ['bool', 'object_or_class'=>'object|class-string|interface-string', 'method'=>'string'],
'mhash' => ['string', 'algo'=>'int', 'data'=>'string', 'key='=>'string'],
'mhash_count' => ['int'],
'mhash_get_block_size' => ['int|false', 'algo'=>'int'],
'mhash_get_hash_name' => ['string|false', 'algo'=>'int'],
'mhash_keygen_s2k' => ['string|false', 'algo'=>'int', 'password'=>'string', 'salt'=>'string', 'length'=>'int'],
'microtime' => ['string', 'as_float='=>'false'],
'microtime\'1' => ['float', 'as_float='=>'true'],
'mime_content_type' => ['string|false', 'filename'=>'string|resource'],
'min' => ['mixed', 'value'=>'non-empty-array'],
'min\'1' => ['mixed', 'value'=>'', 'values'=>'', '...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', 'directory'=>'string', 'permissions='=>'int', 'recursive='=>'bool', 'context='=>'resource'],
'mktime' => ['int|false', 'hour'=>'int', 'minute='=>'int|null', 'second='=>'int|null', 'month='=>'int|null', 'day='=>'int|null', 'year='=>'int|null'],
'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' => ['list<array<string,mixed>>'],
'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', 'second='=>'int', 'usecond='=>'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\CursorId::serialize' => ['string'],
'MongoDB\Driver\CursorId::unserialize' => ['void', 'serialized'=>'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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\ReadConcern::serialize' => ['string'],
'MongoDB\Driver\ReadConcern::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\ReadPreference::__construct' => ['void', 'mode'=>'string|int', 'tagSets='=>'array', 'options='=>'array'],
'MongoDB\Driver\ReadPreference::bsonSerialize' => ['object'],
'MongoDB\Driver\ReadPreference::getHedge' => ['object|null'],
'MongoDB\Driver\ReadPreference::getMaxStalenessSeconds' => ['int'],
'MongoDB\Driver\ReadPreference::getMode' => ['int'],
'MongoDB\Driver\ReadPreference::getModeString' => ['string'],
'MongoDB\Driver\ReadPreference::getTagSets' => ['array'],
'MongoDB\Driver\ReadPreference::serialize' => ['string'],
'MongoDB\Driver\ReadPreference::unserialize' => ['void', 'serialized'=>'string'],
'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::getTransactionOptions' => ['array|null'],
'mongodb\driver\session::getTransactionState' => ['string'],
'mongodb\driver\session::startTransaction' => ['void', 'options'=>'array|object'],
'MongoDB\Driver\WriteConcern::__construct' => ['void', 'wstring'=>'string|int', 'wtimeout='=>'int', 'journal='=>'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\WriteConcern::serialize' => ['string'],
'MongoDB\Driver\WriteConcern::unserialize' => ['void', 'serialized'=>'string'],
'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'MongoResultException::getTraceAsString' => ['string'],
'MongoTimestamp::__construct' => ['void', 'second='=>'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' => ['list<array<string,mixed>>'],
'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', 'from'=>'string', 'to'=>'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', 'value'=>'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', 'permissions='=>'int'],
'msg_queue_exists' => ['bool', 'key'=>'int'],
'msg_receive' => ['bool', 'queue'=>'resource', 'desired_message_type'=>'int', '&w_received_message_type'=>'int', 'max_message_size'=>'int', '&w_message'=>'mixed', 'unserialize='=>'bool', 'flags='=>'int', '&w_error_code='=>'int'],
'msg_remove_queue' => ['bool', 'queue'=>'resource'],
'msg_send' => ['bool', 'queue'=>'resource', 'message_type'=>'int', 'message'=>'mixed', 'serialize='=>'bool', 'blocking='=>'bool', '&w_error_code='=>'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', 'formatter'=>'MessageFormatter', 'values'=>'array'],
'msgfmt_format_message' => ['string|false', 'locale'=>'string', 'pattern'=>'string', 'values'=>'array'],
'msgfmt_get_error_code' => ['int', 'formatter'=>'MessageFormatter'],
'msgfmt_get_error_message' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_locale' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_pattern' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_parse' => ['array|false', 'formatter'=>'MessageFormatter', 'string'=>'string'],
'msgfmt_parse_message' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'message'=>'string'],
'msgfmt_set_pattern' => ['bool', 'formatter'=>'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', 'hostname='=>'string', 'username='=>'string', 'password='=>'string', 'database='=>'string', 'port='=>'int', 'socket='=>'string'],
'mysqli::autocommit' => ['bool', 'enable'=>'bool'],
'mysqli::begin_transaction' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::change_user' => ['bool', 'username'=>'string', 'password'=>'string', 'database'=>'string'],
'mysqli::character_set_name' => ['string'],
'mysqli::close' => ['bool'],
'mysqli::commit' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::debug' => ['bool', 'options'=>'string'],
'mysqli::disable_reads_from_master' => ['bool'],
'mysqli::dump_debug_info' => ['bool'],
'mysqli::escape_string' => ['string', 'string'=>'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', 'process_id'=>'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_write'=>'array', '&w_error'=>'array', 'seconds'=>'int', 'microseconds='=>'int'],
'mysqli::prepare' => ['mysqli_stmt|false', 'query'=>'string'],
'mysqli::query' => ['bool|mysqli_result', 'query'=>'string', 'result_mode='=>'int'],
'mysqli::real_connect' => ['bool', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null', 'flags='=>'int'],
'mysqli::real_escape_string' => ['string', 'string'=>'string'],
'mysqli::real_query' => ['bool', 'query'=>'string'],
'mysqli::reap_async_query' => ['mysqli_result|false'],
'mysqli::refresh' => ['bool', 'flags'=>'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', 'database'=>'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', 'certificate'=>'string', 'ca_certificate'=>'string', 'ca_path'=>'string', 'cipher_algos'=>'string'],
'mysqli::stat' => ['string|false'],
'mysqli::stmt_init' => ['mysqli_stmt'],
'mysqli::store_result' => ['mysqli_result|false', 'mode='=>'int'],
'mysqli::thread_safe' => ['bool'],
'mysqli::use_result' => ['mysqli_result|false'],
'mysqli_affected_rows' => ['int', 'mysql'=>'mysqli'],
'mysqli_autocommit' => ['bool', 'mysql'=>'mysqli', 'enable'=>'bool'],
'mysqli_begin_transaction' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_change_user' => ['bool', 'mysql'=>'mysqli', 'username'=>'string', 'password'=>'string', 'database'=>'?string'],
'mysqli_character_set_name' => ['string', 'mysql'=>'mysqli'],
'mysqli_close' => ['bool', 'mysql'=>'mysqli'],
'mysqli_commit' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_connect' => ['mysqli|false', 'hostname='=>'string', 'username='=>'string', 'password='=>'string', 'database='=>'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', 'options'=>'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', 'mysql'=>'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', 'mysql'=>'mysqli'],
'mysqli_error' => ['string', 'mysql'=>'mysqli'],
'mysqli_error_list' => ['array', 'mysql'=>'mysqli'],
'mysqli_escape_string' => ['string', 'mysql'=>'mysqli', 'string'=>'string'],
'mysqli_execute' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_fetch_all' => ['array', 'result'=>'mysqli_result', 'mode='=>'int'],
'mysqli_fetch_array' => ['?array', 'result'=>'mysqli_result', 'mode='=>'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', 'index'=>'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='=>'string', 'constructor_args='=>'?array'],
'mysqli_fetch_row' => ['?array', 'result'=>'mysqli_result'],
'mysqli_field_count' => ['int', 'mysql'=>'mysqli'],
'mysqli_field_seek' => ['bool', 'result'=>'mysqli_result', 'index'=>'int'],
'mysqli_field_tell' => ['int', 'result'=>'mysqli_result'],
'mysqli_free_result' => ['void', 'result'=>'mysqli_result'],
'mysqli_get_cache_stats' => ['array|false'],
'mysqli_get_charset' => ['object', 'mysql'=>'mysqli'],
'mysqli_get_client_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_client_stats' => ['array|false'],
'mysqli_get_client_version' => ['int', 'link'=>'mysqli'],
'mysqli_get_connection_stats' => ['array|false', 'mysql'=>'mysqli'],
'mysqli_get_host_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_links_stats' => ['array'],
'mysqli_get_proto_info' => ['int', 'mysql'=>'mysqli'],
'mysqli_get_server_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_server_version' => ['int', 'mysql'=>'mysqli'],
'mysqli_get_warnings' => ['mysqli_warning', 'mysql'=>'mysqli'],
'mysqli_info' => ['?string', 'mysql'=>'mysqli'],
'mysqli_init' => ['mysqli|false'],
'mysqli_insert_id' => ['int|string', 'mysql'=>'mysqli'],
'mysqli_kill' => ['bool', 'mysql'=>'mysqli', 'process_id'=>'int'],
'mysqli_link_construct' => ['object'],
'mysqli_master_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_more_results' => ['bool', 'mysql'=>'mysqli'],
'mysqli_multi_query' => ['bool', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_next_result' => ['bool', 'mysql'=>'mysqli'],
'mysqli_num_fields' => ['int', 'result'=>'mysqli_result'],
'mysqli_num_rows' => ['int', 'result'=>'mysqli_result'],
'mysqli_options' => ['bool', 'mysql'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_ping' => ['bool', 'mysql'=>'mysqli'],
'mysqli_poll' => ['int|false', 'read'=>'array', 'write'=>'array', 'error'=>'array', 'seconds'=>'int', 'microseconds='=>'int'],
'mysqli_prepare' => ['mysqli_stmt|false', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_query' => ['mysqli_result|bool', 'mysql'=>'mysqli', 'query'=>'string', 'result_mode='=>'int'],
'mysqli_real_connect' => ['bool', 'mysql='=>'mysqli', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null', 'flags='=>'int'],
'mysqli_real_escape_string' => ['string', 'mysql'=>'mysqli', 'string'=>'string'],
'mysqli_real_query' => ['bool', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_reap_async_query' => ['mysqli_result|false', 'mysql'=>'mysqli'],
'mysqli_refresh' => ['bool', 'mysql'=>'mysqli', 'flags'=>'int'],
'mysqli_release_savepoint' => ['bool', 'mysql'=>'mysqli', 'name'=>'string'],
'mysqli_report' => ['bool', 'flags'=>'int'],
'mysqli_result::__construct' => ['void', 'mysql'=>'mysqli', 'result_mode='=>'int'],
'mysqli_result::close' => ['void'],
'mysqli_result::data_seek' => ['bool', 'offset'=>'int'],
'mysqli_result::fetch_all' => ['array', 'mode='=>'int'],
'mysqli_result::fetch_array' => ['?array', 'mode='=>'int'],
'mysqli_result::fetch_assoc' => ['array<string,string>|null'],
'mysqli_result::fetch_field' => ['object|false'],
'mysqli_result::fetch_field_direct' => ['object|false', 'index'=>'int'],
'mysqli_result::fetch_fields' => ['array|false'],
'mysqli_result::fetch_object' => ['object|stdClass|null', 'class='=>'string', 'constructor_args='=>'array'],
'mysqli_result::fetch_row' => ['?array'],
'mysqli_result::field_seek' => ['bool', 'index'=>'int'],
'mysqli_result::free' => ['void'],
'mysqli_result::free_result' => ['void'],
'mysqli_rollback' => ['bool', 'mysql'=>'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', 'mysql'=>'mysqli', 'name'=>'string'],
'mysqli_savepoint_libmysql' => ['bool'],
'mysqli_select_db' => ['bool', 'mysql'=>'mysqli', 'database'=>'string'],
'mysqli_send_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_set_charset' => ['bool', 'mysql'=>'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', 'mysql'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_slave_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_sqlstate' => ['string', 'mysql'=>'mysqli'],
'mysqli_ssl_set' => ['bool', 'mysql'=>'mysqli', 'key'=>'string', 'certificate'=>'string', 'ca_certificate'=>'string', 'ca_path'=>'string', 'cipher_algos'=>'string'],
'mysqli_stat' => ['string|false', 'mysql'=>'mysqli'],
'mysqli_stmt::__construct' => ['void', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_stmt::attr_get' => ['false|int', 'attribute'=>'int'],
'mysqli_stmt::attr_set' => ['bool', 'attribute'=>'int', 'value'=>'int'],
'mysqli_stmt::bind_param' => ['bool', 'types'=>'string', '&vars'=>'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|null'],
'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_num'=>'int', 'data'=>'string'],
'mysqli_stmt::store_result' => ['bool'],
'mysqli_stmt_affected_rows' => ['int|string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_attr_get' => ['int|false', 'statement'=>'mysqli_stmt', 'attribute'=>'int'],
'mysqli_stmt_attr_set' => ['bool', 'statement'=>'mysqli_stmt', 'attribute'=>'int', 'value'=>'int'],
'mysqli_stmt_bind_param' => ['bool', 'statement'=>'mysqli_stmt', 'types'=>'string', '&vars'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt_bind_result' => ['bool', 'statement'=>'mysqli_stmt', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt_close' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_data_seek' => ['void', 'statement'=>'mysqli_stmt', 'offset'=>'int'],
'mysqli_stmt_errno' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_error' => ['string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_error_list' => ['array', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_execute' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_fetch' => ['bool|null', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_field_count' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_free_result' => ['void', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_get_result' => ['mysqli_result|false', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_get_warnings' => ['object', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_init' => ['mysqli_stmt', 'mysql'=>'mysqli'],
'mysqli_stmt_insert_id' => ['mixed', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_more_results' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_next_result' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_num_rows' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_param_count' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_prepare' => ['bool', 'statement'=>'mysqli_stmt', 'query'=>'string'],
'mysqli_stmt_reset' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_result_metadata' => ['mysqli_result|false', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_send_long_data' => ['bool', 'statement'=>'mysqli_stmt', 'param_num'=>'int', 'data'=>'string'],
'mysqli_stmt_sqlstate' => ['string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_store_result' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_store_result' => ['mysqli_result|false', 'mysql'=>'mysqli', 'mode='=>'int'],
'mysqli_thread_id' => ['int', 'mysql'=>'mysqli'],
'mysqli_thread_safe' => ['bool'],
'mysqli_use_result' => ['mysqli_result|false', 'mysql'=>'mysqli'],
'mysqli_warning::__construct' => ['void'],
'mysqli_warning::next' => ['bool'],
'mysqli_warning_count' => ['int', 'mysql'=>'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'=>'array'],
'natsort' => ['bool', '&rw_array'=>'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', 'string'=>'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', 'value'=>'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', '&r_array'=>'array|object'],
'ngettext' => ['string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int'],
'nl2br' => ['string', 'string'=>'string', 'use_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', 'string'=>'string'],
'normalizer_is_normalized' => ['bool', 'string'=>'string', 'form='=>'int'],
'normalizer_normalize' => ['string', 'string'=>'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', 'num'=>'float|int', 'decimals='=>'int'],
'number_format\'1' => ['string', 'num'=>'float|int', 'decimals'=>'int', 'decimal_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', 'string'=>'string', 'type='=>'int', '&rw_position='=>'int'],
'NumberFormatter::parseCurrency' => ['float|false', 'string'=>'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', 'formatter'=>'NumberFormatter', 'num'=>'int|float', 'type='=>'int'],
'numfmt_format_currency' => ['string|false', 'formatter'=>'NumberFormatter', 'amount'=>'float', 'currency'=>'string'],
'numfmt_get_attribute' => ['int|false', 'formatter'=>'NumberFormatter', 'attribute'=>'int'],
'numfmt_get_error_code' => ['int', 'formatter'=>'NumberFormatter'],
'numfmt_get_error_message' => ['string', 'formatter'=>'NumberFormatter'],
'numfmt_get_locale' => ['string', 'formatter'=>'NumberFormatter', 'type='=>'int'],
'numfmt_get_pattern' => ['string|false', 'formatter'=>'NumberFormatter'],
'numfmt_get_symbol' => ['string|false', 'formatter'=>'NumberFormatter', 'symbol'=>'int'],
'numfmt_get_text_attribute' => ['string|false', 'formatter'=>'NumberFormatter', 'attribute'=>'int'],
'numfmt_parse' => ['float|int|false', 'formatter'=>'NumberFormatter', 'string'=>'string', 'type='=>'int', '&rw_offset='=>'int'],
'numfmt_parse_currency' => ['float|false', 'formatter'=>'NumberFormatter', 'string'=>'string', '&w_currency'=>'string', '&rw_offset='=>'int'],
'numfmt_set_attribute' => ['bool', 'formatter'=>'NumberFormatter', 'attribute'=>'int', 'value'=>'int'],
'numfmt_set_pattern' => ['bool', 'formatter'=>'NumberFormatter', 'pattern'=>'string'],
'numfmt_set_symbol' => ['bool', 'formatter'=>'NumberFormatter', 'symbol'=>'int', 'value'=>'string'],
'numfmt_set_text_attribute' => ['bool', 'formatter'=>'NumberFormatter', 'attribute'=>'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', 'http_method='=>'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', 'http_method='=>'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', 'enable='=>'int'],
'ob_inflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_list_handlers' => ['false|list<string>'],
'ob_start' => ['bool', 'callback='=>'string|array|?callable', 'chunk_size='=>'int', 'flags='=>'int'],
'ob_tidyhandler' => ['string', 'input'=>'string', 'mode='=>'int'],
'oci_bind_array_by_name' => ['bool', 'statement'=>'resource', 'param'=>'string', '&rw_var'=>'array', 'max_array_length'=>'int', 'max_item_length='=>'int', 'type='=>'int'],
'oci_bind_by_name' => ['bool', 'statement'=>'resource', 'param'=>'string', '&rw_var'=>'mixed', 'max_length='=>'int', 'type='=>'int'],
'oci_cancel' => ['bool', 'statement'=>'resource'],
'oci_client_version' => ['string'],
'oci_close' => ['bool', 'connection'=>'resource'],
'OCICollection::append' => ['bool', 'value'=>'mixed'],
'OCICollection::assign' => ['bool', 'from'=>'OCI_Collection'],
'OCICollection::assignElem' => ['bool', 'index'=>'int', 'value'=>'mixed'],
'OCICollection::free' => ['bool'],
'OCICollection::getElem' => ['mixed', 'index'=>'int'],
'OCICollection::max' => ['int|false'],
'OCICollection::size' => ['int|false'],
'OCICollection::trim' => ['bool', 'num'=>'int'],
'oci_collection_append' => ['bool', 'collection'=>'string'],
'oci_collection_assign' => ['bool', 'to'=>'object'],
'oci_collection_element_assign' => ['bool', 'collection'=>'int', 'index'=>'string'],
'oci_collection_element_get' => ['string', 'collection'=>'int'],
'oci_collection_max' => ['int'],
'oci_collection_size' => ['int'],
'oci_collection_trim' => ['bool', 'collection'=>'int'],
'oci_commit' => ['bool', 'connection'=>'resource'],
'oci_connect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_define_by_name' => ['bool', 'statement'=>'resource', 'column'=>'string', '&w_var'=>'mixed', 'type='=>'int'],
'oci_error' => ['array|false', 'connection_or_statement='=>'resource'],
'oci_execute' => ['bool', 'statement'=>'resource', 'mode='=>'int'],
'oci_fetch' => ['bool', 'statement'=>'resource'],
'oci_fetch_all' => ['int|false', 'statement'=>'resource', '&w_output'=>'array', 'offset='=>'int', 'limit='=>'int', 'flags='=>'int'],
'oci_fetch_array' => ['array|false', 'statement'=>'resource', 'mode='=>'int'],
'oci_fetch_assoc' => ['array|false', 'statement'=>'resource'],
'oci_fetch_object' => ['object|false', 'statement'=>'resource'],
'oci_fetch_row' => ['array|false', 'statement'=>'resource'],
'oci_field_is_null' => ['bool', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_name' => ['string|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_precision' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_scale' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_size' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_type' => ['mixed|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_type_raw' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_free_collection' => ['bool'],
'oci_free_cursor' => ['bool', 'statement'=>'resource'],
'oci_free_descriptor' => ['bool'],
'oci_free_statement' => ['bool', 'statement'=>'resource'],
'oci_get_implicit' => ['bool', 'stmt'=>''],
'oci_get_implicit_resultset' => ['resource|false', 'statement'=>'resource'],
'oci_internal_debug' => ['void', 'onoff'=>'bool'],
'OCILob::append' => ['bool', 'lob_from'=>'OCILob'],
'OCILob::close' => ['bool'],
'OCILob::eof' => ['bool'],
'OCILob::erase' => ['int|false', 'offset='=>'int', 'length='=>'int'],
'OCILob::export' => ['bool', 'filename'=>'string', 'start='=>'int', 'length='=>'int'],
'OCILob::flush' => ['bool', 'flag='=>'int'],
'OCILob::free' => ['bool'],
'OCILob::getbuffering' => ['bool'],
'OCILob::import' => ['bool', 'filename'=>'string'],
'OCILob::load' => ['string|false'],
'OCILob::read' => ['string|false', 'length'=>'int'],
'OCILob::rewind' => ['bool'],
'OCILob::save' => ['bool', 'data'=>'string', 'offset='=>'int'],
'OCILob::savefile' => ['bool', 'filename'=>''],
'OCILob::seek' => ['bool', 'offset'=>'int', 'whence='=>'int'],
'OCILob::setbuffering' => ['bool', 'on_off'=>'bool'],
'OCILob::size' => ['int|false'],
'OCILob::tell' => ['int|false'],
'OCILob::truncate' => ['bool', 'length='=>'int'],
'OCILob::write' => ['int|false', 'data'=>'string', 'length='=>'int'],
'OCILob::writeTemporary' => ['bool', 'data'=>'string', 'lob_type='=>'int'],
'OCILob::writetofile' => ['bool', 'filename'=>'', 'start'=>'', 'length'=>''],
'oci_lob_append' => ['bool', 'to'=>'object'],
'oci_lob_close' => ['bool'],
'oci_lob_copy' => ['bool', 'to'=>'OCILob', 'from'=>'OCILob', 'length='=>'int'],
'oci_lob_eof' => ['bool'],
'oci_lob_erase' => ['int', 'lob'=>'int', 'offset'=>'int'],
'oci_lob_export' => ['bool', 'lob'=>'string', 'filename'=>'int', 'offset'=>'int'],
'oci_lob_flush' => ['bool', 'lob'=>'int'],
'oci_lob_import' => ['bool', 'lob'=>'string'],
'oci_lob_is_equal' => ['bool', 'lob1'=>'OCILob', 'lob2'=>'OCILob'],
'oci_lob_load' => ['string'],
'oci_lob_read' => ['string', 'lob'=>'int'],
'oci_lob_rewind' => ['bool'],
'oci_lob_save' => ['bool', 'lob'=>'string', 'data'=>'int'],
'oci_lob_seek' => ['bool', 'lob'=>'int', 'offset'=>'int'],
'oci_lob_size' => ['int'],
'oci_lob_tell' => ['int'],
'oci_lob_truncate' => ['bool', 'lob'=>'int'],
'oci_lob_write' => ['int', 'lob'=>'string', 'data'=>'int'],
'oci_lob_write_temporary' => ['bool', 'value'=>'string', 'lob_type'=>'int'],
'oci_new_collection' => ['OCICollection|false', 'connection'=>'resource', 'type_name'=>'string', 'schema='=>'string'],
'oci_new_connect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_new_cursor' => ['resource|false', 'connection'=>'resource'],
'oci_new_descriptor' => ['OCILob|false', 'connection'=>'resource', 'type='=>'int'],
'oci_num_fields' => ['int|false', 'statement'=>'resource'],
'oci_num_rows' => ['int|false', 'statement'=>'resource'],
'oci_parse' => ['resource|false', 'connection'=>'resource', 'sql'=>'string'],
'oci_password_change' => ['bool', 'connection'=>'resource', 'username'=>'string', 'old_password'=>'string', 'new_password'=>'string'],
'oci_pconnect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_register_taf_callback' => ['bool', 'connection'=>'resource', 'callback='=>'callable'],
'oci_result' => ['mixed|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_rollback' => ['bool', 'connection'=>'resource'],
'oci_server_version' => ['string|false', 'connection'=>'resource'],
'oci_set_action' => ['bool', 'connection'=>'resource', 'action'=>'string'],
'oci_set_call_timeout' => ['bool', 'connection'=>'resource', 'timeout'=>'int'],
'oci_set_client_identifier' => ['bool', 'connection'=>'resource', 'client_id'=>'string'],
'oci_set_client_info' => ['bool', 'connection'=>'resource', 'client_info'=>'string'],
'oci_set_db_operation' => ['bool', 'connection'=>'resource', 'action'=>'string'],
'oci_set_edition' => ['bool', 'edition'=>'string'],
'oci_set_module_name' => ['bool', 'connection'=>'resource', 'name'=>'string'],
'oci_set_prefetch' => ['bool', 'statement'=>'resource', 'rows'=>'int'],
'oci_statement_type' => ['string|false', 'statement'=>'resource'],
'oci_unregister_taf_callback' => ['bool', 'connection'=>'resource'],
'ocifetchinto' => ['int|bool', 'statement'=>'resource', '&w_result'=>'array', 'mode='=>'int'],
'ocigetbufferinglob' => ['bool'],
'ocisetbufferinglob' => ['bool', 'lob'=>'bool'],
'octdec' => ['int|float', 'octal_string'=>'string'],
'odbc_autocommit' => ['mixed', 'odbc'=>'resource', 'enable='=>'bool'],
'odbc_binmode' => ['bool', 'statement'=>'resource', 'mode'=>'int'],
'odbc_close' => ['void', 'odbc'=>'resource'],
'odbc_close_all' => ['void'],
'odbc_columnprivileges' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'column'=>'string'],
'odbc_columns' => ['resource|false', 'odbc'=>'resource', 'catalog='=>'string', 'schema='=>'string', 'table='=>'string', 'column='=>'string'],
'odbc_commit' => ['bool', 'odbc'=>'resource'],
'odbc_connect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_cursor' => ['string', 'statement'=>'resource'],
'odbc_data_source' => ['array|false', 'odbc'=>'resource', 'fetch_type'=>'int'],
'odbc_do' => ['resource', 'odbc'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_error' => ['string', 'odbc='=>'resource'],
'odbc_errormsg' => ['string', 'odbc='=>'resource'],
'odbc_exec' => ['resource', 'odbc'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_execute' => ['bool', 'statement'=>'resource', 'params='=>'array'],
'odbc_fetch_array' => ['array|false', 'statement'=>'resource', 'row='=>'int'],
'odbc_fetch_into' => ['int', 'statement'=>'resource', '&w_array'=>'array', 'row='=>'int'],
'odbc_fetch_object' => ['object|false', 'statement'=>'resource', 'row='=>'int'],
'odbc_fetch_row' => ['bool', 'statement'=>'resource', 'row='=>'int'],
'odbc_field_len' => ['int|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_name' => ['string|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_num' => ['int|false', 'statement'=>'resource', 'field'=>'string'],
'odbc_field_precision' => ['int', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_scale' => ['int|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_type' => ['string|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_foreignkeys' => ['resource|false', 'odbc'=>'resource', 'pk_catalog'=>'string', 'pk_schema'=>'string', 'pk_table'=>'string', 'fk_catalog'=>'string', 'fk_schema'=>'string', 'fk_table'=>'string'],
'odbc_free_result' => ['bool', 'statement'=>'resource'],
'odbc_gettypeinfo' => ['resource', 'odbc'=>'resource', 'data_type='=>'int'],
'odbc_longreadlen' => ['bool', 'statement'=>'resource', 'length'=>'int'],
'odbc_next_result' => ['bool', 'statement'=>'resource'],
'odbc_num_fields' => ['int', 'statement'=>'resource'],
'odbc_num_rows' => ['int', 'statement'=>'resource'],
'odbc_pconnect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_prepare' => ['resource|false', 'odbc'=>'resource', 'query'=>'string'],
'odbc_primarykeys' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string'],
'odbc_procedurecolumns' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'procedure'=>'string', 'column'=>'string'],
'odbc_procedures' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'procedure'=>'string'],
'odbc_result' => ['mixed|false', 'statement'=>'resource', 'field'=>'mixed'],
'odbc_result_all' => ['int|false', 'statement'=>'resource', 'format='=>'string'],
'odbc_rollback' => ['bool', 'odbc'=>'resource'],
'odbc_setoption' => ['bool', 'odbc'=>'resource', 'which'=>'int', 'option'=>'int', 'value'=>'int'],
'odbc_specialcolumns' => ['resource|false', 'odbc'=>'resource', 'type'=>'int', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'scope'=>'int', 'nullable'=>'int'],
'odbc_statistics' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'unique'=>'int', 'accuracy'=>'int'],
'odbc_tableprivileges' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string'],
'odbc_tables' => ['resource|false', 'odbc'=>'resource', 'catalog='=>'string', 'schema='=>'string', 'table='=>'string', 'types='=>'string'],
'opcache_compile_file' => ['bool', 'filename'=>'string'],
'opcache_get_configuration' => ['array'],
'opcache_get_status' => ['array|false', 'include_scripts='=>'bool'],
'opcache_invalidate' => ['bool', 'filename'=>'string', 'force='=>'bool'],
'opcache_is_script_cached' => ['bool', 'filename'=>'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|false', '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', 'directory'=>'string', 'context='=>'resource'],
'openlog' => ['bool', 'prefix'=>'string', 'flags'=>'int', 'facility'=>'int'],
'openssl_cipher_iv_length' => ['int|false', 'cipher_algo'=>'string'],
'openssl_csr_export' => ['bool', 'csr'=>'string|resource', '&w_output'=>'string', 'no_text='=>'bool'],
'openssl_csr_export_to_file' => ['bool', 'csr'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_csr_get_public_key' => ['resource|false', 'csr'=>'string|resource', 'short_names='=>'bool'],
'openssl_csr_get_subject' => ['array|false', 'csr'=>'string|resource', 'short_names='=>'bool'],
'openssl_csr_new' => ['resource|false', 'distinguished_names'=>'array', '&w_private_key'=>'resource', 'options='=>'array', 'extra_attributes='=>'array'],
'openssl_csr_sign' => ['resource|false', 'csr'=>'string|resource', 'ca_certificate'=>'string|resource|null', 'private_key'=>'string|resource|array', 'days'=>'int', 'options='=>'array', 'serial='=>'int'],
'openssl_decrypt' => ['string|false', 'data'=>'string', 'cipher_algo'=>'string', 'passphrase'=>'string', 'options='=>'int', 'iv='=>'string', 'tag='=>'string', 'aad='=>'string'],
'openssl_dh_compute_key' => ['string|false', 'public_key'=>'string', 'private_key'=>'resource'],
'openssl_digest' => ['string|false', 'data'=>'string', 'digest_algo'=>'string', 'binary='=>'bool'],
'openssl_encrypt' => ['string|false', 'data'=>'string', 'cipher_algo'=>'string', 'passphrase'=>'string', 'options='=>'int', 'iv='=>'string', '&w_tag='=>'string', 'aad='=>'string', 'tag_length='=>'int'],
'openssl_error_string' => ['string|false'],
'openssl_free_key' => ['void', 'key'=>'resource'],
'openssl_get_cert_locations' => ['array'],
'openssl_get_cipher_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_curve_names' => ['list<string>'],
'openssl_get_md_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_privatekey' => ['resource|false', 'private_key'=>'string', 'passphrase='=>'string'],
'openssl_get_publickey' => ['resource|false', 'public_key'=>'resource|string'],
'openssl_open' => ['bool', 'data'=>'string', '&w_output'=>'string', 'encrypted_key'=>'string', 'private_key'=>'string|array|resource', 'cipher_algo='=>'string', 'iv='=>'string'],
'openssl_pbkdf2' => ['string|false', 'password'=>'string', 'salt'=>'string', 'key_length'=>'int', 'iterations'=>'int', 'digest_algo='=>'string'],
'openssl_pkcs12_export' => ['bool', 'certificate'=>'string|resource', '&w_output'=>'string', 'private_key'=>'string|array|resource', 'passphrase'=>'string', 'options='=>'array'],
'openssl_pkcs12_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'private_key'=>'string|array|resource', 'passphrase'=>'string', 'options='=>'array'],
'openssl_pkcs12_read' => ['bool', 'pkcs12'=>'string', '&w_certificates'=>'array', 'passphrase'=>'string'],
'openssl_pkcs7_decrypt' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource', 'private_key='=>'string|resource|array'],
'openssl_pkcs7_encrypt' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'cipher_algo='=>'int'],
'openssl_pkcs7_read' => ['bool', 'input_filename'=>'string', '&w_certificates'=>'array'],
'openssl_pkcs7_sign' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource', 'private_key'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'untrusted_certificates_filename='=>'string'],
'openssl_pkcs7_verify' => ['bool|int', 'input_filename'=>'string', 'flags'=>'int', 'signers_certificates_filename='=>'string', 'ca_info='=>'array', 'untrusted_certificates_filename='=>'string', 'content='=>'string', 'output_filename='=>'string'],
'openssl_pkey_derive' => ['string|false', 'public_key'=>'mixed', 'private_key'=>'mixed', 'key_length='=>'?int'],
'openssl_pkey_export' => ['bool', 'key'=>'resource', '&w_output'=>'string', 'passphrase='=>'string|null', 'options='=>'array'],
'openssl_pkey_export_to_file' => ['bool', 'key'=>'resource|string|array', 'output_filename'=>'string', 'passphrase='=>'string|null', 'options='=>'array'],
'openssl_pkey_free' => ['void', 'key'=>'resource'],
'openssl_pkey_get_details' => ['array|false', 'key'=>'resource'],
'openssl_pkey_get_private' => ['resource|false', 'private_key'=>'string', 'passphrase='=>'string'],
'openssl_pkey_get_public' => ['resource|false', 'public_key'=>'resource|string'],
'openssl_pkey_new' => ['resource|false', 'options='=>'array'],
'openssl_private_decrypt' => ['bool', 'data'=>'string', '&w_decrypted_data'=>'string', 'private_key'=>'string|resource|array', 'padding='=>'int'],
'openssl_private_encrypt' => ['bool', 'data'=>'string', '&w_encrypted_data'=>'string', 'private_key'=>'string|resource|array', 'padding='=>'int'],
'openssl_public_decrypt' => ['bool', 'data'=>'string', '&w_decrypted_data'=>'string', 'public_key'=>'string|resource', 'padding='=>'int'],
'openssl_public_encrypt' => ['bool', 'data'=>'string', '&w_encrypted_data'=>'string', 'public_key'=>'string|resource', 'padding='=>'int'],
'openssl_random_pseudo_bytes' => ['string|false', 'length'=>'int', '&w_strong_result='=>'bool'],
'openssl_seal' => ['int|false', 'data'=>'string', '&w_sealed_data'=>'string', '&w_encrypted_keys'=>'array', 'public_key'=>'array', 'cipher_algo='=>'string', '&rw_iv='=>'string'],
'openssl_sign' => ['bool', 'data'=>'string', '&w_signature'=>'string', 'private_key'=>'resource|string', 'algorithm='=>'int|string'],
'openssl_spki_export' => ['?string', 'spki'=>'string'],
'openssl_spki_export_challenge' => ['?string', 'spki'=>'string'],
'openssl_spki_new' => ['?string', 'private_key'=>'resource', 'challenge'=>'string', 'digest_algo='=>'int'],
'openssl_spki_verify' => ['bool', 'spki'=>'string'],
'openssl_verify' => ['-1|0|1', 'data'=>'string', 'signature'=>'string', 'public_key'=>'resource|string', 'algorithm='=>'int|string'],
'openssl_x509_check_private_key' => ['bool', 'certificate'=>'string|resource', 'private_key'=>'string|resource|array'],
'openssl_x509_checkpurpose' => ['bool|int', 'certificate'=>'string|resource', 'purpose'=>'int', 'ca_info='=>'array', 'untrusted_certificates_file='=>'string'],
'openssl_x509_export' => ['bool', 'certificate'=>'string|resource', '&w_output'=>'string', 'no_text='=>'bool'],
'openssl_x509_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_x509_fingerprint' => ['string|false', 'certificate'=>'string|resource', 'digest_algo='=>'string', 'binary='=>'bool'],
'openssl_x509_free' => ['void', 'certificate'=>'resource'],
'openssl_x509_parse' => ['array|false', 'certificate'=>'string|resource', 'short_names='=>'bool'],
'openssl_x509_read' => ['resource|false', 'certificate'=>'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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', '...values='=>'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::kill' => ['void'],
'parallel\Runtime::run' => ['?parallel\Future', 'closure'=>'Closure', 'args='=>'array'],
'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', 'string'=>'string', '&w_result'=>'array'],
'parse_url' => ['mixed|false', 'url'=>'string', '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' => ['list<array<string,mixed>>'],
'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_result_code='=>'int'],
'password_get_info' => ['array', 'hash'=>'string'],
'password_hash' => ['string', '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', 'flags='=>'int'],
'pclose' => ['int', 'handle'=>'resource'],
'pcnlt_sigwaitinfo' => ['int', 'set'=>'array', '&w_siginfo'=>'array'],
'pcntl_alarm' => ['int', 'seconds'=>'int'],
'pcntl_async_signals' => ['bool', 'enable='=>'bool'],
'pcntl_errno' => ['int'],
'pcntl_exec' => ['null|false', 'path'=>'string', 'args='=>'array', 'env_vars='=>'array'],
'pcntl_fork' => ['int'],
'pcntl_get_last_error' => ['int'],
'pcntl_getpriority' => ['int', 'process_id='=>'int', 'mode='=>'int'],
'pcntl_setpriority' => ['bool', 'priority'=>'int', 'process_id='=>'int', 'mode='=>'int'],
'pcntl_signal' => ['bool', 'signal'=>'int', 'handler'=>'callable():void|callable(int):void|callable(int,array):void|int', 'restart_syscalls='=>'bool'],
'pcntl_signal_dispatch' => ['bool'],
'pcntl_signal_get_handler' => ['int|string', 'signal'=>'int'],
'pcntl_sigprocmask' => ['bool', 'mode'=>'int', 'signals'=>'array', '&w_old_signals='=>'array'],
'pcntl_sigtimedwait' => ['int', 'signals'=>'array', '&w_info='=>'array', 'seconds='=>'int', 'nanoseconds='=>'int'],
'pcntl_sigwaitinfo' => ['int', 'signals'=>'array', '&w_info='=>'array'],
'pcntl_strerror' => ['string|false', 'error_code'=>'int'],
'pcntl_wait' => ['int', '&w_status'=>'int', 'flags='=>'int', '&w_resource_usage='=>'array'],
'pcntl_waitpid' => ['int', 'process_id'=>'int', '&w_status'=>'int', 'flags='=>'int', '&w_resource_usage='=>'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', 'length'=>'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', 'length'=>'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' => ['list<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{message:string,pid:int,payload?:string}|false', 'result_type='=>'PDO::FETCH_*', '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' => ['list<array<string,mixed>>'],
'PDOException::getTraceAsString' => ['string'],
'PDOStatement::__sleep' => ['list<string>'],
'PDOStatement::__wakeup' => ['void'],
'PDOStatement::bindColumn' => ['bool', 'column'=>'mixed', '&rw_var'=>'mixed', 'type='=>'int', 'maxLength='=>'int', 'driverOptions='=>'mixed'],
'PDOStatement::bindParam' => ['bool', 'param,'=>'string|int', '&rw_var'=>'mixed', 'type='=>'int', 'maxLength='=>'int', 'driverOptions='=>'mixed'],
'PDOStatement::bindValue' => ['bool', 'param'=>'string|int', 'value'=>'mixed', 'type='=>'int'],
'PDOStatement::closeCursor' => ['bool'],
'PDOStatement::columnCount' => ['int'],
'PDOStatement::debugDumpParams' => ['bool|null'],
'PDOStatement::errorCode' => ['string|null'],
'PDOStatement::errorInfo' => ['array'],
'PDOStatement::execute' => ['bool', 'params='=>'?array'],
'PDOStatement::fetch' => ['mixed', 'mode='=>'int', 'cursorOrientation='=>'int', 'cursorOffset='=>'int'],
'PDOStatement::fetchAll' => ['array|false', 'mode='=>'int', '...args='=>'mixed'],
'PDOStatement::fetchColumn' => ['mixed', 'column='=>'int'],
'PDOStatement::fetchObject' => ['object|false', 'class='=>'?string', 'ctorArgs='=>'?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', '...args='=> 'mixed'],
'pfsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_error_code='=>'int', '&w_error_message='=>'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', 'flags='=>'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', 'connection'=>'resource', 'table_name'=>'string', 'values'=>'array', 'flags='=>'int'],
'pg_copy_from' => ['bool', 'connection'=>'resource', 'table_name'=>'string', 'rows'=>'array', 'separator='=>'string', 'null_as='=>'string'],
'pg_copy_to' => ['array|false', 'connection'=>'resource', 'table_name'=>'string', 'separator='=>'string', 'null_as='=>'string'],
'pg_dbname' => ['string|false', 'connection='=>'resource'],
'pg_delete' => ['string|bool', 'connection'=>'resource', 'table_name'=>'string', 'conditions'=>'array', 'flags='=>'int'],
'pg_end_copy' => ['bool', 'connection='=>'resource'],
'pg_escape_bytea' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_bytea\'1' => ['string', 'connection'=>'string'],
'pg_escape_identifier' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_identifier\'1' => ['string', 'connection'=>'string'],
'pg_escape_literal' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_literal\'1' => ['string', 'connection'=>'string'],
'pg_escape_string' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_string\'1' => ['string', 'connection'=>'string'],
'pg_exec' => ['resource|false', 'connection'=>'resource', 'query'=>'string'],
'pg_execute' => ['resource|false', 'connection'=>'resource', 'statement_name'=>'string', 'params'=>'array'],
'pg_execute\'1' => ['resource|false', 'connection'=>'string', 'statement_name'=>'array'],
'pg_fetch_all' => ['array<array>|false', 'result'=>'resource', 'result_type='=>'int'],
'pg_fetch_all_columns' => ['array|false', 'result'=>'resource', 'field='=>'int'],
'pg_fetch_array' => ['array<string|null>|false', 'result'=>'resource', 'row='=>'?int', 'mode='=>'int'],
'pg_fetch_assoc' => ['array<string, mixed>|false', 'result'=>'resource', 'row='=>'?int'],
'pg_fetch_object' => ['object', 'result'=>'resource', 'row='=>'?int', 'class='=>'int'],
'pg_fetch_object\'1' => ['object', 'result'=>'resource', 'row='=>'?int', 'class='=>'string', 'constructor_args='=>'array'],
'pg_fetch_result' => ['string', 'result'=>'resource', 'row'=>'string|int'],
'pg_fetch_result\'1' => ['string', 'result'=>'resource', 'row'=>'?int', 'field'=>'string|int'],
'pg_fetch_row' => ['array', 'result'=>'resource', 'row='=>'?int', 'mode='=>'int'],
'pg_field_is_null' => ['int', 'result'=>'resource', 'row'=>'string|int'],
'pg_field_is_null\'1' => ['int', 'result'=>'resource', 'row'=>'int', 'field'=>'string|int'],
'pg_field_name' => ['string|false', 'result'=>'resource', 'field'=>'int'],
'pg_field_num' => ['int', 'result'=>'resource', 'field'=>'string'],
'pg_field_prtlen' => ['int|false', 'result'=>'resource', 'row'=>''],
'pg_field_prtlen\'1' => ['int', 'result'=>'resource', 'row'=>'int', 'field'=>'string|int'],
'pg_field_size' => ['int', 'result'=>'resource', 'field'=>'int'],
'pg_field_table' => ['mixed|false', 'result'=>'resource', 'field'=>'int', 'oid_only='=>'bool'],
'pg_field_type' => ['string|false', 'result'=>'resource', 'field'=>'int'],
'pg_field_type_oid' => ['int|false', 'result'=>'resource', 'field'=>'int'],
'pg_flush' => ['mixed', 'connection'=>'resource'],
'pg_free_result' => ['bool', 'result'=>'resource'],
'pg_get_notify' => ['array|false', 'result'=>'resource', 'mode='=>'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', 'connection'=>'resource', 'table_name'=>'string', 'values'=>'array', 'flags='=>'int'],
'pg_last_error' => ['string', 'connection='=>'resource', 'operation='=>'int'],
'pg_last_notice' => ['string|array|bool', 'connection'=>'resource', 'mode='=>'int'],
'pg_last_oid' => ['string', 'result'=>'resource'],
'pg_lo_close' => ['bool', 'lob'=>'resource'],
'pg_lo_create' => ['int|false', 'connection='=>'resource', 'oid='=>''],
'pg_lo_export' => ['bool', 'connection'=>'resource', 'oid'=>'int', 'filename'=>'string'],
'pg_lo_export\'1' => ['bool', 'connection'=>'int', 'oid'=>'string'],
'pg_lo_import' => ['int', 'connection'=>'resource', 'filename'=>'string', 'oid'=>''],
'pg_lo_import\'1' => ['int', 'connection'=>'string', 'filename'=>''],
'pg_lo_open' => ['resource|false', 'connection'=>'resource', 'oid'=>'int', 'mode'=>'string'],
'pg_lo_read' => ['string', 'lob'=>'resource', 'length='=>'int'],
'pg_lo_read_all' => ['int|false', 'lob'=>'resource'],
'pg_lo_seek' => ['bool', 'lob'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'pg_lo_tell' => ['int', 'lob'=>'resource'],
'pg_lo_truncate' => ['bool', 'lob'=>'resource', 'size'=>'int'],
'pg_lo_unlink' => ['bool', 'connection'=>'resource', 'oid'=>'int'],
'pg_lo_write' => ['int|false', 'lob'=>'resource', 'data'=>'string', 'length='=>'int'],
'pg_meta_data' => ['array', 'connection'=>'resource', 'table_name'=>'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', 'name'=>'string'],
'pg_parameter_status\'1' => ['string|false', 'connection'=>'string'],
'pg_pconnect' => ['resource|false', 'connection_string'=>'string', 'flags='=>'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', 'statement_name'=>'string', 'query'=>'string'],
'pg_prepare\'1' => ['resource|false', 'connection'=>'string', 'statement_name'=>'string'],
'pg_put_line' => ['bool', 'connection'=>'resource', 'query'=>'string'],
'pg_put_line\'1' => ['bool', 'connection'=>'string'],
'pg_query' => ['resource|false', 'connection'=>'resource', 'query'=>'string'],
'pg_query\'1' => ['resource|false', 'connection'=>'string'],
'pg_query_params' => ['resource|false', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_query_params\'1' => ['resource|false', 'connection'=>'string', 'query'=>'array'],
'pg_result_error' => ['string|false', 'result'=>'resource'],
'pg_result_error_field' => ['string|?false', 'result'=>'resource', 'field_code'=>'int'],
'pg_result_seek' => ['bool', 'result'=>'resource', 'row'=>'int'],
'pg_result_status' => ['mixed', 'result'=>'resource', 'mode='=>'int'],
'pg_select' => ['bool|string', 'connection'=>'resource', 'table_name'=>'string', 'assoc_array'=>'array', 'options='=>'int', 'result_type='=>'int'],
'pg_send_execute' => ['bool', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_send_prepare' => ['bool', 'connection'=>'resource', 'statement_name'=>'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', 'connection'=>'string'],
'pg_set_error_verbosity' => ['int', 'connection'=>'resource', 'verbosity'=>'int'],
'pg_set_error_verbosity\'1' => ['int', 'connection'=>'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', 'string'=>'string'],
'pg_untrace' => ['bool', 'connection='=>'resource'],
'pg_untrace\'1' => ['bool'],
'pg_update' => ['mixed', 'connection'=>'resource', 'table_name'=>'string', 'values'=>'array', 'conditions'=>'array', 'flags='=>'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' => ['Phar', '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' => ['Phar', '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{hash:string, hash_type:string}'],
'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', 'length='=>'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' => ['PharData', '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' => ['PharData', '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::offsetExists' => ['bool', 'offset'=>'string'],
'PharData::offsetGet' => ['PharFileInfo', 'offset'=>'string'],
'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', 'length='=>'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', 'filename'=>'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', 'flags='=>'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', 'string'=>'string'],
'phpdbg_start_oplog' => ['void'],
'phpinfo' => ['bool', 'flags='=>'int'],
'PhpToken::tokenize' => ['list<PhpToken>', 'code'=>'string', 'flags='=>'int'],
'PhpToken::is' => ['bool', 'kind'=>'string|int|string[]|int[]'],
'PhpToken::isIgnorable' => ['bool'],
'PhpToken::getTokenName' => ['string'],
'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'],
'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'=>'array'],
'posix_access' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'posix_ctermid' => ['string|false'],
'posix_errno' => ['int'],
'posix_get_last_error' => ['int'],
'posix_getcwd' => ['string|false'],
'posix_getegid' => ['int'],
'posix_geteuid' => ['int'],
'posix_getgid' => ['int'],
'posix_getgrgid' => ['array{name: string, passwd: string, gid: int, members: list<string>}|false', 'group_id'=>'int'],
'posix_getgrnam' => ['array{name: string, passwd: string, gid: int, members: list<string>}|false', 'name'=>'string'],
'posix_getgroups' => ['list<int>|false'],
'posix_getlogin' => ['string|false'],
'posix_getpgid' => ['int|false', 'process_id'=>'int'],
'posix_getpgrp' => ['int'],
'posix_getpid' => ['int'],
'posix_getppid' => ['int'],
'posix_getpwnam' => ['array{name: string, passwd: string, uid: int, gid: int, gecos: string, dir: string, shell: string}|false', 'username'=>'string'],
'posix_getpwuid' => ['array{name: string, passwd: string, uid: int, gid: int, gecos: string, dir: string, shell: string}|false', 'user_id'=>'int'],
'posix_getrlimit' => ['array{"soft core": string, "hard core": string, "soft data": string, "hard data": string, "soft stack": integer, "hard stack": string, "soft totalmem": string, "hard totalmem": string, "soft rss": string, "hard rss": string, "soft maxproc": integer, "hard maxproc": integer, "soft memlock": integer, "hard memlock": integer, "soft cpu": string, "hard cpu": string, "soft filesize": string, "hard filesize": string, "soft openfiles": integer, "hard openfiles": integer}|false'],
'posix_getsid' => ['int|false', 'process_id'=>'int'],
'posix_getuid' => ['int'],
'posix_initgroups' => ['bool', 'username'=>'string', 'group_id'=>'int'],
'posix_isatty' => ['bool', 'file_descriptor'=>'resource|int'],
'posix_kill' => ['bool', 'process_id'=>'int', 'signal'=>'int'],
'posix_mkfifo' => ['bool', 'filename'=>'string', 'permissions'=>'int'],
'posix_mknod' => ['bool', 'filename'=>'string', 'flags'=>'int', 'major='=>'int', 'minor='=>'int'],
'posix_setegid' => ['bool', 'group_id'=>'int'],
'posix_seteuid' => ['bool', 'user_id'=>'int'],
'posix_setgid' => ['bool', 'group_id'=>'int'],
'posix_setpgid' => ['bool', 'process_id'=>'int', 'process_group_id'=>'int'],
'posix_setrlimit' => ['bool', 'resource'=>'int', 'soft_limit'=>'int', 'hard_limit'=>'int'],
'posix_setsid' => ['int'],
'posix_setuid' => ['bool', 'user_id'=>'int'],
'posix_strerror' => ['string', 'error_code'=>'int'],
'posix_times' => ['array{ticks: int, utime: int, stime: int, cutime: int, cstime: int}|false'],
'posix_ttyname' => ['string|false', 'file_descriptor'=>'resource|int'],
'posix_uname' => ['array{sysname: string, nodename: string, release: string, version: string, machine: string, domainname: string}|false'],
'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', 'num'=>'int|float', 'exponent'=>'int|float'],
'preg_filter' => ['null|string|string[]', 'pattern'=>'mixed', 'replacement'=>'mixed', 'subject'=>'mixed', 'limit='=>'int', '&w_count='=>'int'],
'preg_grep' => ['array|false', 'pattern'=>'string', 'array'=>'array', 'flags='=>'int'],
'preg_last_error' => ['int'],
'preg_match' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'string[]', 'flags='=>'0|', 'offset='=>'int'],
'preg_match\'1' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_match_all' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_quote' => ['string', 'str'=>'string', 'delimiter='=>'string'],
'preg_replace' => ['string|string[]|null', 'pattern'=>'string|array', 'replacement'=>'string|array', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback' => ['string|null', 'pattern'=>'string|array', 'callback'=>'callable(string[]):string', 'subject'=>'string', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback\'1' => ['string[]|null', 'pattern'=>'string|array', 'callback'=>'callable(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' => ['list<string>|false', 'pattern'=>'string', 'subject'=>'string', 'limit'=>'int', 'flags='=>'null'],
'preg_split\'1' => ['list<string>|list<list<string|int>>|false', 'pattern'=>'string', 'subject'=>'string', 'limit='=>'int', 'flags='=>'int'],
'prev' => ['mixed', '&r_array'=>'array|object'],
'print' => ['int', 'arg'=>'string'],
'print_r' => ['string', 'value'=>'mixed'],
'print_r\'1' => ['true', 'value'=>'mixed', 'return='=>'bool'],
'printf' => ['int', 'format'=>'string', '...values='=>'string|int|float'],
'proc_close' => ['int', 'process'=>'resource'],
'proc_get_status' => ['array{command: string, pid: int, running: bool, signaled: bool, stopped: bool, exitcode: int, termsig: int, stopsig: int}', 'process'=>'resource'],
'proc_nice' => ['bool', 'priority'=>'int'],
'proc_open' => ['resource|false', 'cmd'=>'string|array', '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'=>'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', 'value'=>'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', 'length'=>'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', 'length'=>'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', 'dictionary'=>'int', 'word'=>'string'],
'pspell_add_to_session' => ['bool', 'dictionary'=>'int', 'word'=>'string'],
'pspell_check' => ['bool', 'dictionary'=>'int', 'word'=>'string'],
'pspell_clear_session' => ['bool', 'dictionary'=>'int'],
'pspell_config_create' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string'],
'pspell_config_data_dir' => ['bool', 'config'=>'int', 'directory'=>'string'],
'pspell_config_dict_dir' => ['bool', 'config'=>'int', 'directory'=>'string'],
'pspell_config_ignore' => ['bool', 'config'=>'int', 'min_length'=>'int'],
'pspell_config_mode' => ['bool', 'config'=>'int', 'mode'=>'int'],
'pspell_config_personal' => ['bool', 'config'=>'int', 'filename'=>'string'],
'pspell_config_repl' => ['bool', 'config'=>'int', 'filename'=>'string'],
'pspell_config_runtogether' => ['bool', 'config'=>'int', 'allow'=>'bool'],
'pspell_config_save_repl' => ['bool', 'config'=>'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', 'filename'=>'string', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_save_wordlist' => ['bool', 'dictionary'=>'int'],
'pspell_store_replacement' => ['bool', 'dictionary'=>'int', 'misspelled'=>'string', 'correct'=>'string'],
'pspell_suggest' => ['array', 'dictionary'=>'int', 'word'=>'string'],
'putenv' => ['bool', 'assignment'=>'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', 'string'=>'string'],
'quoted_printable_encode' => ['string', 'string'=>'string'],
'quotemeta' => ['string', 'string'=>'string'],
'rad2deg' => ['float', 'num'=>'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|false', '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', 'start'=>'mixed', 'end'=>'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'RarException::getTraceAsString' => ['string'],
'RarException::isUsingExceptions' => ['bool'],
'RarException::setUsingExceptions' => ['RarEntry', 'using_exceptions'=>'bool'],
'rawurldecode' => ['string', 'string'=>'string'],
'rawurlencode' => ['string', 'string'=>'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::flush' => ['int', 'timeout_ms'=>'int'],
'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<string, string>'],
'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[]|null'],
'RdKafka\KafkaConsumer::commit' => ['void', 'message_or_offsets='=>'RdKafka\Message|RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::commitAsync' => ['void', 'message_or_offsets='=>'RdKafka\Message|RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::consume' => ['RdKafka\Message', 'timeout_ms'=>'int'],
'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\ProducerTopic::producev' => ['void', 'partition'=>'int', 'msgflags'=>'int', 'payload'=>'string', 'key='=>'?string', 'headers='=>'?array<string, string>', 'timestamp_ms='=>'?int', 'opaque='=>'?string'],
'RdKafka\Queue::__construct' => ['void'],
'RdKafka\Queue::consume' => ['?RdKafka\Message', 'timeout_ms'=>'string'],
'RdKafka\Topic::getName' => ['string'],
'RdKafka\TopicConf::dump' => ['array<string, string>'],
'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'],
'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|false', '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', 'callback'=>'callable'],
'readline_info' => ['mixed', 'var_name='=>'string', 'value='=>'string|int|bool'],
'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', 'path'=>'string'],
'realpath' => ['string|false', 'path'=>'string'],
'realpath_cache_get' => ['array'],
'realpath_cache_size' => ['int'],
'recode' => ['string', 'request'=>'string', 'string'=>'string'],
'recode_file' => ['bool', 'request'=>'string', 'input'=>'resource', 'output'=>'resource'],
'recode_string' => ['string|false', 'request'=>'string', 'string'=>'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' => ['Iterator'],
'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'=>'string[]', 'timeout'=>'int'],
'Redis::blPop\'1' => ['array', 'key'=>'string', 'timeout_or_key'=>'int|string', '...extra_args'=>'int|string'],
'Redis::brPop' => ['array', 'keys'=>'string[]', 'timeout'=>'int'],
'Redis::brPop\'1' => ['array', 'key'=>'string', 'timeout_or_key'=>'int|string', '...extra_args'=>'int|string'],
'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|false'],
'Redis::getHost' => ['string|false'],
'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', 'nodeParams'=>'string|array{0:string,1:int}'],
'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'=>'mixed', 'options='=>'array'],
'Redis::set\'1' => ['bool', 'key'=>'string', 'value'=>'mixed', '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'=>'mixed'],
'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|bool', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::sSize' => ['int', 'key'=>'string'],
'Redis::strLen' => ['int', 'key'=>'string'],
'Redis::subscribe' => ['mixed|null', 'channels'=>'array', 'callback'=>'string|array'],
'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::zAdd\'1' => ['int', 'options'=>'array', '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'=>'string', 'max'=>'string', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'string', 'end'=>'string', 'options='=>'array'],
'Redis::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zScan' => ['array|bool', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::zScore' => ['float|false', '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' => ['', 'callable='=>'callable'],
'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::unlink\'1' => ['int', 'key'=>'string[]'],
'RedisArray::unwatch' => [''],
'RedisCluster::__construct' => ['void', 'name'=>'?string', 'seeds='=>'string[]', 'timeout='=>'float', 'readTimeout='=>'float', 'persistent='=>'bool', 'auth='=>'?string'],
'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|array{0:string,1:int}'],
'RedisCluster::bgsave' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::bitCount' => ['int', 'key'=>'string'],
'RedisCluster::bitOp' => ['int', 'operation'=>'string', 'retKey'=>'string', 'key1'=>'string', '...other_keys='=>'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|array{0:string,1:int}', 'subCmd='=>'string', '...args='=>''],
'RedisCluster::close' => [''],
'RedisCluster::cluster' => ['mixed', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'arguments='=>'mixed'],
'RedisCluster::command' => ['array|bool'],
'RedisCluster::config' => ['array|bool', 'nodeParams'=>'string|array{0:string,1:int}', 'operation'=>'string', 'key'=>'string', 'value='=>'string'],
'RedisCluster::dbSize' => ['int', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::decr' => ['int', 'key'=>'string'],
'RedisCluster::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::del' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::del\'1' => ['int', 'key'=>'string[]'],
'RedisCluster::discard' => [''],
'RedisCluster::dump' => ['string|false', 'key'=>'string'],
'RedisCluster::echo' => ['string', 'nodeParams'=>'string|array{0:string,1:int}', '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|array{0:string,1:int}', 'async='=>'bool'],
'RedisCluster::flushDB' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}', 'async='=>'bool'],
'RedisCluster::geoAdd' => ['int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string', '...other_members='=>'float|string'],
'RedisCluster::geoDist' => ['', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'RedisCluster::geohash' => ['array<int,string>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'RedisCluster::geopos' => ['array<int,array{0:string,1:string}>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'RedisCluster::geoRadius' => ['', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'radiusUnit'=>'string', 'options='=>'array'],
'RedisCluster::geoRadiusByMember' => ['string[]', '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|false', 'key'=>'string', 'hashKey'=>'string', '...other_hashKeys='=>'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' => ['array', 'nodeParams'=>'string|array{0:string,1:int}', 'option='=>'string'],
'RedisCluster::keys' => ['array', 'pattern'=>'string'],
'RedisCluster::lastSave' => ['int', 'nodeParams'=>'string|array{0:string,1:int}'],
'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|false', '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|int|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|array{0:string,1:int}'],
'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', 'nodeParams'=>'string', 'keyword'=>'string', '...argument='=>'string'],
'RedisCluster::punSubscribe' => ['', 'channels'=>'', 'callback'=>''],
'RedisCluster::randomKey' => ['string', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::rawCommand' => ['mixed', 'nodeParams'=>'string|array{0:string,1:int}', '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'],
'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|array{0:string,1:int}'],
'RedisCluster::scan' => ['array|false', '&iterator'=>'int', 'nodeParams'=>'string|array{0:string,1:int}', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::sCard' => ['int', 'key'=>'string'],
'RedisCluster::script' => ['string|bool|array', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'script='=>'string', '...other_scripts='=>'string[]'],
'RedisCluster::sDiff' => ['list<string>', 'key1'=>'string', 'key2'=>'string', '...other_keys='=>'string'],
'RedisCluster::sDiffStore' => ['int', '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' => ['list<string>', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sInterStore' => ['int', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::slowLog' => ['array|int|bool', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'length='=>'int'],
'RedisCluster::sMembers' => ['list<string>', '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' => ['list<string>', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::sUnion\'1' => ['list<string>', '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'],
'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::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionClass::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionClass::getConstants' => ['array<string,mixed>', 'filter=' => '?int'],
'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' => ['list<class-string>'],
'ReflectionClass::getInterfaces' => ['array<class-string, ReflectionClass>'],
'ReflectionClass::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionClass::getMethods' => ['list<ReflectionMethod>', 'filter='=>'int'],
'ReflectionClass::getModifiers' => ['int'],
'ReflectionClass::getName' => ['class-string'],
'ReflectionClass::getNamespaceName' => ['string'],
'ReflectionClass::getParentClass' => ['ReflectionClass|false'],
'ReflectionClass::getProperties' => ['list<ReflectionProperty>', 'filter='=>'int'],
'ReflectionClass::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionClass::getReflectionConstant' => ['ReflectionClassConstant|false', 'name'=>'string'],
'ReflectionClass::getReflectionConstants' => ['list<ReflectionClassConstant>'],
'ReflectionClass::getShortName' => ['string'],
'ReflectionClass::getStartLine' => ['int|false'],
'ReflectionClass::getStaticProperties' => ['array<string, ReflectionProperty>'],
'ReflectionClass::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionClass::getTraitAliases' => ['array<string,string>|null'],
'ReflectionClass::getTraitNames' => ['list<trait-string>|null'],
'ReflectionClass::getTraits' => ['array<trait-string,ReflectionClass>'],
'ReflectionClass::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionClass::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionClass::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionClass::implementsInterface' => ['bool', 'interface_name'=>'interface-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'=>'class-string|ReflectionClass'],
'ReflectionClass::isTrait' => ['bool'],
'ReflectionClass::isUserDefined' => ['bool'],
'ReflectionClass::newInstance' => ['object', '...args='=>'mixed'],
'ReflectionClass::newInstanceArgs' => ['object', 'args='=>'list<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::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'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<class-string,ReflectionClass>'],
'ReflectionExtension::getClassNames' => ['list<class-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' => ['list<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::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'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' => ['list<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'=>'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' => ['list<\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' => ['bool'],
'ReflectionNamedType::getName' => ['string'],
'ReflectionNamedType::isBuiltin' => ['bool'],
'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' => ['list<\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' => ['list<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::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'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::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionProperty::getDeclaringClass' => ['ReflectionClass'],
'ReflectionProperty::getDocComment' => ['string|false'],
'ReflectionProperty::getModifiers' => ['int'],
'ReflectionProperty::getName' => ['string'],
'ReflectionProperty::getType' => ['?ReflectionType'],
'ReflectionProperty::getValue' => ['mixed', 'object='=>'object'],
'ReflectionProperty::hasType' => ['bool'],
'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'],
'ReflectionUnionType::getTypes' => ['list<ReflectionNamedType>'],
'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', 'callback'=>'callable', '...args='=>'mixed'],
'register_tick_function' => ['bool', 'callback'=>'callable():void', '...args='=>'mixed'],
'rename' => ['bool', 'from'=>'string', 'to'=>'string', 'context='=>'resource'],
'rename_function' => ['bool', 'original_name'=>'string', 'new_name'=>'string'],
'reset' => ['mixed|false', '&r_array'=>'array|object'],
'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', 'bundle'=>'ResourceBundle'],
'resourcebundle_create' => ['?ResourceBundle', 'locale'=>'string', 'bundle'=>'string', 'fallback='=>'bool'],
'resourcebundle_get' => ['mixed|null', 'bundle'=>'ResourceBundle', 'index'=>'string|int', 'fallback='=>'bool'],
'resourcebundle_get_error_code' => ['int', 'bundle'=>'ResourceBundle'],
'resourcebundle_get_error_message' => ['string', 'bundle'=>'ResourceBundle'],
'resourcebundle_locales' => ['array', 'bundle'=>'string'],
'restore_error_handler' => ['true'],
'restore_exception_handler' => ['bool'],
'restore_include_path' => ['void'],
'rewind' => ['bool', 'stream'=>'resource'],
'rewinddir' => ['null|false', 'dir_handle='=>'resource'],
'rmdir' => ['bool', 'directory'=>'string', 'context='=>'resource'],
'round' => ['float', 'num'=>'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|false', 'filename'=>'string'],
'rpm_version' => ['string'],
'rpmaddtag' => ['bool', 'tag'=>'int'],
'rpmdbinfo' => ['array', 'nevr'=>'string', 'full='=>'bool'],
'rpmdbsearch' => ['array', 'pattern'=>'string', 'rpmtag='=>'int', 'rpmmire='=>'int', 'full='=>'bool'],
'rpminfo' => ['array', 'path'=>'string', 'full='=>'bool', 'error='=>'string'],
'rpmvercmp' => ['int', 'evr1'=>'string', 'evr2'=>'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'=>'array', 'flags='=>'int'],
'rtrim' => ['string', 'string'=>'string', 'characters='=>'string'],
'runkit7_constant_add' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'new_visibility='=>'int'],
'runkit7_constant_redefine' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'new_visibility='=>'?int'],
'runkit7_constant_remove' => ['bool', 'constant_name'=>'string'],
'runkit7_function_add' => ['bool', 'function_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_doc_comment='=>'?string', 'return_by_reference='=>'?bool', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_function_copy' => ['bool', 'source_name'=>'string', 'target_name'=>'string'],
'runkit7_function_redefine' => ['bool', 'function_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_doc_comment='=>'?string', 'return_by_reference='=>'?bool', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_function_remove' => ['bool', 'function_name'=>'string'],
'runkit7_function_rename' => ['bool', 'source_name'=>'string', 'target_name'=>'string'],
'runkit7_import' => ['bool', 'filename'=>'string', 'flags='=>'?int'],
'runkit7_method_add' => ['bool', 'class_name'=>'string', 'method_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_flags='=>'int|null|string', 'flags_or_doc_comment='=>'int|null|string', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_method_copy' => ['bool', 'destination_class'=>'string', 'destination_method'=>'string', 'source_class'=>'string', 'source_method='=>'?string'],
'runkit7_method_redefine' => ['bool', 'class_name'=>'string', 'method_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_flags='=>'int|null|string', 'flags_or_doc_comment='=>'int|null|string', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_method_remove' => ['bool', 'class_name'=>'string', 'method_name'=>'string'],
'runkit7_method_rename' => ['bool', 'class_name'=>'string', 'source_method_name'=>'string', 'source_target_name'=>'string'],
'runkit7_superglobals' => ['array'],
'runkit7_zval_inspect' => ['array', 'value'=>'mixed'],
'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'],
'runkit_zval_inspect' => ['array', 'value'=>'mixed'],
'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' => ['list<array<string,mixed>>'],
'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', 'codepage'=>'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', 'object'=>'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', 'string'=>'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', 'string'=>'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' => ['list<string>|false', 'directory'=>'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', 'semaphore'=>'resource', 'non_blocking='=>'bool'],
'sem_get' => ['resource|false', 'key'=>'int', 'max_acquire='=>'int', 'permissions='=>'int', 'auto_release='=>'int'],
'sem_release' => ['bool', 'semaphore'=>'resource'],
'sem_remove' => ['bool', 'semaphore'=>'resource'],
'Serializable::__construct' => ['void'],
'Serializable::serialize' => ['?string'],
'Serializable::unserialize' => ['void', 'serialized'=>'string'],
'serialize' => ['string', 'value'=>'mixed'],
'ServerRequest::withInput' => ['ServerRequest', 'input'=>'mixed'],
'ServerRequest::withoutParams' => ['ServerRequest', 'params'=>'int|string'],
'ServerRequest::withParam' => ['ServerRequest', 'key'=>'int|string', 'value'=>'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', 'value='=>'int'],
'session_cache_limiter' => ['string', 'value='=>'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|false', 'id='=>'string'],
'session_is_registered' => ['bool', 'name'=>'string'],
'session_module_name' => ['string', 'module='=>'string'],
'session_name' => ['string|false', 'name='=>'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', 'path='=>'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', 'open'=>'SessionHandlerInterface', 'close='=>'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', 'id'=>'string'],
'SessionHandlerInterface::gc' => ['int|false', 'max_lifetime'=>'int'],
'SessionHandlerInterface::open' => ['bool', 'path'=>'string', 'name'=>'string'],
'SessionHandlerInterface::read' => ['string|false', 'id'=>'string'],
'SessionHandlerInterface::write' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionIdInterface::create_sid' => ['string'],
'SessionUpdateTimestampHandler::updateTimestamp' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionUpdateTimestampHandler::validateId' => ['char', 'id'=>'string'],
'SessionUpdateTimestampHandlerInterface::updateTimestamp' => ['bool', 'key'=>'string', 'value'=>'string'],
'SessionUpdateTimestampHandlerInterface::validateId' => ['bool', 'key'=>'string'],
'set_error_handler' => ['null|callable(int,string,string=,int=,array=):bool', 'callback'=>'null|callable(int,string,string=,int=,array=):bool', 'error_levels='=>'int'],
'set_exception_handler' => ['null|callable(Throwable):void', 'callback'=>'null|callable(Throwable):void'],
'set_file_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'set_include_path' => ['string|false', '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', 'samesite='=>'string', 'url_encode='=>'int'],
'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', 'locales'=>'string|0|null', '...rest='=>'string'],
'setlocale\'1' => ['string|false', 'category'=>'int', 'locales'=>'?array'],
'setproctitle' => ['void', 'title'=>'string'],
'setrawcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool'],
'setrawcookie\'1' => ['bool', 'name'=>'string', 'value='=>'string', 'options='=>'array'],
'setRightFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setthreadtitle' => ['bool', 'title'=>'string'],
'settype' => ['bool', '&rw_var'=>'mixed', 'type'=>'string'],
'sha1' => ['string', 'string'=>'string', 'binary='=>'bool'],
'sha1_file' => ['string|false', 'filename'=>'string', 'binary='=>'bool'],
'sha256' => ['string', 'string'=>'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|false|null', 'command'=>'string'],
'shm_attach' => ['resource', 'key'=>'int', 'size='=>'int', 'permissions='=>'int'],
'shm_detach' => ['bool', 'shm'=>'resource'],
'shm_get_var' => ['mixed', 'shm'=>'resource', 'key'=>'int'],
'shm_has_var' => ['bool', 'shm'=>'resource', 'key'=>'int'],
'shm_put_var' => ['bool', 'shm'=>'resource', 'key'=>'int', 'value'=>'mixed'],
'shm_remove' => ['bool', 'shm'=>'resource'],
'shm_remove_var' => ['bool', 'shm'=>'resource', 'key'=>'int'],
'shmop_close' => ['void', 'shmop'=>'resource'],
'shmop_delete' => ['bool', 'shmop'=>'resource'],
'shmop_open' => ['resource|false', 'key'=>'int', 'mode'=>'string', 'permissions'=>'int', 'size'=>'int'],
'shmop_read' => ['string|false', 'shmop'=>'resource', 'offset'=>'int', 'size'=>'int'],
'shmop_size' => ['int', 'shmop'=>'resource'],
'shmop_write' => ['int|false', 'shmop'=>'resource', 'data'=>'string', 'offset'=>'int'],
'show_source' => ['string|bool', 'filename'=>'string', 'return='=>'bool'],
'shuffle' => ['bool', '&rw_array'=>'array'],
'signeurlpaiement' => ['string', 'clent'=>'string', 'data'=>'string'],
'similar_text' => ['int', 'string1'=>'string', 'string2'=>'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', 'namespace_or_prefix='=>'string', 'is_prefix='=>'bool'],
'simplexml_load_string' => ['SimpleXMLElement|false', 'data'=>'string', 'class_name='=>'string', 'options='=>'int', 'namespace_or_prefix='=>'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'],
'sin' => ['float', 'num'=>'float'],
'sinh' => ['float', 'num'=>'float'],
'sizeof' => ['int', 'value'=>'Countable|array', 'mode='=>'int'],
'sleep' => ['int|false', 'seconds'=>'int'],
'snmp2_get' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_getnext' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_real_walk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_set' => ['bool', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_walk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_get' => ['string|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_getnext' => ['string|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_real_walk' => ['array|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_set' => ['bool', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_walk' => ['array|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_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' => ['array|string|false', 'objectId'=>'string|array', 'preserveKeys='=>'bool'],
'SNMP::getErrno' => ['int'],
'SNMP::getError' => ['string'],
'SNMP::getnext' => ['string|array|false', 'objectId'=>'string|array'],
'SNMP::set' => ['bool', 'objectId'=>'string|array', 'type'=>'string|array', 'value'=>'mixed'],
'SNMP::setSecurity' => ['bool', 'securityLevel'=>'string', 'authProtocol='=>'string', 'authPassphrase='=>'string', 'privacyProtocol='=>'string', 'privacyPassphrase='=>'string', 'contextName='=>'string', 'contextEngineId='=>'string'],
'SNMP::walk' => ['array|false', 'objectId'=>'string', 'suffixAsKey='=>'bool', 'maxRepetitions='=>'int', 'nonRepeaters='=>'int'],
'snmp_get_quick_print' => ['bool'],
'snmp_get_valueretrieval' => ['int'],
'snmp_read_mib' => ['bool', 'filename'=>'string'],
'snmp_set_enum_print' => ['bool', 'enable'=>'int'],
'snmp_set_oid_numeric_print' => ['void', 'format'=>'int'],
'snmp_set_oid_output_format' => ['bool', 'format'=>'int'],
'snmp_set_quick_print' => ['bool', 'enable'=>'bool'],
'snmp_set_valueretrieval' => ['bool', 'method='=>'int'],
'snmpget' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpgetnext' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmprealwalk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpset' => ['bool', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'mixed', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalk' => ['array|false', 'hostname'=>'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|null'],
'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|null'],
'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' => ['list<array<string,mixed>>'],
'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', 'object'=>'object'],
'SoapServer::setPersistence' => ['void', 'mode'=>'int'],
'SoapServer::SoapServer' => ['object', 'wsdl'=>'?string', 'options='=>'array'],
'SoapVar::__construct' => ['void', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string|null', 'type_namespace='=>'string|null', 'node_name='=>'string|null', 'node_namespace='=>'string|null'],
'SoapVar::SoapVar' => ['object', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string|null', 'type_namespace='=>'string|null', 'node_name='=>'string|null', 'node_namespace='=>'string|null'],
'socket_accept' => ['Socket|false', 'socket'=>'Socket'],
'socket_addrinfo_bind' => ['Socket|false', 'address'=>'AddressInfo'],
'socket_addrinfo_connect' => ['Socket|false', 'address'=>'AddressInfo'],
'socket_addrinfo_explain' => ['array', 'address'=>'AddressInfo'],
'socket_addrinfo_lookup' => ['false|AddressInfo[]', 'host='=>'string|null', 'service='=>'mixed', 'hints='=>'array'],
'socket_bind' => ['bool', 'socket'=>'Socket', 'addr'=>'string', 'port='=>'int'],
'socket_clear_error' => ['void', 'socket='=>'Socket'],
'socket_close' => ['void', 'socket'=>'Socket'],
'socket_cmsg_space' => ['int', 'level'=>'int', 'type'=>'int'],
'socket_connect' => ['bool', 'socket'=>'Socket', 'addr'=>'string', 'port='=>'int'],
'socket_create' => ['Socket|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'socket_create_listen' => ['Socket|false', 'port'=>'int', 'backlog='=>'int'],
'socket_create_pair' => ['bool', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int', '&w_fd'=>'Socket[]'],
'socket_export_stream' => ['resource|false', 'socket'=>'Socket'],
'socket_get_option' => ['mixed|false', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int'],
'socket_get_status' => ['array', 'stream'=>'Socket'],
'socket_getopt' => ['mixed', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int'],
'socket_getpeername' => ['bool', 'socket'=>'Socket', '&w_addr'=>'string', '&w_port='=>'int'],
'socket_getsockname' => ['bool', 'socket'=>'Socket', '&w_addr'=>'string', '&w_port='=>'int'],
'socket_import_stream' => ['Socket|false|null', 'stream'=>'resource'],
'socket_last_error' => ['int', 'socket='=>'Socket'],
'socket_listen' => ['bool', 'socket'=>'Socket', 'backlog='=>'int'],
'socket_read' => ['string|false', 'socket'=>'Socket', 'length'=>'int', 'type='=>'int'],
'socket_recv' => ['int|false', 'socket'=>'Socket', '&w_buf'=>'string', 'length'=>'int', 'flags'=>'int'],
'socket_recvfrom' => ['int|false', 'socket'=>'Socket', '&w_buf'=>'string', 'length'=>'int', 'flags'=>'int', '&w_name'=>'string', '&w_port='=>'int'],
'socket_recvmsg' => ['int|false', 'socket'=>'Socket', '&w_message'=>'string', 'flags='=>'int'],
'socket_select' => ['int|false', '&rw_read_fds'=>'Socket[]|null', '&rw_write_fds'=>'Socket[]|null', '&rw_except_fds'=>'Socket[]|null', 'tv_sec'=>'int|null', 'tv_usec='=>'int'],
'socket_send' => ['int|false', 'socket'=>'Socket', 'buf'=>'string', 'length'=>'int', 'flags'=>'int'],
'socket_sendmsg' => ['int|false', 'socket'=>'Socket', 'message'=>'array', 'flags'=>'int'],
'socket_sendto' => ['int|false', 'socket'=>'Socket', 'buf'=>'string', 'length'=>'int', 'flags'=>'int', 'addr'=>'string', 'port='=>'int'],
'socket_set_block' => ['bool', 'socket'=>'Socket'],
'socket_set_blocking' => ['bool', 'socket'=>'Socket', 'mode'=>'int'],
'socket_set_nonblock' => ['bool', 'socket'=>'Socket'],
'socket_set_option' => ['bool', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int', 'optval'=>'int|string|array'],
'socket_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'socket_setopt' => ['void', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int', 'optval'=>'int|string|array'],
'socket_shutdown' => ['bool', 'socket'=>'Socket', 'how='=>'int'],
'socket_strerror' => ['string', 'errno'=>'int'],
'socket_write' => ['int|false', 'socket'=>'Socket', 'data'=>'string', 'length='=>'int|null'],
'socket_wsaprotocol_info_export' => ['string|false', 'socket'=>'Socket', 'process_id'=>'int'],
'socket_wsaprotocol_info_import' => ['Socket|false', 'info_id'=>'string'],
'socket_wsaprotocol_info_release' => ['bool', 'info_id'=>'string'],
'sodium_add' => ['void', '&rw_string1'=>'string', 'string2'=>'string'],
'sodium_base642bin' => ['string', 'string'=>'string', 'id'=>'int', 'ignore='=>'string'],
'sodium_bin2base64' => ['string', 'string'=>'string', 'id'=>'int'],
'sodium_bin2hex' => ['string', 'string'=>'string'],
'sodium_compare' => ['int', 'string1'=>'string', 'string2'=>'string'],
'sodium_crypto_aead_aes256gcm_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_encrypt' => ['string', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_is_available' => ['bool'],
'sodium_crypto_aead_aes256gcm_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_encrypt' => ['string|false', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_encrypt' => ['string|false', 'message'=>'string', 'additional_data'=>'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', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' => ['string|false', 'message'=>'string', 'additional_data'=>'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', 'message'=>'string', 'nonce'=>'string', 'key_pair'=>'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', 'ciphertext'=>'string', 'nonce'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_box_publickey_from_secretkey' => ['string', 'secret_key'=>'string'],
'sodium_crypto_box_seal' => ['string', 'message'=>'string', 'public_key'=>'string'],
'sodium_crypto_box_seal_open' => ['string|false', 'ciphertext'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_box_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_generichash' => ['string', 'message'=>'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', '&rw_state'=>'string', 'string'=>'string'],
'sodium_crypto_kdf_derive_from_key' => ['string', 'subkey_length'=>'int', 'subkey_id'=>'int', 'context'=>'string', 'key'=>'string'],
'sodium_crypto_kdf_keygen' => ['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', 'key_pair'=>'string'],
'sodium_crypto_kx_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_kx_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_kx_server_session_keys' => ['array<int,string>', 'server_key_pair'=>'string', 'client_key'=>'string'],
'sodium_crypto_pwhash' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int', 'algo='=>'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', 'n'=>'string', 'p'=>'string'],
'sodium_crypto_scalarmult_base' => ['string', 'secret_key'=>'string'],
'sodium_crypto_secretbox' => ['string', 'message'=>'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', '&r_state'=>'string', 'ciphertext'=>'string', 'additional_data='=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_push' => ['string', '&w_state'=>'string', 'message'=>'string', 'additional_data='=>'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', 'secret_key'=>'string'],
'sodium_crypto_sign_detached' => ['string', 'message'=>'string', 'secret_key'=>'string'],
'sodium_crypto_sign_ed25519_pk_to_curve25519' => ['string', 'public_key'=>'string'],
'sodium_crypto_sign_ed25519_sk_to_curve25519' => ['string', 'secret_key'=>'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', 'signed_message'=>'string', 'public_key'=>'string'],
'sodium_crypto_sign_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_sign_publickey_from_secretkey' => ['string', 'secret_key'=>'string'],
'sodium_crypto_sign_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_sign_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_sign_verify_detached' => ['bool', 'signature'=>'string', 'message'=>'string', 'public_key'=>'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', 'string'=>'string', 'ignore='=>'string'],
'sodium_increment' => ['void', '&rw_string'=>'string'],
'sodium_memcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'sodium_memzero' => ['void', '&w_string'=>'string'],
'sodium_pad' => ['string', 'string'=>'string', 'block_size'=>'int'],
'sodium_unpad' => ['string', 'string'=>'string', 'block_size'=>'int'],
'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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', 'string'=>'string'],
'SolrUtils::getSolrVersion' => ['string'],
'SolrUtils::queryPhrase' => ['string', 'string'=>'string'],
'sort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'soundex' => ['string', 'string'=>'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'=>'string', 'file_extensions='=>'string'],
'spl_autoload_call' => ['void', 'class'=>'string'],
'spl_autoload_extensions' => ['string', 'file_extensions='=>'string'],
'spl_autoload_functions' => ['false|list<callable(string):void>'],
'spl_autoload_register' => ['bool', 'callback='=>'callable(string):void', 'throw='=>'bool', 'prepend='=>'bool'],
'spl_autoload_unregister' => ['bool', 'callback'=>'callable(string):void'],
'spl_classes' => ['array'],
'spl_object_hash' => ['string', 'object'=>'object'],
'spl_object_id' => ['int', 'object'=>'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' => ['list<string>|array{0: null}|false|null', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fgets' => ['string|false'],
'SplFileObject::flock' => ['bool', 'operation'=>'int', '&w_wouldblock='=>'int'],
'SplFileObject::fpassthru' => ['int|false'],
'SplFileObject::fputcsv' => ['int|false', 'fields'=>'array<array-key, null|scalar|Stringable>', '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', 'string'=>'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' => ['false'],
'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', 'object'=>'object', 'inf='=>'mixed'],
'SplObjectStorage::contains' => ['bool', 'object'=>'object'],
'SplObjectStorage::count' => ['int'],
'SplObjectStorage::current' => ['object'],
'SplObjectStorage::detach' => ['void', 'object'=>'object'],
'SplObjectStorage::getHash' => ['string', 'object'=>'object'],
'SplObjectStorage::getInfo' => ['mixed'],
'SplObjectStorage::key' => ['int'],
'SplObjectStorage::next' => ['void'],
'SplObjectStorage::offsetExists' => ['bool', 'object'=>'object'],
'SplObjectStorage::offsetGet' => ['mixed', 'object'=>'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' => ['list<string>|array{0: null}|false|null', '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<array-key, null|scalar|Stringable>', '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', 'string'=>'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', '...values='=>'string|int|float'],
'SQLite3::__construct' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryptionKey='=>'?string'],
'SQLite3::busyTimeout' => ['bool', 'milliseconds'=>'int'],
'SQLite3::changes' => ['int'],
'SQLite3::close' => ['bool'],
'SQLite3::createAggregate' => ['bool', 'name'=>'string', 'stepCallback'=>'callable', 'finalCallback'=>'callable', 'argCount='=>'int'],
'SQLite3::createCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'SQLite3::createFunction' => ['bool', 'name'=>'string', 'callback'=>'callable', 'argCount='=>'int', 'flags='=>'int'],
'SQLite3::enableExceptions' => ['bool', 'enable='=>'bool'],
'SQLite3::escapeString' => ['string', 'string'=>'string'],
'SQLite3::exec' => ['bool', 'query'=>'string'],
'SQLite3::lastErrorCode' => ['int'],
'SQLite3::lastErrorMsg' => ['string'],
'SQLite3::lastInsertRowID' => ['int'],
'SQLite3::loadExtension' => ['bool', 'name'=>'string'],
'SQLite3::open' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryptionKey='=>'?string'],
'SQLite3::openBlob' => ['resource|false', 'table'=>'string', 'column'=>'string', 'rowid'=>'int', 'database='=>'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', 'entireRow='=>'bool'],
'SQLite3::version' => ['array'],
'SQLite3Result::__construct' => ['void'],
'SQLite3Result::columnName' => ['string', 'column'=>'int'],
'SQLite3Result::columnType' => ['int', 'column'=>'int'],
'SQLite3Result::fetchArray' => ['array|false', 'mode='=>'int'],
'SQLite3Result::finalize' => ['bool'],
'SQLite3Result::numColumns' => ['int'],
'SQLite3Result::reset' => ['bool'],
'SQLite3Stmt::__construct' => ['void', 'sqlite3'=>'sqlite3', 'query'=>'string'],
'SQLite3Stmt::bindParam' => ['bool', 'param'=>'string|int', '&rw_var'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::bindValue' => ['bool', 'param'=>'string|int', 'value'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::clear' => ['bool'],
'SQLite3Stmt::close' => ['bool'],
'SQLite3Stmt::execute' => ['false|SQLite3Result'],
'SQLite3Stmt::getSQL' => ['string', 'expand='=>'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' => ['list<array<string,mixed>>'],
'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', 'num'=>'float'],
'srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'sscanf' => ['list<float|int|string|null>|int|null', 'string'=>'string', 'format'=>'string', '&...w_vars='=>'string|int|float|null'],
'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', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_factorial' => ['float', 'n'=>'int'],
'stats_stat_gennch' => ['float', 'n'=>'int'],
'stats_stat_independent_t' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_innerproduct' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_stat_paired_t' => ['float', 'array1'=>'array', 'array2'=>'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_contains' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_ends_with' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_getcsv' => ['non-empty-list<?string>', 'string'=>'string', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'str_ireplace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_count='=>'int'],
'str_pad' => ['string', 'string'=>'string', 'length'=>'int', 'pad_string='=>'string', 'pad_type='=>'int'],
'str_repeat' => ['string', 'string'=>'string', 'times'=>'int'],
'str_replace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_count='=>'int'],
'str_rot13' => ['string', 'string'=>'string'],
'str_shuffle' => ['string', 'string'=>'string'],
'str_split' => ['non-empty-list<string>', 'string'=>'string', 'length='=>'positive-int'],
'str_starts_with' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_word_count' => ['array<int, string>|int', 'string'=>'string', 'format='=>'int', 'characters='=>'string'],
'strcasecmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool'],
'strcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strcoll' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strcspn' => ['int', 'string'=>'string', 'characters'=>'string', 'offset='=>'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', 'stream_or_context'=>'resource'],
'stream_context_get_params' => ['array', 'context'=>'resource'],
'stream_context_set_default' => ['resource', 'options'=>'array'],
'stream_context_set_option' => ['bool', 'context'=>'', 'wrapper_or_options'=>'string', 'option_name'=>'string', 'value'=>''],
'stream_context_set_option\'1' => ['bool', 'context'=>'', 'wrapper_or_options'=>'array'],
'stream_context_set_params' => ['bool', 'context'=>'resource', 'params'=>'array'],
'stream_copy_to_stream' => ['int|false', 'from'=>'resource', 'to'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_encoding' => ['bool', 'stream'=>'resource', 'encoding='=>'string'],
'stream_filter_append' => ['resource|false', 'stream'=>'resource', 'filter_name'=>'string', 'mode='=>'int', 'params='=>'mixed'],
'stream_filter_prepend' => ['resource|false', 'stream'=>'resource', 'filter_name'=>'string', 'mode='=>'int', 'params='=>'mixed'],
'stream_filter_register' => ['bool', 'filter_name'=>'string', 'class'=>'string'],
'stream_filter_remove' => ['bool', 'stream_filter'=>'resource'],
'stream_get_contents' => ['string|false', 'stream'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_get_filters' => ['array'],
'stream_get_line' => ['string|false', 'stream'=>'resource', 'length'=>'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}', 'stream'=>'resource'],
'stream_get_transports' => ['list<string>'],
'stream_get_wrappers' => ['list<string>'],
'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', 'class'=>'string', 'flags='=>'int'],
'stream_resolve_include_path' => ['string|false', 'filename'=>'string'],
'stream_select' => ['int|false', '&rw_read'=>'resource[]', '&rw_write'=>'?resource[]', '&rw_except'=>'?resource[]', 'seconds'=>'?int', 'microseconds='=>'?int'],
'stream_set_blocking' => ['bool', 'stream'=>'resource', 'enable'=>'bool'],
'stream_set_chunk_size' => ['int|false', 'stream'=>'resource', 'size'=>'int'],
'stream_set_read_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'stream_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'stream_set_write_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'stream_socket_accept' => ['resource|false', 'socket'=>'resource', 'timeout='=>'float', '&w_peer_name='=>'string'],
'stream_socket_client' => ['resource|false', 'address'=>'string', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_enable_crypto' => ['int|bool', 'stream'=>'resource', 'enable'=>'bool', 'crypto_method='=>'int', 'session_stream='=>'resource'],
'stream_socket_get_name' => ['string', 'socket'=>'resource', 'remote'=>'bool'],
'stream_socket_pair' => ['resource[]|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'stream_socket_recvfrom' => ['string', 'socket'=>'resource', 'length'=>'int', 'flags='=>'int', '&w_address='=>'string'],
'stream_socket_sendto' => ['int', 'socket'=>'resource', 'data'=>'string', 'flags='=>'int', 'address='=>'string'],
'stream_socket_server' => ['resource|false', 'address'=>'string', '&w_error_code='=>'int', '&w_error_message='=>'string', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_shutdown' => ['bool', 'stream'=>'resource', 'mode'=>'int'],
'stream_supports_lock' => ['bool', 'stream'=>'resource'],
'stream_wrapper_register' => ['bool', 'protocol'=>'string', 'class'=>'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', 'string'=>'string', 'allowed_tags='=>'string'],
'stripcslashes' => ['string', 'string'=>'string'],
'stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'stripslashes' => ['string', 'string'=>'string'],
'stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool'],
'strlen' => ['int', 'string'=>'string'],
'strnatcasecmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strnatcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strncasecmp' => ['int', 'string1'=>'string', 'string2'=>'string', 'length'=>'int'],
'strncmp' => ['int', 'string1'=>'string', 'string2'=>'string', 'length'=>'int'],
'strpbrk' => ['string|false', 'string'=>'string', 'characters'=>'string'],
'strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'strptime' => ['array|false', 'timestamp'=>'string', 'format'=>'string'],
'strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string'],
'strrev' => ['string', 'string'=>'string'],
'strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'strspn' => ['int', 'string'=>'string', 'characters'=>'string', 'offset='=>'int', 'length='=>'int'],
'strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool'],
'strtok' => ['string|false', 'string'=>'string', 'token'=>'string'],
'strtok\'1' => ['string|false', 'string'=>'string'],
'strtolower' => ['lowercase-string', 'string'=>'string'],
'strtotime' => ['int|false', 'datetime'=>'string', 'baseTimestamp='=>'int'],
'strtoupper' => ['string', 'string'=>'string'],
'strtr' => ['string', 'string'=>'string', 'from'=>'string', 'to'=>'string'],
'strtr\'1' => ['string', 'string'=>'string', 'from'=>'array'],
'strval' => ['string', 'value'=>'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', 'string'=>'string', 'offset'=>'int', 'length='=>'int'],
'substr_compare' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset'=>'int', 'length='=>'int', 'case_insensitive='=>'bool'],
'substr_count' => ['int', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'length='=>'int'],
'substr_replace' => ['string|string[]', 'string'=>'string|string[]', 'replace'=>'mixed', 'offset'=>'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', 'string'=>'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', 'string'=>'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_result_code='=>'int'],
'taint' => ['bool', '&rw_string'=>'string', '&...w_other_strings='=>'string'],
'tan' => ['float', 'num'=>'float'],
'tanh' => ['float', 'num'=>'float'],
'tcpwrap_check' => ['bool', 'daemon'=>'string', 'address'=>'string', 'user='=>'string', 'nodns='=>'bool'],
'tempnam' => ['string|false', 'directory'=>'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' => ['list<array<string,mixed>>'],
'Throwable::getTraceAsString' => ['string'],
'tidy::__construct' => ['void', 'filename='=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::body' => ['tidyNode'],
'tidy::cleanRepair' => ['bool'],
'tidy::diagnose' => ['bool'],
'tidy::getConfig' => ['array'],
'tidy::getHtmlVer' => ['int'],
'tidy::getOpt' => ['mixed', 'option'=>'string'],
'tidy::getOptDoc' => ['string', 'option'=>'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', 'useIncludePath='=>'bool'],
'tidy::parseString' => ['bool', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::repairFile' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::repairString' => ['string', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::root' => ['tidyNode'],
'tidy_access_count' => ['int', 'tidy'=>'tidy'],
'tidy_clean_repair' => ['bool', 'tidy'=>'tidy'],
'tidy_config_count' => ['int', 'tidy'=>'tidy'],
'tidy_diagnose' => ['bool', 'tidy'=>'tidy'],
'tidy_error_count' => ['int', 'tidy'=>'tidy'],
'tidy_get_body' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_config' => ['array', 'tidy'=>'tidy'],
'tidy_get_error_buffer' => ['string', 'tidy'=>'tidy'],
'tidy_get_head' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_html' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_html_ver' => ['int', 'tidy'=>'tidy'],
'tidy_get_opt_doc' => ['string', 'tidy'=>'tidy', 'option'=>'string'],
'tidy_get_output' => ['string', 'tidy'=>'tidy'],
'tidy_get_release' => ['string'],
'tidy_get_root' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_status' => ['int', 'tidy'=>'tidy'],
'tidy_getopt' => ['mixed', 'tidy'=>'string', 'option'=>'tidy'],
'tidy_is_xhtml' => ['bool', 'tidy'=>'tidy'],
'tidy_is_xml' => ['bool', 'tidy'=>'tidy'],
'tidy_load_config' => ['void', 'filename'=>'string', 'encoding'=>'string'],
'tidy_parse_file' => ['tidy', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy_parse_string' => ['tidy', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy_repair_file' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy_repair_string' => ['string', 'string'=>'string', 'config='=>'', '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', 'tidy'=>'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<string, list<array{dst: bool, offset: int, timezone_id: string|null}>>|false'],
'timezone_identifiers_list' => ['list<string>', 'timezoneGroup='=>'int', 'countryCode='=>'?string'],
'timezone_location_get' => ['array|false', 'object'=>'DateTimeZone'],
'timezone_name_from_abbr' => ['string|false', 'abbr'=>'string', 'utcOffset='=>'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' => ['list<array{ts: int, time: string, offset: int, isdst: bool, abbr: string}>|false', 'object'=>'DateTimeZone', 'timestampBegin='=>'int', 'timestampEnd='=>'int'],
'timezone_version_get' => ['string'],
'tmpfile' => ['resource|false'],
'token_get_all' => ['list<string|array{0:int,1:string,2:int}>', 'code'=>'string', 'flags='=>'int'],
'token_name' => ['string', 'id'=>'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', 'mtime='=>'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', 'trait'=>'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', 'transliterator'=>'Transliterator'],
'transliterator_get_error_code' => ['int', 'transliterator'=>'Transliterator'],
'transliterator_get_error_message' => ['string', 'transliterator'=>'Transliterator'],
'transliterator_list_ids' => ['array'],
'transliterator_transliterate' => ['string|false', 'transliterator'=>'Transliterator|string', 'string'=>'string', 'start='=>'int', 'end='=>'int'],
'trigger_error' => ['bool', 'message'=>'string', 'error_level='=>'256|512|1024|16384'],
'trim' => ['string', 'string'=>'string', 'characters='=>'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' => ['list<array<string,mixed>>'],
'TypeError::getTraceAsString' => ['string'],
'uasort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'ucfirst' => ['string', 'string'=>'string'],
'UConverter::__construct' => ['void', 'destination_encoding='=>'string', 'source_encoding='=>'string'],
'UConverter::convert' => ['string', 'string'=>'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', 'string'=>'string', 'toEncoding'=>'string', 'fromEncoding'=>'string', 'options='=>'?array'],
'ucwords' => ['string', 'string'=>'string', 'separators='=>'string'],
'udm_add_search_limit' => ['bool', 'agent'=>'resource', 'var'=>'int', 'value'=>'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', 'string'=>'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', 'string'=>'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'=>'array', 'callback'=>'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' => ['list<array<string,mixed>>'],
'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' => ['list<array<string,mixed>>'],
'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', 'string'=>'string', 'offset='=>'int'],
'unregister_tick_function' => ['void', 'callback'=>'callable'],
'unserialize' => ['mixed', 'data'=>'string', 'options='=>'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', 'string'=>'string'],
'urlencode' => ['string', 'string'=>'string'],
'use_soap_error_handler' => ['bool', 'enable='=>'bool'],
'user_error' => ['void', 'message'=>'string', 'error_level='=>'int'],
'usleep' => ['void', 'microseconds'=>'int'],
'usort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'utf8_decode' => ['string', 'string'=>'string'],
'utf8_encode' => ['string', 'string'=>'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' => ['list<array<string,mixed>>'],
'V8JsScriptException::getTraceAsString' => ['string'],
'var_dump' => ['void', 'value'=>'mixed', '...values='=>'mixed'],
'var_export' => ['?string', 'value'=>'mixed', 'return='=>'bool'],
'VARIANT::__construct' => ['void', 'value='=>'mixed', 'type='=>'int', 'codepage='=>'int'],
'variant_abs' => ['mixed', 'value'=>'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', 'locale_id='=>'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', 'value'=>'mixed'],
'variant_get_type' => ['int', 'variant'=>'VARIANT'],
'variant_idiv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_imp' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_int' => ['mixed', 'value'=>'mixed'],
'variant_mod' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_mul' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_neg' => ['mixed', 'value'=>'mixed'],
'variant_not' => ['mixed', 'value'=>'mixed'],
'variant_or' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_pow' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_round' => ['mixed', 'value'=>'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', 'version1'=>'string', 'version2'=>'string', 'operator'=>'\'<\'|\'lt\'|\'<=\'|\'le\'|\'>\'|\'gt\'|\'>=\'|\'ge\'|\'==\'|\'=\'|\'eq\'|\'!=\'|\'<>\'|\'ne\''],
'version_compare\'1' => ['int', 'version1'=>'string', 'version2'=>'string'],
'vfprintf' => ['int', 'stream'=>'resource', 'format'=>'string', 'values'=>'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', 'values'=>'array'],
'vsprintf' => ['string', 'format'=>'string', 'values'=>'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', 'value'=>'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', 'string'=>'string', 'width='=>'int', 'break='=>'string', 'cut_long_words='=>'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', 'string'=>'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', 'string'=>'string', 'patch'=>'string', 'flags='=>'int', '&w_error='=>'string'],
'xdiff_string_patch_binary' => ['string', 'string'=>'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', 'error_code'=>'int'],
'xml_get_current_byte_index' => ['int|false', 'parser'=>'XMLParser'],
'xml_get_current_column_number' => ['int|false', 'parser'=>'XMLParser'],
'xml_get_current_line_number' => ['int|false', 'parser'=>'XMLParser'],
'xml_get_error_code' => ['int|false', 'parser'=>'XMLParser'],
'xml_parse' => ['int', 'parser'=>'XMLParser', 'data'=>'string', 'is_final='=>'bool'],
'xml_parse_into_struct' => ['int', 'parser'=>'XMLParser', 'data'=>'string', '&w_values'=>'array', '&w_index='=>'array'],
'xml_parser_create' => ['XMLParser', 'encoding='=>'string'],
'xml_parser_create_ns' => ['XMLParser', 'encoding='=>'string', 'separator='=>'string'],
'xml_parser_free' => ['bool', 'parser'=>'XMLParser'],
'xml_parser_get_option' => ['mixed|false', 'parser'=>'XMLParser', 'option'=>'int'],
'xml_parser_set_option' => ['bool', 'parser'=>'XMLParser', 'option'=>'int', 'value'=>'mixed'],
'xml_set_character_data_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_default_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_element_handler' => ['bool', 'parser'=>'XMLParser', 'start_handler'=>'callable', 'end_handler'=>'callable'],
'xml_set_end_namespace_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_external_entity_ref_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_notation_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_object' => ['bool', 'parser'=>'XMLParser', 'object'=>'object'],
'xml_set_processing_instruction_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_start_namespace_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_unparsed_entity_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'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::endDtdAttlist' => ['bool'],
'XMLWriter::endDtdElement' => ['bool'],
'XMLWriter::endDtdEntity' => ['bool'],
'XMLWriter::endElement' => ['bool'],
'XMLWriter::endPi' => ['bool'],
'XMLWriter::flush' => ['string|int', 'empty='=>'bool'],
'XMLWriter::fullEndElement' => ['bool'],
'XMLWriter::openMemory' => ['bool'],
'XMLWriter::openUri' => ['bool', 'uri'=>'string'],
'XMLWriter::outputMemory' => ['string', 'flush='=>'bool'],
'XMLWriter::setIndent' => ['bool', 'enable'=>'bool'],
'XMLWriter::setIndentString' => ['bool', 'indentation'=>'string'],
'XMLWriter::startAttribute' => ['bool', 'name'=>'string'],
'XMLWriter::startAttributeNs' => ['bool', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?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', 'namespace'=>'?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', 'namespace'=>'?string', 'value'=>'string'],
'XMLWriter::writeCdata' => ['bool', 'content'=>'string'],
'XMLWriter::writeComment' => ['bool', 'content'=>'string'],
'XMLWriter::writeDtd' => ['bool', 'name'=>'string', 'publicId='=>'?string', 'systemId='=>'?string', 'content='=>'?string'],
'XMLWriter::writeDtdAttlist' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDtdElement' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDtdEntity' => ['bool', 'name'=>'string', 'content'=>'string', 'isParam='=>'bool', 'publicId='=>'?string', 'systemId='=>'?string', 'notationData='=>'?string'],
'XMLWriter::writeElement' => ['bool', 'name'=>'string', 'content='=>'?string'],
'XMLWriter::writeElementNs' => ['bool', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'content='=>'?string'],
'XMLWriter::writePi' => ['bool', 'target'=>'string', 'content'=>'string'],
'XMLWriter::writeRaw' => ['bool', 'content'=>'string'],
'xmlwriter_end_attribute' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_cdata' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_comment' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_document' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd_attlist' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd_element' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd_entity' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_element' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_pi' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_flush' => ['string|int', 'writer'=>'XMLWriter', 'empty='=>'bool'],
'xmlwriter_full_end_element' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_open_memory' => ['XMLWriter|false'],
'xmlwriter_open_uri' => ['XMLWriter|false', 'uri'=>'string'],
'xmlwriter_output_memory' => ['string', 'writer'=>'XMLWriter', 'flush='=>'bool'],
'xmlwriter_set_indent' => ['bool', 'writer'=>'XMLWriter', 'enable'=>'bool'],
'xmlwriter_set_indent_string' => ['bool', 'writer'=>'XMLWriter', 'indentation'=>'string'],
'xmlwriter_start_attribute' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string'],
'xmlwriter_start_attribute_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string'],
'xmlwriter_start_cdata' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_start_comment' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_start_document' => ['bool', 'writer'=>'XMLWriter', 'version='=>'?string', 'encoding='=>'?string', 'standalone='=>'?string'],
'xmlwriter_start_dtd' => ['bool', 'writer'=>'XMLWriter', 'qualifiedName'=>'string', 'publicId='=>'?string', 'systemId='=>'?string'],
'xmlwriter_start_dtd_attlist' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string'],
'xmlwriter_start_dtd_element' => ['bool', 'writer'=>'XMLWriter', 'qualifiedName'=>'string'],
'xmlwriter_start_dtd_entity' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'isParam'=>'bool'],
'xmlwriter_start_element' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string'],
'xmlwriter_start_element_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string'],
'xmlwriter_start_pi' => ['bool', 'writer'=>'XMLWriter', 'target'=>'string'],
'xmlwriter_text' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xmlwriter_write_attribute' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'value'=>'string'],
'xmlwriter_write_attribute_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'value'=>'string'],
'xmlwriter_write_cdata' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xmlwriter_write_comment' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xmlwriter_write_dtd' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'publicId='=>'?string', 'systemId='=>'?string', 'content='=>'?string'],
'xmlwriter_write_dtd_attlist' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_element' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_entity' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content'=>'string', 'isParam='=>'bool', 'publicId='=>'?string', 'systemId='=>'?string', 'notationData='=>'?string'],
'xmlwriter_write_element' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content='=>'?string'],
'xmlwriter_write_element_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'content='=>'?string'],
'xmlwriter_write_pi' => ['bool', 'writer'=>'XMLWriter', 'target'=>'string', 'content'=>'string'],
'xmlwriter_write_raw' => ['bool', 'writer'=>'XMLWriter', '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'=>'', 'object'=>'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', 'namespace'=>'string', 'name'=>'string'],
'XsltProcessor::getSecurityPrefs' => ['int'],
'XSLTProcessor::hasExsltSupport' => ['bool'],
'XSLTProcessor::importStylesheet' => ['bool', 'stylesheet'=>'object'],
'XSLTProcessor::registerPHPFunctions' => ['void', 'functions='=>'mixed'],
'XSLTProcessor::removeParameter' => ['bool', 'namespace'=>'string', 'name'=>'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', 'preferences'=>'int'],
'XSLTProcessor::transformToDoc' => ['DOMDocument|false', 'document'=>'DOMNode'],
'XSLTProcessor::transformToURI' => ['int', 'document'=>'DOMDocument', 'uri'=>'string'],
'XSLTProcessor::transformToXML' => ['string|false', 'document'=>'DOMDocument'],
'yac::__construct' => ['void', 'prefix='=>'string'],
'yac::__get' => ['mixed', 'key'=>'string'],
'yac::__set' => ['mixed', 'key'=>'string', 'value'=>'mixed'],
'yac::delete' => ['bool', 'keys'=>'string|array', 'ttl='=>'int'],
'yac::dump' => ['mixed', 'num'=>'int'],
'yac::flush' => ['bool'],
'yac::get' => ['mixed', 'key'=>'string|array', 'cas='=>'int'],
'yac::info' => ['array'],
'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' => ['list<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' => ['list<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' => ['list<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::getControllerName' => ['string'],
'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' => ['list<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::getName' => ['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' => ['list<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::getDefaultAction' => ['string'],
'Yaf_Dispatcher::getDefaultController' => ['string'],
'Yaf_Dispatcher::getDefaultModule' => ['string'],
'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' => ['list<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::getNamespacePath' => ['string', 'namespaces'=>'string'],
'Yaf_Loader::import' => ['bool'],
'Yaf_Loader::isLocalName' => ['bool'],
'Yaf_Loader::registerLocalNamespace' => ['void', 'prefix'=>'mixed'],
'Yaf_Loader::registerNamespace' => ['bool', 'namespaces'=>'string|array', 'path='=>'string'],
'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::clearParams' => ['bool'],
'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' => ['list<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' => ['list<array<string,mixed>>'],
'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', 'object'=>'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' => ['list<array<string,mixed>>'],
'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|int|false', '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', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::getFromName' => ['string|false', 'entryname'=>'string', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::getNameIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getStatusString' => ['string|false'],
'ZipArchive::getStream' => ['resource|false', 'entryname'=>'string'],
'ZipArchive::isCompressionMethodSupported' => ['bool', 'method'=>'int', 'encode='=>'bool'],
'ZipArchive::isEncryptionMethodSupported' => ['bool', 'method'=>'int', 'encode='=>'bool'],
'ZipArchive::locateName' => ['int|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::open' => ['int|bool', 'source'=>'string', 'flags='=>'int'],
'ZipArchive::registerCancelCallback' => ['bool', 'callback'=>'callable'],
'ZipArchive::registerProgressCallback' => ['bool', 'rate'=>'float', 'callback'=>'callable'],
'ZipArchive::renameIndex' => ['bool', 'index'=>'int', 'new_name'=>'string'],
'ZipArchive::renameName' => ['bool', 'name'=>'string', 'new_name'=>'string'],
'ZipArchive::replaceFile' => ['bool', 'filename'=>'string', 'index'=>'int', 'start='=>'int', 'length='=>'int', 'flags='=>'int'],
'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::setMtimeIndex' => ['bool', 'index'=>'int', 'timestamp'=>'int', 'flags='=>'int'],
'ZipArchive::setMtimeName' => ['bool', 'name'=>'string', 'timestamp'=>'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|false', 'data'=>'string', 'max_length='=>'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 | 11,154 | `short_names` is still optional, so `=` that indicates it has to stay there. | vimeo-psalm | php |
@@ -153,6 +153,10 @@ func (agent *ecsAgent) appendFirelensFluentbitCapabilities(capabilities []*ecs.A
return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensFluentbit)
}
+func (agent *ecsAgent) appendEFSCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
+ return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityEFS)
+}
+
func (agent *ecsAgent) appendFirelensLoggingDriverCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
return appendNameOnlyAttribute(capabilities, capabilityPrefix+capabilityFirelensLoggingDriver)
} | 1 | // +build linux
// Copyright 2014-2019 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 app
import (
"strings"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi"
"github.com/aws/amazon-ecs-agent/agent/ecs_client/model/ecs"
"github.com/aws/amazon-ecs-agent/agent/ecscni"
"github.com/aws/amazon-ecs-agent/agent/taskresource/volume"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/aws-sdk-go/aws"
"github.com/cihub/seelog"
)
const (
AVX = "avx"
AVX2 = "avx2"
SSE41 = "sse4_1"
SSE42 = "sse4_2"
CpuInfoPath = "/proc/cpuinfo"
)
func (agent *ecsAgent) appendVolumeDriverCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
// "local" is default docker driver
capabilities = appendNameOnlyAttribute(capabilities, attributePrefix+capabilityDockerPluginInfix+volume.DockerLocalVolumeDriver)
// for non-standardized plugins, call docker pkg's plugins.Scan()
nonStandardizedPlugins, err := agent.mobyPlugins.Scan()
if err != nil {
seelog.Warnf("Scanning plugins failed: %v", err)
// do not return yet, we need the list of plugins below. range handles nil slice.
}
for _, pluginName := range nonStandardizedPlugins {
// Replace the ':' to '.' in the plugin name for attributes
capabilities = appendNameOnlyAttribute(capabilities,
attributePrefix+capabilityDockerPluginInfix+strings.Replace(pluginName, config.DockerTagSeparator, attributeSeparator, -1))
}
// for standardized plugins, call docker's plugin ls API
pluginEnabled := true
volumeDriverType := []string{dockerapi.VolumeDriverType}
standardizedPlugins, err := agent.dockerClient.ListPluginsWithFilters(agent.ctx, pluginEnabled, volumeDriverType, dockerclient.ListPluginsTimeout)
if err != nil {
seelog.Warnf("Listing plugins with filters enabled=%t, capabilities=%v failed: %v", pluginEnabled, volumeDriverType, err)
return capabilities
}
// For plugin with default tag latest, register two attributes with and without the latest tag
// as the tag is optional and can be added by docker or customer
for _, pluginName := range standardizedPlugins {
names := strings.Split(pluginName, config.DockerTagSeparator)
if len(names) > 1 && names[len(names)-1] == config.DefaultDockerTag {
capabilities = appendNameOnlyAttribute(capabilities, attributePrefix+capabilityDockerPluginInfix+strings.Join(names[:len(names)-1], attributeSeparator))
}
capabilities = appendNameOnlyAttribute(capabilities,
attributePrefix+capabilityDockerPluginInfix+strings.Replace(pluginName, config.DockerTagSeparator, attributeSeparator, -1))
}
return capabilities
}
func (agent *ecsAgent) appendNvidiaDriverVersionAttribute(capabilities []*ecs.Attribute) []*ecs.Attribute {
if agent.resourceFields != nil && agent.resourceFields.NvidiaGPUManager != nil {
driverVersion := agent.resourceFields.NvidiaGPUManager.GetDriverVersion()
if driverVersion != "" {
capabilities = appendNameOnlyAttribute(capabilities, attributePrefix+capabilityNvidiaDriverVersionInfix+driverVersion)
}
}
return capabilities
}
func (agent *ecsAgent) appendENITrunkingCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
if !agent.cfg.ENITrunkingEnabled {
return capabilities
}
capabilities = appendNameOnlyAttribute(capabilities, attributePrefix+taskENITrunkingAttributeSuffix)
return agent.appendBranchENIPluginVersionAttribute(capabilities)
}
func (agent *ecsAgent) appendBranchENIPluginVersionAttribute(capabilities []*ecs.Attribute) []*ecs.Attribute {
version, err := agent.cniClient.Version(ecscni.ECSBranchENIPluginName)
if err != nil {
seelog.Warnf(
"Unable to determine the version of the plugin '%s': %v",
ecscni.ECSBranchENIPluginName, err)
return capabilities
}
return append(capabilities, &ecs.Attribute{
Name: aws.String(attributePrefix + branchCNIPluginVersionSuffix),
Value: aws.String(version),
})
}
func (agent *ecsAgent) appendPIDAndIPCNamespaceSharingCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
return appendNameOnlyAttribute(capabilities, attributePrefix+capabiltyPIDAndIPCNamespaceSharing)
}
func (agent *ecsAgent) appendAppMeshCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
return appendNameOnlyAttribute(capabilities, attributePrefix+appMeshAttributeSuffix)
}
func (agent *ecsAgent) appendTaskEIACapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
capabilities = appendNameOnlyAttribute(capabilities, attributePrefix+taskEIAAttributeSuffix)
eiaRequiredFlags := []string{AVX, AVX2, SSE41, SSE42}
cpuInfo, err := utils.ReadCPUInfo(CpuInfoPath)
if err != nil {
seelog.Warnf("Unable to read cpuinfo: %v", err)
return capabilities
}
flagMap := utils.GetCPUFlags(cpuInfo)
missingFlags := []string{}
for _, requiredFlag := range eiaRequiredFlags {
if _, ok := flagMap[requiredFlag]; !ok {
missingFlags = append(missingFlags, requiredFlag)
}
}
if len(missingFlags) > 0 {
seelog.Infof("Missing cpu flags for EIA support: %v", strings.Join(missingFlags, ","))
return capabilities
}
return appendNameOnlyAttribute(capabilities, attributePrefix+taskEIAWithOptimizedCPU)
}
func (agent *ecsAgent) appendFirelensFluentdCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensFluentd)
}
func (agent *ecsAgent) appendFirelensFluentbitCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensFluentbit)
}
func (agent *ecsAgent) appendFirelensLoggingDriverCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
return appendNameOnlyAttribute(capabilities, capabilityPrefix+capabilityFirelensLoggingDriver)
}
func (agent *ecsAgent) appendFirelensConfigCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
capabilities = appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensConfigFile)
return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensConfigS3)
}
| 1 | 23,539 | missing calling of this method | aws-amazon-ecs-agent | go |
@@ -9,10 +9,12 @@ import (
"fmt"
"text/template"
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/fatih/structs"
"gopkg.in/yaml.v3"
- "github.com/aws/amazon-ecs-cli-v2/internal/pkg/archer"
+ archerCfn "github.com/aws/amazon-ecs-cli-v2/internal/pkg/deploy/cloudformation"
"github.com/aws/amazon-ecs-cli-v2/templates"
)
| 1 | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"bytes"
"errors"
"fmt"
"text/template"
"github.com/fatih/structs"
"gopkg.in/yaml.v3"
"github.com/aws/amazon-ecs-cli-v2/internal/pkg/archer"
"github.com/aws/amazon-ecs-cli-v2/templates"
)
// Provider defines a source of the artifacts
// that will be built and deployed via a pipeline
type Provider interface {
fmt.Stringer
Name() string
Properties() map[string]interface{}
}
type githubProvider struct {
properties *GithubProperties
}
func (p *githubProvider) Name() string {
return "github"
}
func (p *githubProvider) String() string {
return "github"
}
func (p *githubProvider) Properties() map[string]interface{} {
return structs.Map(p.properties)
}
// GithubProperties contain information for configuring a Github
// source provider.
type GithubProperties struct {
// use tag from https://godoc.org/github.com/fatih/structs#example-Map--Tags
// to specify the name of the field in the output properties
Repository string `structs:"repository" yaml:"repository"`
Branch string `structs:"branch" yaml:"branch"`
}
// NewProvider creates a source provider based on the type of
// the provided provider-specific configurations
func NewProvider(configs interface{}) (Provider, error) {
switch props := configs.(type) {
case *GithubProperties:
return &githubProvider{
properties: props,
}, nil
default:
return nil, &ErrUnknownProvider{unknownProviderProperties: props}
}
}
// PipelineSchemaMajorVersion is the major version number
// of the pipeline manifest schema
type PipelineSchemaMajorVersion int
const (
// Ver1 is the current schema major version of the pipeline.yml file.
Ver1 PipelineSchemaMajorVersion = iota + 1
)
// pipelineManifest contains information that defines the relationship
// and deployment ordering of your environments.
type pipelineManifest struct {
Version PipelineSchemaMajorVersion `yaml:"version"`
Source *Source `yaml:"source"`
Stages []PipelineStage `yaml:"stages"`
}
// Source defines the source of the artifacts to be built and deployed.
type Source struct {
ProviderName string `yaml:"provider"`
Properties map[string]interface{} `yaml:"properties"`
}
// PipelineStage represents configuration for each deployment stage
// of a workspace. A stage consists of the Archer Environment the pipeline
// is deloying to and the containerized applications that will be deployed.
type PipelineStage struct {
*AssociatedEnvironment `yaml:",inline"`
Applications []*archer.Application `yaml:"-"`
}
// AssociatedEnvironment defines the necessary information a pipline stage
// needs for an Archer Environment.
type AssociatedEnvironment struct {
Project string `yaml:"-"` // Name of the project this environment belongs to.
Name string `yaml:"name"` // Name of the environment, must be unique within a project.
Region string `yaml:"-"` // Name of the region this environment is stored in.
AccountID string `yaml:"-"` // Account ID of the account this environment is stored in.
Prod bool `yaml:"-"` // Whether or not this environment is a production environment.
}
// CreatePipeline returns a pipeline manifest object.
func CreatePipeline(provider Provider, stages ...PipelineStage) (archer.Manifest, error) {
// TODO: #221 Do more validations
var defaultStages []PipelineStage
if len(stages) == 0 {
defaultStages = []PipelineStage{
{
AssociatedEnvironment: &AssociatedEnvironment{
Name: "test",
},
},
{
AssociatedEnvironment: &AssociatedEnvironment{
Name: "prod",
},
},
}
}
return &pipelineManifest{
Version: Ver1,
Source: &Source{
ProviderName: provider.Name(),
Properties: provider.Properties(),
},
Stages: append(defaultStages, stages...),
}, nil
}
// Marshal serializes the pipeline manifest object into byte array that
// represents the pipeline.yml document.
func (m *pipelineManifest) Marshal() ([]byte, error) {
box := templates.Box()
content, err := box.FindString("cicd/pipeline.yml")
if err != nil {
return nil, err
}
tpl, err := template.New("pipelineTemplate").Parse(content)
if err != nil {
return nil, err
}
var buf bytes.Buffer
if err := tpl.Execute(&buf, *m); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// UnmarshalPipeline deserializes the YAML input stream into a pipeline
// manifest object. It returns an error if any issue occurs during
// deserialization or the YAML input contains invalid fields.
func UnmarshalPipeline(in []byte) (archer.Manifest, error) {
pm := pipelineManifest{}
err := yaml.Unmarshal(in, &pm)
if err != nil {
return nil, err
}
var version PipelineSchemaMajorVersion
if version, err = validateVersion(&pm); err != nil {
return nil, err
}
// TODO: #221 Do more validations
switch version {
case Ver1:
return &pm, nil
}
// we should never reach here, this is just to make the compiler happy
return nil, errors.New("unexpected error occurs while unmarshalling pipeline.yml")
}
func validateVersion(pm *pipelineManifest) (PipelineSchemaMajorVersion, error) {
switch pm.Version {
case Ver1:
return Ver1, nil
default:
return pm.Version,
&ErrInvalidPipelineManifestVersion{
invalidVersion: pm.Version,
}
}
}
// CFNTemplate serializes the manifest object into a CloudFormation template.
func (m *pipelineManifest) CFNTemplate() (string, error) {
// TODO: #223 Generate CFN template for the archer pipeline
return "", nil
}
| 1 | 10,714 | We could get rid of this dependency being forced on clients by changing the `StackConfiguration` interface abstraction to deal with strings instead of `cloudformation.Parameters` and `cloudformation.Tags`, and internally to the `cloudformation` package translate the input strings into the `service/cloudformation` package specific values hiding that from consumers. I don't think that should be taken on as part of this PR, but I think we should consider doing it at some point. | aws-copilot-cli | go |
@@ -25,6 +25,8 @@ import (
// Stress chaos is a chaos to generate plenty of stresses over a collection of pods.
// +kubebuilder:object:root=true
+// +kubebuilder:printcolumn:name="action",type=string,JSONPath=`.spec.action`
+// +kubebuilder:printcolumn:name="duration",type=string,JSONPath=`.spec.duration`
// +chaos-mesh:experiment
// StressChaos is the Schema for the stresschaos API | 1 | // Copyright 2021 Chaos Mesh 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 (
"fmt"
"github.com/docker/go-units"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Stress chaos is a chaos to generate plenty of stresses over a collection of pods.
// +kubebuilder:object:root=true
// +chaos-mesh:experiment
// StressChaos is the Schema for the stresschaos API
type StressChaos struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec defines the behavior of a time chaos experiment
Spec StressChaosSpec `json:"spec"`
// +optional
// Most recently observed status of the time chaos experiment
Status StressChaosStatus `json:"status"`
}
var _ InnerObjectWithCustomStatus = (*StressChaos)(nil)
var _ InnerObjectWithSelector = (*StressChaos)(nil)
var _ InnerObject = (*StressChaos)(nil)
// StressChaosSpec defines the desired state of StressChaos
type StressChaosSpec struct {
ContainerSelector `json:",inline"`
// Stressors defines plenty of stressors supported to stress system components out.
// You can use one or more of them to make up various kinds of stresses. At least
// one of the stressors should be specified.
// +optional
Stressors *Stressors `json:"stressors,omitempty"`
// StressngStressors defines plenty of stressors just like `Stressors` except that it's an experimental
// feature and more powerful. You can define stressors in `stress-ng` (see also `man stress-ng`) dialect,
// however not all of the supported stressors are well tested. It maybe retired in later releases. You
// should always use `Stressors` to define the stressors and use this only when you want more stressors
// unsupported by `Stressors`. When both `StressngStressors` and `Stressors` are defined, `StressngStressors`
// wins.
// +optional
StressngStressors string `json:"stressngStressors,omitempty"`
// Duration represents the duration of the chaos action
// +optional
Duration *string `json:"duration,omitempty" webhook:"Duration"`
}
// StressChaosStatus defines the observed state of StressChaos
type StressChaosStatus struct {
ChaosStatus `json:",inline"`
// Instances always specifies stressing instances
// +optional
Instances map[string]StressInstance `json:"instances,omitempty"`
}
// StressInstance is an instance generates stresses
type StressInstance struct {
// UID is the instance identifier
// +optional
UID string `json:"uid"`
// StartTime specifies when the instance starts
// +optional
StartTime *metav1.Time `json:"startTime"`
}
// Stressors defines plenty of stressors supported to stress system components out.
// You can use one or more of them to make up various kinds of stresses
type Stressors struct {
// MemoryStressor stresses virtual memory out
// +optional
MemoryStressor *MemoryStressor `json:"memory,omitempty"`
// CPUStressor stresses CPU out
// +optional
CPUStressor *CPUStressor `json:"cpu,omitempty"`
}
// Normalize the stressors to comply with stress-ng
func (in *Stressors) Normalize() (string, error) {
stressors := ""
if in.MemoryStressor != nil && in.MemoryStressor.Workers != 0 {
stressors += fmt.Sprintf(" --vm %d --vm-keep", in.MemoryStressor.Workers)
if len(in.MemoryStressor.Size) != 0 {
if in.MemoryStressor.Size[len(in.MemoryStressor.Size)-1] != '%' {
size, err := units.FromHumanSize(string(in.MemoryStressor.Size))
if err != nil {
return "", err
}
stressors += fmt.Sprintf(" --vm-bytes %d", size)
} else {
stressors += fmt.Sprintf(" --vm-bytes %s",
in.MemoryStressor.Size)
}
}
if in.MemoryStressor.Options != nil {
for _, v := range in.MemoryStressor.Options {
stressors += fmt.Sprintf(" %v ", v)
}
}
}
if in.CPUStressor != nil && in.CPUStressor.Workers != 0 {
stressors += fmt.Sprintf(" --cpu %d", in.CPUStressor.Workers)
if in.CPUStressor.Load != nil {
stressors += fmt.Sprintf(" --cpu-load %d",
*in.CPUStressor.Load)
}
if in.CPUStressor.Options != nil {
for _, v := range in.CPUStressor.Options {
stressors += fmt.Sprintf(" %v ", v)
}
}
}
return stressors, nil
}
// Stressor defines common configurations of a stressor
type Stressor struct {
// Workers specifies N workers to apply the stressor.
// Maximum 8192 workers can run by stress-ng
// +kubebuilder:validation:Maximum=8192
Workers int `json:"workers"`
}
// MemoryStressor defines how to stress memory out
type MemoryStressor struct {
Stressor `json:",inline"`
// Size specifies N bytes consumed per vm worker, default is the total available memory.
// One can specify the size as % of total available memory or in units of B, KB/KiB,
// MB/MiB, GB/GiB, TB/TiB.
// +optional
Size string `json:"size,omitempty" webhook:"Bytes"`
// extend stress-ng options
// +optional
Options []string `json:"options,omitempty"`
}
// CPUStressor defines how to stress CPU out
type CPUStressor struct {
Stressor `json:",inline"`
// Load specifies P percent loading per CPU worker. 0 is effectively a sleep (no load) and 100
// is full loading.
// +optional
Load *int `json:"load,omitempty"`
// extend stress-ng options
// +optional
Options []string `json:"options,omitempty"`
}
func (obj *StressChaos) GetSelectorSpecs() map[string]interface{} {
return map[string]interface{}{
".": &obj.Spec.ContainerSelector,
}
}
func (obj *StressChaos) GetCustomStatus() interface{} {
return &obj.Status.Instances
}
| 1 | 25,451 | `StressChaos` does not contains a field .spec.action | chaos-mesh-chaos-mesh | go |
@@ -1931,7 +1931,12 @@ class FunctionCallTest extends TestCase
return $b["a"];
}
- a(["a" => "hello"]);',
+ function b(string $str): string
+ {
+ return $str;
+ }
+
+ a(["a" => b("hello")]);',
'error_message' => 'InvalidScalarArgument',
],
'objectLikeKeyChecksAgainstDifferentTKeyedArray' => [ | 1 | <?php
namespace Psalm\Tests;
use Psalm\Config;
use Psalm\Context;
use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;
use const DIRECTORY_SEPARATOR;
class FunctionCallTest extends TestCase
{
use InvalidCodeAnalysisTestTrait;
use ValidCodeAnalysisTestTrait;
/**
* @return iterable<string,array{string,assertions?:array<string,string>,error_levels?:string[]}>
*/
public function providerValidCodeParse(): iterable
{
return [
'preg_grep' => [
'<?php
/**
* @param array<int,string> $strings
* @return array<int,string>
*/
function filter(array $strings): array {
return preg_grep("/search/", $strings, PREG_GREP_INVERT);
}
'
],
'typedArrayWithDefault' => [
'<?php
class A {}
/** @param array<A> $a */
function fooFoo(array $a = []): void {
}',
],
'abs' => [
'<?php
$a = abs(-5);
$b = abs(-7.5);
$c = $_GET["c"];
$c = is_numeric($c) ? abs($c) : null;',
'assertions' => [
'$a' => 'int|positive-int',
'$b' => 'float',
'$c' => 'float|int|null|positive-int',
],
'error_levels' => ['MixedAssignment', 'MixedArgument'],
],
'validDocblockParamDefault' => [
'<?php
/**
* @param int|false $p
* @return void
*/
function f($p = false) {}',
],
'byRefNewString' => [
'<?php
function fooFoo(?string &$v): void {}
fooFoo($a);',
],
'byRefVariableFunctionExistingArray' => [
'<?php
$arr = [];
function fooFoo(array &$v): void {}
$function = "fooFoo";
$function($arr);
if ($arr) {}',
],
'byRefProperty' => [
'<?php
class A {
/** @var string */
public $foo = "hello";
}
$a = new A();
function fooFoo(string &$v): void {}
fooFoo($a->foo);',
],
'namespaced' => [
'<?php
namespace A;
/** @return void */
function f(int $p) {}
f(5);',
],
'namespacedRootFunctionCall' => [
'<?php
namespace {
/** @return void */
function foo() { }
}
namespace A\B\C {
foo();
}',
],
'namespacedAliasedFunctionCall' => [
'<?php
namespace Aye {
/** @return void */
function foo() { }
}
namespace Bee {
use Aye as A;
A\foo();
}',
],
'noRedundantConditionAfterArrayObjectCountCheck' => [
'<?php
/** @var ArrayObject<int, int> */
$a = [];
$b = 5;
if (count($a)) {}',
],
'noRedundantConditionAfterMixedOrEmptyArrayCountCheck' => [
'<?php
function foo(string $s) : void {
$a = $_GET["s"] ?: [];
if (count($a)) {}
if (!count($a)) {}
}',
'assertions' => [],
'error_levels' => ['MixedAssignment', 'MixedArgument'],
],
'objectLikeArrayAssignmentInConditional' => [
'<?php
$a = [];
if (rand(0, 1)) {
$a["a"] = 5;
}
if (count($a)) {}
if (!count($a)) {}',
],
'noRedundantConditionAfterCheckingExplodeLength' => [
'<?php
/** @var string */
$s = "hello";
$segments = explode(".", $s);
if (count($segments) === 1) {}',
],
'arrayPopNonEmptyAfterThreeAssertions' => [
'<?php
class A {}
class B extends A {
/** @var array<int, string> */
public $arr = [];
}
/** @var array<A> */
$replacement_stmts = [];
if (!$replacement_stmts
|| !$replacement_stmts[0] instanceof B
|| count($replacement_stmts[0]->arr) > 1
) {
return null;
}
$b = $replacement_stmts[0]->arr;',
'assertions' => [
'$b' => 'array<int, string>',
],
],
'countMoreThan0CanBeInverted' => [
'<?php
$a = [];
if (rand(0, 1)) {
$a[] = "hello";
}
if (count($a) > 0) {
exit;
}',
'assertions' => [
'$a' => 'array<empty, empty>',
],
],
'byRefAfterCallable' => [
'<?php
/**
* @param callable $callback
* @return void
*/
function route($callback) {
if (!is_callable($callback)) { }
$a = preg_match("", "", $b);
if ($b[0]) {}
}',
'assertions' => [],
'error_levels' => [
'MixedAssignment',
'MixedArrayAccess',
'RedundantConditionGivenDocblockType',
],
],
'ignoreNullablePregReplace' => [
'<?php
function foo(string $s): string {
$s = preg_replace("/hello/", "", $s);
if ($s === null) {
return "hello";
}
return $s;
}
function bar(string $s): string {
$s = preg_replace("/hello/", "", $s);
return $s;
}
function bat(string $s): ?string {
$s = preg_replace("/hello/", "", $s);
return $s;
}',
],
'extractVarCheck' => [
'<?php
function takesString(string $str): void {}
$foo = null;
$a = ["$foo" => "bar"];
extract($a);
takesString($foo);',
'assertions' => [],
'error_levels' => [
'MixedAssignment',
'MixedArrayAccess',
'MixedArgument',
],
],
'compact' => [
'<?php
/**
* @return array<string, mixed>
*/
function test(): array {
return compact(["val"]);
}',
],
'objectLikeKeyChecksAgainstGeneric' => [
'<?php
/**
* @param array<string, string> $b
*/
function a($b): string
{
return $b["a"];
}
a(["a" => "hello"]);',
],
'objectLikeKeyChecksAgainstTKeyedArray' => [
'<?php
/**
* @param array{a: string} $b
*/
function a($b): string
{
return $b["a"];
}
a(["a" => "hello"]);',
],
'getenv' => [
'<?php
$a = getenv();
$b = getenv("some_key");',
'assertions' => [
'$a' => 'array<string, string>',
'$b' => 'false|string',
],
],
'ignoreFalsableFileGetContents' => [
'<?php
function foo(string $s): string {
return file_get_contents($s);
}
function bar(string $s): string {
$a = file_get_contents($s);
if ($a === false) {
return "hello";
}
return $a;
}
/**
* @return false|string
*/
function bat(string $s) {
return file_get_contents($s);
}',
],
'validCallables' => [
'<?php
class A {
public static function b() : void {}
}
function c() : void {}
["a", "b"]();
"A::b"();
"c"();',
],
'noInvalidOperandForCoreFunctions' => [
'<?php
function foo(string $a, string $b) : int {
$aTime = strtotime($a);
$bTime = strtotime($b);
return $aTime - $bTime;
}',
],
'strposIntSecondParam' => [
'<?php
function hasZeroByteOffset(string $s) : bool {
return strpos($s, 0) !== false;
}',
],
'functionCallInGlobalScope' => [
'<?php
$a = function() use ($argv) : void {};',
],
'varExport' => [
'<?php
$a = var_export(["a"], true);',
'assertions' => [
'$a' => 'string',
],
],
'varExportConstFetch' => [
'<?php
class Foo {
const BOOL_VAR_EXPORT_RETURN = true;
/**
* @param mixed $mixed
*/
public static function Baz($mixed) : string {
return var_export($mixed, self::BOOL_VAR_EXPORT_RETURN);
}
}',
],
'explode' => [
'<?php
/** @var string $string */
$elements = explode(" ", $string);',
'assertions' => [
'$elements' => 'non-empty-list<string>',
],
],
'explodeWithPositiveLimit' => [
'<?php
/** @var string $string */
$elements = explode(" ", $string, 5);',
'assertions' => [
'$elements' => 'non-empty-list<string>',
],
],
'explodeWithNegativeLimit' => [
'<?php
/** @var string $string */
$elements = explode(" ", $string, -5);',
'assertions' => [
'$elements' => 'list<string>',
],
],
'explodeWithDynamicLimit' => [
'<?php
/**
* @var string $string
* @var int $limit
*/
$elements = explode(" ", $string, $limit);',
'assertions' => [
'$elements' => 'list<string>',
],
],
'explodeWithDynamicDelimiter' => [
'<?php
/**
* @var string $delim
* @var string $string
*/
$elements = explode($delim, $string);',
'assertions' => [
'$elements' => 'false|non-empty-list<string>',
],
],
'explodeWithDynamicDelimiterAndPositiveLimit' => [
'<?php
/**
* @var string $delim
* @var string $string
*/
$elements = explode($delim, $string, 5);',
'assertions' => [
'$elements' => 'false|non-empty-list<string>',
],
],
'explodeWithDynamicDelimiterAndNegativeLimit' => [
'<?php
/**
* @var string $delim
* @var string $string
*/
$elements = explode($delim, $string, -5);',
'assertions' => [
'$elements' => 'false|list<string>',
],
],
'explodeWithDynamicDelimiterAndLimit' => [
'<?php
/**
* @var string $delim
* @var string $string
* @var int $limit
*/
$elements = explode($delim, $string, $limit);',
'assertions' => [
'$elements' => 'false|list<string>',
],
],
'explodeWithDynamicNonEmptyDelimiter' => [
'<?php
/**
* @var non-empty-string $delim
* @var string $string
*/
$elements = explode($delim, $string);',
'assertions' => [
'$elements' => 'non-empty-list<string>',
],
],
'explodeWithLiteralNonEmptyDelimiter' => [
'<?php
/**
* @var string $string
*/
$elements = explode(" ", $string);',
'assertions' => [
'$elements' => 'non-empty-list<string>',
],
],
'explodeWithLiteralEmptyDelimiter' => [
'<?php
/**
* @var string $string
*/
$elements = explode("", $string);',
'assertions' => [
'$elements' => 'false',
],
],
'explodeWithPossiblyFalse' => [
'<?php
/** @return non-empty-list<string> */
function exploder(string $d, string $s) : array {
return explode($d, $s);
}',
],
'allowPossiblyUndefinedClassInClassExists' => [
'<?php
if (class_exists(Foo::class)) {}',
],
'allowConstructorAfterClassExists' => [
'<?php
function foo(string $s) : void {
if (class_exists($s)) {
new $s();
}
}',
'assertions' => [],
'error_levels' => ['MixedMethodCall'],
],
'next' => [
'<?php
$arr = ["one", "two", "three"];
$n = next($arr);',
'assertions' => [
'$n' => 'false|string',
],
],
'iteratorToArray' => [
'<?php
/**
* @return Generator<stdClass>
*/
function generator(): Generator {
yield new stdClass;
}
$a = iterator_to_array(generator());',
'assertions' => [
'$a' => 'array<array-key, stdClass>',
],
],
'iteratorToArrayWithGetIterator' => [
'<?php
class C implements IteratorAggregate {
/**
* @return Traversable<int,string>
*/
public function getIterator() {
yield 1 => "1";
}
}
$a = iterator_to_array(new C);',
'assertions' => [
'$a' => 'array<int, string>',
],
],
'iteratorToArrayWithGetIteratorReturningList' => [
'<?php
class C implements IteratorAggregate {
/**
* @return Traversable<int,string>
*/
public function getIterator() {
yield 1 => "1";
}
}
$a = iterator_to_array(new C, false);',
'assertions' => [
'$a' => 'list<string>',
],
],
'strtrWithPossiblyFalseFirstArg' => [
'<?php
/**
* @param false|string $str
* @param array<string, string> $replace_pairs
* @return string
*/
function strtr_wrapper($str, array $replace_pairs) {
/** @psalm-suppress PossiblyFalseArgument */
return strtr($str, $replace_pairs);
}',
],
'versionCompare' => [
'<?php
/** @return "="|"==" */
function getString() : string {
return rand(0, 1) ? "==" : "=";
}
$a = version_compare("5.0.0", "7.0.0");
$b = version_compare("5.0.0", "7.0.0", "==");
$c = version_compare("5.0.0", "7.0.0", getString());
',
'assertions' => [
'$a' => 'int',
'$b' => 'bool',
'$c' => 'bool',
],
],
'getTimeOfDay' => [
'<?php
$a = gettimeofday(true) - gettimeofday(true);
$b = gettimeofday();
$c = gettimeofday(false);',
'assertions' => [
'$a' => 'float',
'$b' => 'array<string, int>',
'$c' => 'array<string, int>',
],
],
'parseUrlArray' => [
'<?php
function foo(string $s) : string {
$parts = parse_url($s);
return $parts["host"] ?? "";
}
function hereisanotherone(string $s) : string {
$parsed = parse_url($s);
if (isset($parsed["host"])) {
return $parsed["host"];
}
return "";
}
function hereisthelastone(string $s) : string {
$parsed = parse_url($s);
if (isset($parsed["host"])) {
return $parsed["host"];
}
return "";
}
function portisint(string $s) : int {
$parsed = parse_url($s);
if (isset($parsed["port"])) {
return $parsed["port"];
}
return 80;
}
function portismaybeint(string $s) : ? int {
$parsed = parse_url($s);
return $parsed["port"] ?? null;
}
$porta = parse_url("", PHP_URL_PORT);
$porte = parse_url("localhost:443", PHP_URL_PORT);',
'assertions' => [
'$porta' => 'false|int|null',
'$porte' => 'false|int|null',
],
'error_levels' => ['MixedReturnStatement', 'MixedInferredReturnType'],
],
'parseUrlComponent' => [
'<?php
function foo(string $s) : string {
return parse_url($s, PHP_URL_HOST) ?? "";
}
function bar(string $s) : string {
return parse_url($s, PHP_URL_HOST);
}
function bag(string $s) : string {
$host = parse_url($s, PHP_URL_HOST);
if (is_string($host)) {
return $host;
}
return "";
}',
],
'parseUrlTypes' => [
'<?php
$url = "foo";
$components = parse_url($url);
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$port = parse_url($url, PHP_URL_PORT);
$user = parse_url($url, PHP_URL_USER);
$pass = parse_url($url, PHP_URL_PASS);
$path = parse_url($url, PHP_URL_PATH);
$query = parse_url($url, PHP_URL_QUERY);
$fragment = parse_url($url, PHP_URL_FRAGMENT);',
'assertions' => [
'$components' => 'array{fragment?: string, host?: string, pass?: string, path?: string, port?: int, query?: string, scheme?: string, user?: string}|false',
'$scheme' => 'false|null|string',
'$host' => 'false|null|string',
'$port' => 'false|int|null',
'$user' => 'false|null|string',
'$pass' => 'false|null|string',
'$path' => 'false|null|string',
'$query' => 'false|null|string',
'$fragment' => 'false|null|string',
],
],
'triggerUserError' => [
'<?php
function mightLeave() : string {
if (rand(0, 1)) {
trigger_error("bad", E_USER_ERROR);
} else {
return "here";
}
}',
],
'getParentClass' => [
'<?php
class A {}
class B extends A {}
$b = get_parent_class(new A());
if ($b === false) {}
$c = new $b();',
'assertions' => [],
'error_levels' => ['MixedMethodCall'],
],
'suppressError' => [
'<?php
$a = @file_get_contents("foo");',
'assertions' => [
'$a' => 'false|string',
],
],
'echo' => [
'<?php
echo false;',
],
'printrOutput' => [
'<?php
function foo(string $s) : void {
echo $s;
}
foo(print_r(1, true));',
],
'microtime' => [
'<?php
$a = microtime(true);
$b = microtime();
/** @psalm-suppress InvalidScalarArgument */
$c = microtime(1);
$d = microtime(false);',
'assertions' => [
'$a' => 'float',
'$b' => 'string',
'$c' => 'float|string',
'$d' => 'string',
],
],
'filterVar' => [
'<?php
function filterInt(string $s) : int {
$filtered = filter_var($s, FILTER_VALIDATE_INT);
if ($filtered === false) {
return 0;
}
return $filtered;
}
function filterNullableInt(string $s) : ?int {
return filter_var($s, FILTER_VALIDATE_INT, ["options" => ["default" => null]]);
}
function filterIntWithDefault(string $s) : int {
return filter_var($s, FILTER_VALIDATE_INT, ["options" => ["default" => 5]]);
}
function filterBool(string $s) : bool {
return filter_var($s, FILTER_VALIDATE_BOOLEAN);
}
function filterNullableBool(string $s) : ?bool {
return filter_var($s, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
function filterNullableBoolWithFlagsArray(string $s) : ?bool {
return filter_var($s, FILTER_VALIDATE_BOOLEAN, ["flags" => FILTER_NULL_ON_FAILURE]);
}
function filterFloat(string $s) : float {
$filtered = filter_var($s, FILTER_VALIDATE_FLOAT);
if ($filtered === false) {
return 0.0;
}
return $filtered;
}
function filterFloatWithDefault(string $s) : float {
return filter_var($s, FILTER_VALIDATE_FLOAT, ["options" => ["default" => 5.0]]);
}',
],
'callVariableVar' => [
'<?php
class Foo
{
public static function someInt(): int
{
return 1;
}
}
/**
* @return int
*/
function makeInt()
{
$fooClass = Foo::class;
return $fooClass::someInt();
}',
],
'expectsIterable' => [
'<?php
function foo(iterable $i) : void {}
function bar(array $a) : void {
foo($a);
}',
],
'getTypeHasValues' => [
'<?php
/**
* @param mixed $maybe
*/
function matchesTypes($maybe) : void {
$t = gettype($maybe);
if ($t === "object") {}
}',
],
'getTypeSwitchClosedResource' => [
'<?php
$data = "foo";
switch (gettype($data)) {
case "resource (closed)":
case "unknown type":
return "foo";
}',
],
'functionResolutionInNamespace' => [
'<?php
namespace Foo;
function sort(int $_) : void {}
sort(5);',
],
'rangeWithIntStep' => [
'<?php
function foo(int $bar) : string {
return (string) $bar;
}
foreach (range(1, 10, 1) as $x) {
foo($x);
}',
],
'rangeWithNoStep' => [
'<?php
function foo(int $bar) : string {
return (string) $bar;
}
foreach (range(1, 10) as $x) {
foo($x);
}',
],
'rangeWithNoStepAndString' => [
'<?php
function foo(string $bar) : void {}
foreach (range("a", "z") as $x) {
foo($x);
}',
],
'rangeWithFloatStep' => [
'<?php
function foo(float $bar) : string {
return (string) $bar;
}
foreach (range(1, 10, .3) as $x) {
foo($x);
}',
],
'rangeWithFloatStart' => [
'<?php
function foo(float $bar) : string {
return (string) $bar;
}
foreach (range(1.5, 10) as $x) {
foo($x);
}',
],
'rangeWithIntOrFloatStep' => [
'<?php
/** @var int|float */
$step = 1;
$a = range(1, 10, $step);
/** @var int */
$step = 1;
$b = range(1, 10, $step);
/** @var float */
$step = 1.;
$c = range(1, 10, $step);
',
'assertions' => [
'$a' => 'non-empty-list<float|int>',
'$b' => 'non-empty-list<int>',
'$c' => 'non-empty-list<float>',
],
],
'duplicateNamespacedFunction' => [
'<?php
namespace Bar;
function sort() : void {}',
],
'arrayMapAfterFunctionMissingFile' => [
'<?php
require_once(FOO);
$urls = array_map("strval", [1, 2, 3]);',
[],
'error_levels' => ['UndefinedConstant', 'UnresolvableInclude'],
],
'noNamespaceClash' => [
'<?php
namespace FunctionNamespace {
function foo() : void {}
}
namespace ClassNamespace {
class Foo {}
}
namespace {
use ClassNamespace\Foo;
use function FunctionNamespace\foo;
new Foo();
foo();
}',
],
'hashInit70' => [
'<?php
$h = hash_init("sha256");',
[
'$h' => 'resource',
],
[],
'7.1',
],
'hashInit71' => [
'<?php
$h = hash_init("sha256");',
[
'$h' => 'resource',
],
[],
'7.1',
],
'hashInit72' => [
'<?php
$h = hash_init("sha256");',
[
'$h' => 'HashContext|false',
],
[],
'7.2',
],
'hashInit73' => [
'<?php
$h = hash_init("sha256");',
[
'$h' => 'HashContext|false',
],
[],
'7.3',
],
'hashInit80' => [
'<?php
$h = hash_init("sha256");',
[
'$h' => 'HashContext',
],
[],
'8.0',
],
'nullableByRef' => [
'<?php
function foo(?string &$s) : void {}
function bar() : void {
foo($bar);
}',
],
'getClassNewInstance' => [
'<?php
interface I {}
class C implements I {}
class Props {
/** @var class-string<I>[] */
public $arr = [];
}
(new Props)->arr[] = get_class(new C);',
],
'getClassVariable' => [
'<?php
interface I {}
class C implements I {}
$c_instance = new C;
class Props {
/** @var class-string<I>[] */
public $arr = [];
}
(new Props)->arr[] = get_class($c_instance);',
],
'getClassAnonymousNewInstance' => [
'<?php
interface I {}
class Props {
/** @var class-string<I>[] */
public $arr = [];
}
(new Props)->arr[] = get_class(new class implements I{});',
],
'getClassAnonymousVariable' => [
'<?php
interface I {}
$anon_instance = new class implements I {};
class Props {
/** @var class-string<I>[] */
public $arr = [];
}
(new Props)->arr[] = get_class($anon_instance);',
],
'mktime' => [
'<?php
/** @psalm-suppress InvalidScalarArgument */
$a = mktime("foo");
/** @psalm-suppress MixedArgument */
$b = mktime($_GET["foo"]);
$c = mktime(1, 2, 3);',
'assertions' => [
'$a' => 'false|int',
'$b' => 'false|int',
'$c' => 'int',
],
],
'PHP73-hrtime' => [
'<?php
$a = hrtime(true);
$b = hrtime();
/** @psalm-suppress InvalidScalarArgument */
$c = hrtime(1);
$d = hrtime(false);',
'assertions' => [
'$a' => 'int',
'$b' => 'array{0: int, 1: int}',
'$c' => 'array{0: int, 1: int}|int',
'$d' => 'array{0: int, 1: int}',
],
],
'PHP73-hrtimeCanBeFloat' => [
'<?php
$a = hrtime(true);
if (is_int($a)) {}
if (is_float($a)) {}',
],
'min' => [
'<?php
$a = min(0, 1);
$b = min([0, 1]);
$c = min("a", "b");
$d = min(1, 2, 3, 4);
$e = min(1, 2, 3, 4, 5);
$f = min(...[1, 2, 3]);',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'string',
'$d' => 'int',
'$e' => 'int',
'$f' => 'int',
],
],
'minUnpackedArg' => [
'<?php
$f = min(...[1, 2, 3]);',
'assertions' => [
'$f' => 'int',
],
],
'sscanf' => [
'<?php
sscanf("10:05:03", "%d:%d:%d", $hours, $minutes, $seconds);',
'assertions' => [
'$hours' => 'float|int|null|string',
'$minutes' => 'float|int|null|string',
'$seconds' => 'float|int|null|string',
],
],
'noImplicitAssignmentToStringFromMixedWithDocblockTypes' => [
'<?php
/** @param string $s */
function takesString($s) : void {}
function takesInt(int $i) : void {}
/**
* @param mixed $s
* @psalm-suppress MixedArgument
*/
function bar($s) : void {
takesString($s);
takesInt($s);
}',
],
'ignoreNullableIssuesAfterMixedCoercion' => [
'<?php
function takesNullableString(?string $s) : void {}
function takesString(string $s) : void {}
/**
* @param mixed $s
* @psalm-suppress MixedArgument
*/
function bar($s) : void {
takesNullableString($s);
takesString($s);
}',
],
'countableSimpleXmlElement' => [
'<?php
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><a><b></b><b></b></a>");
echo count($xml);',
],
'countableCallableArray' => [
'<?php
/** @param callable|false $x */
function example($x) : void {
if (is_array($x)) {
echo "Count is: " . count($x);
}
}'
],
'countNonEmptyArrayShouldBePositiveInt' => [
'<?php
/**
* @psalm-pure
* @param non-empty-list $x
* @return positive-int
*/
function example($x) : int {
return count($x);
}',
],
'countListShouldBeZeroOrPositive' => [
'<?php
/**
* @psalm-pure
* @param list $x
* @return positive-int|0
*/
function example($x) : int {
return count($x);
}',
],
'countArrayShouldBeZeroOrPositive' => [
'<?php
/**
* @psalm-pure
* @param array $x
* @return positive-int|0
*/
function example($x) : int {
return count($x);
}',
],
'countEmptyArrayShouldBeZero' => [
'<?php
/**
* @psalm-pure
* @param array<empty, empty> $x
* @return 0
*/
function example($x) : int {
return count($x);
}',
],
'countConstantSizeArrayShouldBeConstantInteger' => [
'<?php
/**
* @psalm-pure
* @param array{int, int, string} $x
* @return 3
*/
function example($x) : int {
return count($x);
}',
],
'countCallableArrayShouldBe2' => [
'<?php
/**
* @psalm-pure
* @return 2
*/
function example(callable $x) : int {
assert(is_array($x));
return count($x);
}',
],
'countOnPureObjectIsPure' => [
'<?php
class PureCountable implements \Countable {
/** @psalm-pure */
public function count(): int { return 1; }
}
/** @psalm-pure */
function example(PureCountable $x) : int {
return count($x);
}',
],
'refineWithTraitExists' => [
'<?php
function foo(string $s) : void {
if (trait_exists($s)) {
new ReflectionClass($s);
}
}',
],
'refineWithClassExistsOrTraitExists' => [
'<?php
function foo(string $s) : void {
if (trait_exists($s) || class_exists($s)) {
new ReflectionClass($s);
}
}
function bar(string $s) : void {
if (class_exists($s) || trait_exists($s)) {
new ReflectionClass($s);
}
}
function baz(string $s) : void {
if (class_exists($s) || interface_exists($s) || trait_exists($s)) {
new ReflectionClass($s);
}
}',
],
'minSingleArg' => [
'<?php
/** @psalm-suppress TooFewArguments */
min(0);',
],
'PHP73-allowIsCountableToInformType' => [
'<?php
function getObject() : iterable{
return [];
}
$iterableObject = getObject();
if (is_countable($iterableObject)) {
if (count($iterableObject) === 0) {}
}',
],
'versionCompareAsCallable' => [
'<?php
$a = ["1.0", "2.0"];
usort($a, "version_compare");',
],
'coerceToObjectAfterBeingCalled' => [
'<?php
class Foo {
public function bar() : void {}
}
function takesFoo(Foo $foo) : void {}
/** @param mixed $f */
function takesMixed($f) : void {
if (rand(0, 1)) {
$f = new Foo();
}
/** @psalm-suppress MixedArgument */
takesFoo($f);
$f->bar();
}',
],
'functionExists' => [
'<?php
if (!function_exists("in_array")) {
function in_array($a, $b) {
return true;
}
}',
],
'pregMatch' => [
'<?php
function takesInt(int $i) : void {}
takesInt(preg_match("{foo}", "foo"));',
],
'pregMatch2' => [
'<?php
$r = preg_match("{foo}", "foo");',
'assertions' => [
'$r===' => '0|1|false',
],
],
'pregMatchWithMatches' => [
'<?php
/** @param string[] $matches */
function takesMatches(array $matches) : void {}
preg_match("{foo}", "foo", $matches);
takesMatches($matches);',
],
'pregMatchWithMatches2' => [
'<?php
$r = preg_match("{foo}", "foo", $matches);',
'assertions' => [
'$r===' => '0|1|false',
'$matches===' => 'array<array-key, string>',
],
],
'pregMatchWithOffset' => [
'<?php
/** @param string[] $matches */
function takesMatches(array $matches) : void {}
preg_match("{foo}", "foo", $matches, 0, 10);
takesMatches($matches);',
],
'pregMatchWithOffset2' => [
'<?php
$r = preg_match("{foo}", "foo", $matches, 0, 10);',
'assertions' => [
'$r===' => '0|1|false',
'$matches===' => 'array<array-key, string>',
],
],
'pregMatchWithFlags' => [
'<?php
function takesInt(int $i) : void {}
if (preg_match("{foo}", "this is foo", $matches, PREG_OFFSET_CAPTURE)) {
takesInt($matches[0][1]);
}',
],
'pregMatchWithFlagOffsetCapture' => [
'<?php
$r = preg_match("{foo}", "foo", $matches, PREG_OFFSET_CAPTURE);',
'assertions' => [
'$r===' => '0|1|false',
'$matches===' => 'array<array-key, array{string, int}>',
],
],
'PHP72-pregMatchWithFlagUnmatchedAsNull' => [
'<?php
$r = preg_match("{foo}", "foo", $matches, PREG_UNMATCHED_AS_NULL);',
'assertions' => [
'$r===' => '0|1|false',
'$matches===' => 'array<array-key, null|string>',
],
],
'PHP72-pregMatchWithFlagOffsetCaptureAndUnmatchedAsNull' => [
'<?php
$r = preg_match("{foo}", "foo", $matches, PREG_OFFSET_CAPTURE | PREG_UNMATCHED_AS_NULL);',
'assertions' => [
'$r===' => '0|1|false',
'$matches===' => 'array<array-key, array{null|string, int}>',
],
],
'pregReplaceCallback' => [
'<?php
function foo(string $s) : string {
return preg_replace_callback(
\'/<files (psalm-version="[^"]+") (?:php-version="(.+)">\n)/\',
/** @param string[] $matches */
function (array $matches) : string {
return $matches[1];
},
$s
);
}',
],
'pregReplaceCallbackWithArray' => [
'<?php
/**
* @param string[] $ids
*/
function(array $ids): array {
return \preg_replace_callback(
"",
fn (array $matches) => $matches[4],
$ids
);
};',
'assertions' => [],
'error_levels' => [],
'7.4'
],
'compactDefinedVariable' => [
'<?php
/**
* @return array<string, mixed>
*/
function foo(int $a, string $b, bool $c) : array {
return compact("a", "b", "c");
}',
],
'PHP73-setCookiePhp73' => [
'<?php
setcookie(
"name",
"value",
[
"path" => "/",
"expires" => 0,
"httponly" => true,
"secure" => true,
"samesite" => "Lax"
]
);',
],
'printrBadArg' => [
'<?php
/** @psalm-suppress InvalidScalarArgument */
$a = print_r([], 1);
echo $a;',
],
'dontCoerceCallMapArgs' => [
'<?php
function getStr() : ?string {
return rand(0,1) ? "test" : null;
}
function test() : void {
$g = getStr();
/** @psalm-suppress PossiblyNullArgument */
$x = strtoupper($g);
$c = "prefix " . (strtoupper($g ?? "") === "x" ? "xa" : "ya");
echo "$x, $c\n";
}'
],
'mysqliRealConnectFunctionAllowsNullParameters' => [
'<?php
$mysqli = mysqli_init();
mysqli_real_connect($mysqli, null, \'test\', null);',
],
'callUserFunc' => [
'<?php
$func = function(int $arg1, int $arg2) : int {
return $arg1 * $arg2;
};
$a = call_user_func($func, 2, 4);',
[
'$a' => 'int',
]
],
'callUserFuncArray' => [
'<?php
$func = function(int $arg1, int $arg2) : int {
return $arg1 * $arg2;
};
$a = call_user_func_array($func, [2, 4]);',
[
'$a' => 'int',
]
],
'dateTest' => [
'<?php
$y = date("Y");
$m = date("m");
$F = date("F");
$y2 = date("Y", 10000);
$F2 = date("F", 10000);
/** @psalm-suppress MixedArgument */
$F3 = date("F", $_GET["F3"]);',
[
'$y' => 'numeric-string',
'$m' => 'numeric-string',
'$F' => 'string',
'$y2' => 'numeric-string',
'$F2' => 'string',
'$F3' => 'false|string',
]
],
'sscanfReturnTypeWithTwoParameters' => [
'<?php
$data = sscanf("42 psalm road", "%s %s");',
[
'$data' => 'list<float|int|null|string>|null',
]
],
'sscanfReturnTypeWithMoreThanTwoParameters' => [
'<?php
$n = sscanf("42 psalm road", "%s %s", $p1, $p2);',
[
'$n' => 'int',
'$p1' => 'float|int|null|string',
'$p2' => 'float|int|null|string',
],
],
'writeArgsAllowed' => [
'<?php
/**
* @param 0|256|512|768 $flags
* @return false|int
*/
function safeMatch(string $pattern, string $subject, ?array $matches = null, int $flags = 0) {
return \preg_match($pattern, $subject, $matches, $flags);
}
safeMatch("/a/", "b");'
],
'fgetcsv' => [
'<?php
$headers = fgetcsv(fopen("test.txt", "r"));
if (empty($headers)) {
throw new Exception("invalid headers");
}
print_r(array_map("strval", $headers));'
],
'allowListEqualToRange' => [
'<?php
/** @param array<int, int> $two */
function collectCommit(array $one, array $two) : void {
if ($one && array_values($one) === array_values($two)) {}
}'
],
'pregMatchAll' => [
'<?php
/**
* @return array<list<string>>
*/
function extractUsernames(string $input): array {
preg_match_all(\'/([a-zA-Z])*/\', $input, $matches);
return $matches;
}'
],
'pregMatchAllOffsetCapture' => [
'<?php
function foo(string $input): array {
preg_match_all(\'/([a-zA-Z])*/\', $input, $matches, PREG_OFFSET_CAPTURE);
return $matches[0];
}'
],
'pregMatchAllReturnsFalse' => [
'<?php
/**
* @return int|false
*/
function badpattern() {
return @preg_match_all("foo", "foo", $matches);
}'
],
'strposAllowDictionary' => [
'<?php
function sayHello(string $format): void {
if (strpos("abcdefghijklmno", $format)) {}
}',
],
'curlInitIsResourceAllowedIn7x' => [
'<?php
$ch = curl_init();
if (!is_resource($ch)) {}',
[],
[],
'7.4'
],
'pregSplit' => [
'<?php
/** @return non-empty-list */
function foo(string $s) {
return preg_split("/ /", $s);
}'
],
'pregSplitWithFlags' => [
'<?php
/** @return list<string> */
function foo(string $s) {
return preg_split("/ /", $s, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
}'
],
'mbConvertEncodingWithArray' => [
'<?php
/**
* @param array<int, string> $str
* @return array<int, string>
*/
function test2(array $str): array {
return mb_convert_encoding($str, "UTF-8", "UTF-8");
}'
],
'getDebugType' => [
'<?php
function foo(mixed $var) : void {
switch (get_debug_type($var)) {
case "string":
echo "a string";
break;
case Exception::class;
echo "an Exception with message " . $var->getMessage();
break;
}
}',
[],
[],
'8.0'
],
'getTypeDoubleThenInt' => [
'<?php
function safe_float(mixed $val): bool {
switch (gettype($val)) {
case "double":
case "integer":
return true;
// ... more cases omitted
default:
return false;
}
}',
[],
[],
'8.0'
],
'maxWithFloats' => [
'<?php
function foo(float $_float): void
{}
foo(max(1.1, 1.2));',
],
'maxWithObjects' => [
'<?php
function foo(DateTimeImmutable $fooDate): string
{
return $fooDate->format("Y");
}
foo(max(new DateTimeImmutable(), new DateTimeImmutable()));',
],
'maxWithMisc' => [
'<?php
$a = max(new DateTimeImmutable(), 1.2);',
[
'$a' => 'DateTimeImmutable|float',
],
],
'strtolowerEmptiness' => [
'<?php
/** @param non-empty-string $s */
function foo(string $s) : void {
$s = strtolower($s);
foo($s);
}',
],
'preventObjectLeakingFromCallmapReference' => [
'<?php
function one(): void
{
try {
exec("", $output);
} catch (Exception $e){
}
}
function two(): array
{
exec("", $lines);
return $lines;
}',
],
'array_is_list' => [
'<?php
function getArray() : array {
return [];
}
$s = getArray();
assert(array_is_list($s));
',
'assertions' => [
'$s' => 'list<mixed>',
],
[],
'8.1',
],
'array_is_list_on_empty_array' => [
'<?php
$a = [];
if(array_is_list($a)) {
//$a is still empty array
}
',
[],
[],
'8.1',
],
'possiblyUndefinedArrayDestructurationOnOptionalArg' => [
'<?php
class A
{
}
function foo(A $a1, A $a2 = null): void
{
}
$arguments = [new A()];
if (mt_rand(1, 10) > 5) {
// when this is done outside if - no errors
$arguments[] = new A();
}
foo(...$arguments);
',
],
'is_aWithStringableClass' => [
'<?php
/**
* @psalm-var class-string<Throwable> $exceptionType
*/
if (\is_a(new Exception(), $exceptionType)) {}
',
],
'strposFirstParamAllowClassString' => [
'<?php
function sayHello(string $needle): void {
if (strpos(DateTime::class, $needle)) {}
}',
],
'mb_strtolowerProducesStringWithSecondArgument' => [
'<?php
$r = mb_strtolower("École", "BASE64");
',
'assertions' => [
'$r===' => 'string',
],
],
'mb_strtolowerProducesLowercaseStringWithNullOrAbsentEncoding' => [
'<?php
$a = mb_strtolower("AAA");
$b = mb_strtolower("AAA", null);
',
'assertions' => [
'$a===' => 'lowercase-string',
'$b===' => 'lowercase-string',
],
[],
'8.1',
],
'count_charsProducesArrayOrString' => [
'<?php
$a = count_chars("foo");
$b = count_chars("foo", 1);
$c = count_chars("foo", 2);
$d = count_chars("foo", 3);
$e = count_chars("foo", 4);
',
'assertions' => [
'$a===' => 'array<int, int>',
'$b===' => 'array<int, int>',
'$c===' => 'array<int, int>',
'$d===' => 'string',
'$e===' => 'string',
],
[],
'8.1',
],
];
}
/**
* @return iterable<string,array{string,error_message:string,1?:string[],2?:bool,3?:string}>
*/
public function providerInvalidCodeParse(): iterable
{
return [
'invalidScalarArgument' => [
'<?php
function fooFoo(int $a): void {}
fooFoo("string");',
'error_message' => 'InvalidScalarArgument',
],
'invalidArgumentWithDeclareStrictTypes' => [
'<?php declare(strict_types=1);
function fooFoo(int $a): void {}
fooFoo("string");',
'error_message' => 'InvalidArgument',
],
'builtinFunctioninvalidArgumentWithWeakTypes' => [
'<?php
$s = substr(5, 4);',
'error_message' => 'InvalidScalarArgument',
],
'builtinFunctioninvalidArgumentWithDeclareStrictTypes' => [
'<?php declare(strict_types=1);
$s = substr(5, 4);',
'error_message' => 'InvalidArgument',
],
'builtinFunctioninvalidArgumentWithDeclareStrictTypesInClass' => [
'<?php declare(strict_types=1);
class A {
public function foo() : void {
$s = substr(5, 4);
}
}',
'error_message' => 'InvalidArgument',
],
'mixedArgument' => [
'<?php
function fooFoo(int $a): void {}
/** @var mixed */
$a = "hello";
fooFoo($a);',
'error_message' => 'MixedArgument',
'error_levels' => ['MixedAssignment'],
],
'nullArgument' => [
'<?php
function fooFoo(int $a): void {}
fooFoo(null);',
'error_message' => 'NullArgument',
],
'tooFewArguments' => [
'<?php
function fooFoo(int $a): void {}
fooFoo();',
'error_message' => 'TooFewArguments',
],
'tooManyArguments' => [
'<?php
function fooFoo(int $a): void {}
fooFoo(5, "dfd");',
'error_message' => 'TooManyArguments - src' . DIRECTORY_SEPARATOR . 'somefile.php:3:21 - Too many arguments for fooFoo '
. '- expecting 1 but saw 2',
],
'tooManyArgumentsForConstructor' => [
'<?php
class A { }
new A("hello");',
'error_message' => 'TooManyArguments',
],
'typeCoercion' => [
'<?php
class A {}
class B extends A{}
function fooFoo(B $b): void {}
fooFoo(new A());',
'error_message' => 'ArgumentTypeCoercion',
],
'arrayTypeCoercion' => [
'<?php
class A {}
class B extends A{}
/**
* @param B[] $b
* @return void
*/
function fooFoo(array $b) {}
fooFoo([new A()]);',
'error_message' => 'ArgumentTypeCoercion',
],
'duplicateParam' => [
'<?php
/**
* @return void
*/
function f($p, $p) {}',
'error_message' => 'DuplicateParam',
'error_levels' => ['MissingParamType'],
],
'invalidParamDefault' => [
'<?php
function f(int $p = false) {}',
'error_message' => 'InvalidParamDefault',
],
'invalidDocblockParamDefault' => [
'<?php
/**
* @param int $p
* @return void
*/
function f($p = false) {}',
'error_message' => 'InvalidParamDefault',
],
'badByRef' => [
'<?php
function fooFoo(string &$v): void {}
fooFoo("a");',
'error_message' => 'InvalidPassByReference',
],
'badArrayByRef' => [
'<?php
function fooFoo(array &$a): void {}
fooFoo([1, 2, 3]);',
'error_message' => 'InvalidPassByReference',
],
'invalidArgAfterCallable' => [
'<?php
/**
* @param callable $callback
* @return void
*/
function route($callback) {
if (!is_callable($callback)) { }
takes_int("string");
}
function takes_int(int $i) {}',
'error_message' => 'InvalidScalarArgument',
'error_levels' => [
'MixedAssignment',
'MixedArrayAccess',
'RedundantConditionGivenDocblockType',
],
],
'undefinedFunctionInArrayMap' => [
'<?php
array_map(
"undefined_function",
[1, 2, 3]
);',
'error_message' => 'UndefinedFunction',
],
'objectLikeKeyChecksAgainstDifferentGeneric' => [
'<?php
/**
* @param array<string, int> $b
*/
function a($b): int
{
return $b["a"];
}
a(["a" => "hello"]);',
'error_message' => 'InvalidScalarArgument',
],
'objectLikeKeyChecksAgainstDifferentTKeyedArray' => [
'<?php
/**
* @param array{a: int} $b
*/
function a($b): int
{
return $b["a"];
}
a(["a" => "hello"]);',
'error_message' => 'InvalidArgument',
],
'possiblyNullFunctionCall' => [
'<?php
$a = rand(0, 1) ? function(): void {} : null;
$a();',
'error_message' => 'PossiblyNullFunctionCall',
],
'possiblyInvalidFunctionCall' => [
'<?php
$a = rand(0, 1) ? function(): void {} : 23515;
$a();',
'error_message' => 'PossiblyInvalidFunctionCall',
],
'varExportAssignmentToVoid' => [
'<?php
$a = var_export(["a"]);',
'error_message' => 'AssignmentToVoid',
],
'explodeWithEmptyString' => [
'<?php
function exploder(string $s) : array {
return explode("", $s);
}',
'error_message' => 'FalsableReturnStatement',
],
'complainAboutArrayToIterable' => [
'<?php
class A {}
class B {}
/**
* @param iterable<mixed,A> $p
*/
function takesIterableOfA(iterable $p): void {}
takesIterableOfA([new B]); // should complain',
'error_message' => 'InvalidArgument',
],
'complainAboutArrayToIterableSingleParam' => [
'<?php
class A {}
class B {}
/**
* @param iterable<A> $p
*/
function takesIterableOfA(iterable $p): void {}
takesIterableOfA([new B]); // should complain',
'error_message' => 'InvalidArgument',
],
'putInvalidTypeMessagesFirst' => [
'<?php
$q = rand(0,1) ? new stdClass : false;
strlen($q);',
'error_message' => 'InvalidArgument',
],
'getTypeInvalidValue' => [
'<?php
/**
* @param mixed $maybe
*/
function matchesTypes($maybe) : void {
$t = gettype($maybe);
if ($t === "bool") {}
}',
'error_message' => 'TypeDoesNotContainType',
],
'rangeWithFloatStep' => [
'<?php
function foo(int $bar) : string {
return (string) $bar;
}
foreach (range(1, 10, .3) as $x) {
foo($x);
}',
'error_message' => 'InvalidScalarArgument',
],
'rangeWithFloatStart' => [
'<?php
function foo(int $bar) : string {
return (string) $bar;
}
foreach (range(1.4, 10) as $x) {
foo($x);
}',
'error_message' => 'InvalidScalarArgument',
],
'duplicateFunction' => [
'<?php
function f() : void {}
function f() : void {}',
'error_message' => 'DuplicateFunction',
],
'duplicateCoreFunction' => [
'<?php
function sort() : void {}',
'error_message' => 'DuplicateFunction',
],
'functionCallOnMixed' => [
'<?php
/**
* @var mixed $s
* @psalm-suppress MixedAssignment
*/
$s = 1;
$s();',
'error_message' => 'MixedFunctionCall',
],
'iterableOfObjectCannotAcceptIterableOfInt' => [
'<?php
/** @param iterable<string,object> $_p */
function accepts(iterable $_p): void {}
/** @return iterable<int,int> */
function iterable() { yield 1; }
accepts(iterable());',
'error_message' => 'InvalidArgument',
],
'iterableOfObjectCannotAcceptTraversableOfInt' => [
'<?php
/** @param iterable<string,object> $_p */
function accepts(iterable $_p): void {}
/** @return Traversable<int,int> */
function traversable() { yield 1; }
accepts(traversable());',
'error_message' => 'InvalidArgument',
],
'iterableOfObjectCannotAcceptGeneratorOfInt' => [
'<?php
/** @param iterable<string,object> $_p */
function accepts(iterable $_p): void {}
/** @return Generator<int,int,mixed,void> */
function generator() { yield 1; }
accepts(generator());',
'error_message' => 'InvalidArgument',
],
'iterableOfObjectCannotAcceptArrayOfInt' => [
'<?php
/** @param iterable<string,object> $_p */
function accepts(iterable $_p): void {}
/** @return array<int,int> */
function arr() { return [1]; }
accepts(arr());',
'error_message' => 'InvalidArgument',
],
'nonNullableByRef' => [
'<?php
function foo(string &$s) : void {}
function bar() : void {
foo($bar);
}',
'error_message' => 'NullReference',
],
'intCastByRef' => [
'<?php
function foo(int &$i) : void {}
$a = rand(0, 1) ? null : 5;
/** @psalm-suppress MixedArgument */
foo((int) $a);',
'error_message' => 'InvalidPassByReference',
],
'implicitAssignmentToStringFromMixed' => [
'<?php
/** @param "a"|"b" $s */
function takesString(string $s) : void {}
function takesInt(int $i) : void {}
/**
* @param mixed $s
* @psalm-suppress MixedArgument
*/
function bar($s) : void {
takesString($s);
takesInt($s);
}',
'error_message' => 'InvalidScalarArgument',
],
'tooFewArgsAccurateCount' => [
'<?php
preg_match(\'/adsf/\');',
'error_message' => 'TooFewArguments - src' . DIRECTORY_SEPARATOR . 'somefile.php:2:21 - Too few arguments for preg_match - expecting 2 but saw 1',
],
'compactUndefinedVariable' => [
'<?php
/**
* @return array<string, mixed>
*/
function foo() : array {
return compact("a", "b", "c");
}',
'error_message' => 'UndefinedVariable',
],
'countCallableArrayShouldBeTwo' => [
'<?php
/** @param callable|false $x */
function example($x) : void {
if (is_array($x)) {
$c = count($x);
if ($c !== 2) {}
}
}',
'error_message' => 'TypeDoesNotContainType',
],
'countOnObjectCannotBePositive' => [
'<?php
/** @return positive-int|0 */
function example(\Countable $x) : int {
return count($x);
}',
'error_message' => 'LessSpecificReturnStatement',
],
'countOnUnknownObjectCannotBePure' => [
'<?php
/** @psalm-pure */
function example(\Countable $x) : int {
return count($x);
}',
'error_message' => 'ImpureFunctionCall',
],
'coerceCallMapArgsInStrictMode' => [
'<?php
declare(strict_types=1);
function getStr() : ?string {
return rand(0,1) ? "test" : null;
}
function test() : void {
$g = getStr();
/** @psalm-suppress PossiblyNullArgument */
$x = strtoupper($g);
$c = "prefix " . (strtoupper($g ?? "") === "x" ? "xa" : "ya");
echo "$x, $c\n";
}',
'error_message' => 'RedundantCondition',
],
'noCrashOnEmptyArrayPush' => [
'<?php
array_push();',
'error_message' => 'TooFewArguments',
],
'printOnlyString' => [
'<?php
print [];',
'error_message' => 'InvalidArgument',
],
'printReturns1' => [
'<?php
(print "test") === 2;',
'error_message' => 'TypeDoesNotContainType',
],
'sodiumMemzeroNullifyString' => [
'<?php
function returnsStr(): string {
$str = "x";
sodium_memzero($str);
return $str;
}',
'error_message' => 'NullableReturnStatement'
],
'noCrashWithPattern' => [
'<?php
echo !\is_callable($loop_callback)
|| (\is_array($loop_callback)
&& !\method_exists(...$loop_callback));',
'error_message' => 'UndefinedGlobalVariable'
],
'parseUrlPossiblyUndefined' => [
'<?php
function bar(string $s) : string {
$parsed = parse_url($s);
return $parsed["host"];
}',
'error_message' => 'PossiblyUndefinedArrayOffset',
],
'parseUrlPossiblyUndefined2' => [
'<?php
function bag(string $s) : string {
$parsed = parse_url($s);
if (is_string($parsed["host"] ?? false)) {
return $parsed["host"];
}
return "";
}',
'error_message' => 'PossiblyUndefinedArrayOffset',
],
'strposNoSetFirstParam' => [
'<?php
function sayHello(string $format): void {
if (strpos("u", $format)) {}
}',
'error_message' => 'InvalidLiteralArgument',
],
'curlInitIsResourceFailsIn8x' => [
'<?php
$ch = curl_init();
if (!is_resource($ch)) {}',
'error_message' => 'RedundantCondition',
[],
false,
'8.0'
],
'maxCallWithArray' => [
'<?php
function foo(array $a) {
max($a);
}',
'error_message' => 'ArgumentTypeCoercion',
],
'pregSplitNoEmpty' => [
'<?php
/** @return non-empty-list */
function foo(string $s) {
return preg_split("/ /", $s, -1, PREG_SPLIT_NO_EMPTY);
}',
'error_message' => 'InvalidReturnStatement'
],
'maxWithMixed' => [
'<?php
/** @var mixed $b */;
/** @var mixed $c */;
$a = max($b, $c);',
'error_message' => 'MixedAssignment'
],
'literalFalseArgument' => [
'<?php
function takesAString(string $s): void{
echo $s;
}
takesAString(false);',
'error_message' => 'InvalidArgument'
],
'getClassWithoutArgsOutsideClass' => [
'<?php
echo get_class();',
'error_message' => 'TooFewArguments',
],
'count_charsWithInvalidMode' => [
'<?php
function scope(int $mode){
$a = count_chars("foo", $mode);
}',
'error_message' => 'ArgumentTypeCoercion',
],
];
}
public function testTriggerErrorDefault(): void
{
$config = Config::getInstance();
$config->trigger_error_exits = 'default';
$this->addFile(
'somefile.php',
'<?php
/** @return true */
function returnsTrue(): bool {
return trigger_error("", E_USER_NOTICE);
}
/** @return never */
function returnsNever(): void {
trigger_error("", E_USER_ERROR);
}
/**
* @psalm-suppress ArgumentTypeCoercion
* @return mixed
*/
function returnsNeverOrBool(int $i) {
return trigger_error("", $i);
}'
);
//will only pass if no exception is thrown
$this->assertTrue(true);
$this->analyzeFile('somefile.php', new Context());
}
public function testTriggerErrorAlways(): void
{
$config = Config::getInstance();
$config->trigger_error_exits = 'always';
$this->addFile(
'somefile.php',
'<?php
/** @return never */
function returnsNever1(): void {
trigger_error("", E_USER_NOTICE);
}
/** @return never */
function returnsNever2(): void {
trigger_error("", E_USER_ERROR);
}'
);
//will only pass if no exception is thrown
$this->assertTrue(true);
$this->analyzeFile('somefile.php', new Context());
}
public function testTriggerErrorNever(): void
{
$config = Config::getInstance();
$config->trigger_error_exits = 'never';
$this->addFile(
'somefile.php',
'<?php
/** @return true */
function returnsTrue1(): bool {
return trigger_error("", E_USER_NOTICE);
}
/** @return true */
function returnsTrue2(): bool {
return trigger_error("", E_USER_ERROR);
}'
);
//will only pass if no exception is thrown
$this->assertTrue(true);
$this->analyzeFile('somefile.php', new Context());
}
}
| 1 | 12,277 | Non-int literal strings are no longer coercible to int, I think this is an improvement. Without this change it now reports `InvalidArgument`. | vimeo-psalm | php |
@@ -27,6 +27,8 @@
#include "cast_utils.h"
#include "layer_validation_tests.h"
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+
class MessageIdFilter {
public:
MessageIdFilter(const char *filter_string) { | 1 | /*
* Copyright (c) 2015-2020 The Khronos Group Inc.
* Copyright (c) 2015-2020 Valve Corporation
* Copyright (c) 2015-2020 LunarG, Inc.
* Copyright (c) 2015-2020 Google, 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
*
* Author: Chia-I Wu <[email protected]>
* Author: Chris Forbes <[email protected]>
* Author: Courtney Goeltzenleuchter <[email protected]>
* Author: Mark Lobodzinski <[email protected]>
* Author: Mike Stroyan <[email protected]>
* Author: Tobin Ehlis <[email protected]>
* Author: Tony Barbour <[email protected]>
* Author: Cody Northrop <[email protected]>
* Author: Dave Houlton <[email protected]>
* Author: Jeremy Kniager <[email protected]>
* Author: Shannon McPherson <[email protected]>
* Author: John Zulauf <[email protected]>
*/
#include "cast_utils.h"
#include "layer_validation_tests.h"
class MessageIdFilter {
public:
MessageIdFilter(const char *filter_string) {
local_string = filter_string;
filter_string_value.arrayString.pCharArray = local_string.data();
filter_string_value.arrayString.count = local_string.size();
strncpy(filter_setting_val.name, "message_id_filter", sizeof(filter_setting_val.name));
filter_setting_val.type = VK_LAYER_SETTING_VALUE_TYPE_STRING_ARRAY_EXT;
filter_setting_val.data = filter_string_value;
filter_setting = {static_cast<VkStructureType>(VK_STRUCTURE_TYPE_INSTANCE_LAYER_SETTINGS_EXT), nullptr, 1,
&filter_setting_val};
}
VkLayerSettingsEXT *pnext{&filter_setting};
private:
VkLayerSettingValueDataEXT filter_string_value{};
VkLayerSettingValueEXT filter_setting_val;
VkLayerSettingsEXT filter_setting;
std::string local_string;
};
class CustomStypeList {
public:
CustomStypeList(const char *stype_id_string) {
local_string = stype_id_string;
custom_stype_value.arrayString.pCharArray = local_string.data();
custom_stype_value.arrayString.count = local_string.size();
strncpy(custom_stype_setting_val.name, "custom_stype_list", sizeof(custom_stype_setting_val.name));
custom_stype_setting_val.type = VK_LAYER_SETTING_VALUE_TYPE_STRING_ARRAY_EXT;
custom_stype_setting_val.data = custom_stype_value;
custom_stype_setting = {static_cast<VkStructureType>(VK_STRUCTURE_TYPE_INSTANCE_LAYER_SETTINGS_EXT), nullptr, 1,
&custom_stype_setting_val};
}
CustomStypeList(const std::vector<uint32_t> &stype_id_array) {
local_vector = stype_id_array;
custom_stype_value.arrayInt32.pInt32Array = local_vector.data();
custom_stype_value.arrayInt32.count = local_vector.size();
strncpy(custom_stype_setting_val.name, "custom_stype_list", sizeof(custom_stype_setting_val.name));
custom_stype_setting_val.type = VK_LAYER_SETTING_VALUE_TYPE_UINT32_ARRAY_EXT;
custom_stype_setting_val.data = custom_stype_value;
custom_stype_setting = {static_cast<VkStructureType>(VK_STRUCTURE_TYPE_INSTANCE_LAYER_SETTINGS_EXT), nullptr, 1,
&custom_stype_setting_val};
}
VkLayerSettingsEXT *pnext{&custom_stype_setting};
private:
VkLayerSettingValueDataEXT custom_stype_value{};
VkLayerSettingValueEXT custom_stype_setting_val;
VkLayerSettingsEXT custom_stype_setting;
std::string local_string;
std::vector<uint32_t> local_vector;
};
class DuplicateMsgLimit {
public:
DuplicateMsgLimit(const uint32_t limit) {
limit_value.value32 = limit;
strncpy(limit_setting_val.name, "duplicate_message_limit", sizeof(limit_setting_val.name));
limit_setting_val.type = VK_LAYER_SETTING_VALUE_TYPE_UINT32_EXT;
limit_setting_val.data = limit_value;
limit_setting = {static_cast<VkStructureType>(VK_STRUCTURE_TYPE_INSTANCE_LAYER_SETTINGS_EXT), nullptr, 1,
&limit_setting_val};
}
VkLayerSettingsEXT *pnext{&limit_setting};
private:
VkLayerSettingValueDataEXT limit_value{};
VkLayerSettingValueEXT limit_setting_val;
VkLayerSettingsEXT limit_setting;
};
TEST_F(VkLayerTest, CustomStypeStructString) {
TEST_DESCRIPTION("Positive Test for ability to specify custom pNext structs using a list (string)");
// Create a custom structure
typedef struct CustomStruct {
VkStructureType sType;
const void *pNext;
uint32_t custom_data;
} CustomStruct;
uint32_t custom_stype = 3000300000;
CustomStruct custom_struct;
custom_struct.pNext = nullptr;
custom_struct.sType = static_cast<VkStructureType>(custom_stype);
custom_struct.custom_data = 44;
// Communicate list of structinfo pairs to layers
auto stype_list = CustomStypeList("3000300000,24");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor, stype_list.pnext));
ASSERT_NO_FATAL_FAILURE(InitState());
uint32_t queue_family_index = 0;
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.size = 1024;
buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
buffer_create_info.queueFamilyIndexCount = 1;
buffer_create_info.pQueueFamilyIndices = &queue_family_index;
VkBufferObj buffer;
buffer.init(*m_device, buffer_create_info);
VkBufferView buffer_view;
VkBufferViewCreateInfo bvci = {};
bvci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
bvci.pNext = &custom_struct; // Add custom struct through pNext
bvci.buffer = buffer.handle();
bvci.format = VK_FORMAT_R32_SFLOAT;
bvci.range = VK_WHOLE_SIZE;
m_errorMonitor->ExpectSuccess(kErrorBit);
vk::CreateBufferView(m_device->device(), &bvci, NULL, &buffer_view);
m_errorMonitor->VerifyNotFound();
vk::DestroyBufferView(m_device->device(), buffer_view, nullptr);
}
TEST_F(VkLayerTest, CustomStypeStructArray) {
TEST_DESCRIPTION("Positive Test for ability to specify custom pNext structs using a vector of integers");
// Create a custom structure
typedef struct CustomStruct {
VkStructureType sType;
const void *pNext;
uint32_t custom_data;
} CustomStruct;
const uint32_t custom_stype_a = 3000300000;
CustomStruct custom_struct_a;
custom_struct_a.pNext = nullptr;
custom_struct_a.sType = static_cast<VkStructureType>(custom_stype_a);
custom_struct_a.custom_data = 44;
const uint32_t custom_stype_b = 3000300001;
CustomStruct custom_struct_b;
custom_struct_b.pNext = &custom_struct_a;
custom_struct_b.sType = static_cast<VkStructureType>(custom_stype_b);
custom_struct_b.custom_data = 88;
// Communicate list of structinfo pairs to layers, including a duplicate which should get filtered out
std::vector<uint32_t> custom_struct_info = {custom_stype_a, sizeof(CustomStruct), custom_stype_b,
sizeof(CustomStruct), custom_stype_a, sizeof(CustomStruct)};
auto stype_list = CustomStypeList(custom_struct_info);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor, stype_list.pnext));
ASSERT_NO_FATAL_FAILURE(InitState());
uint32_t queue_family_index = 0;
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.size = 1024;
buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
buffer_create_info.queueFamilyIndexCount = 1;
buffer_create_info.pQueueFamilyIndices = &queue_family_index;
VkBufferObj buffer;
buffer.init(*m_device, buffer_create_info);
VkBufferView buffer_view;
VkBufferViewCreateInfo bvci = {};
bvci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
bvci.pNext = &custom_struct_b; // Add custom struct through pNext
bvci.buffer = buffer.handle();
bvci.format = VK_FORMAT_R32_SFLOAT;
bvci.range = VK_WHOLE_SIZE;
m_errorMonitor->ExpectSuccess(kErrorBit);
vk::CreateBufferView(m_device->device(), &bvci, NULL, &buffer_view);
m_errorMonitor->VerifyNotFound();
vk::DestroyBufferView(m_device->device(), buffer_view, nullptr);
}
TEST_F(VkLayerTest, DuplicateMessageLimit) {
TEST_DESCRIPTION("Use the duplicate_message_id setting and verify correct operation");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
auto msg_limit = DuplicateMsgLimit(3);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor, msg_limit.pnext));
ASSERT_NO_FATAL_FAILURE(InitState());
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
// Create an invalid pNext structure to trigger the stateless validation warning
VkBaseOutStructure bogus_struct{};
bogus_struct.sType = static_cast<VkStructureType>(0x33333333);
auto properties2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&bogus_struct);
// Should get the first three errors just fine
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "VUID-VkPhysicalDeviceProperties2-pNext-pNext");
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "VUID-VkPhysicalDeviceProperties2-pNext-pNext");
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "VUID-VkPhysicalDeviceProperties2-pNext-pNext");
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
m_errorMonitor->VerifyFound();
// Limit should prevent the message from coming through a fourth time
m_errorMonitor->ExpectSuccess(kWarningBit);
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
m_errorMonitor->VerifyNotFound();
}
TEST_F(VkLayerTest, MessageIdFilterString) {
TEST_DESCRIPTION("Validate that message id string filtering is working");
// This test would normally produce an unexpected error or two. Use the message filter instead of
// the error_monitor's SetUnexpectedError to test the filtering.
auto filter_setting = MessageIdFilter("VUID-VkRenderPassCreateInfo-pNext-01963");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor, filter_setting.pnext));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE2_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_MAINTENANCE2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkAttachmentDescription attach = {0,
VK_FORMAT_R8G8B8A8_UNORM,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkSubpassDescription subpass = {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 1, &ref, 0, nullptr, nullptr, nullptr, 0, nullptr};
VkInputAttachmentAspectReference iaar = {0, 0, VK_IMAGE_ASPECT_METADATA_BIT};
VkRenderPassInputAttachmentAspectCreateInfo rpiaaci = {VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO,
nullptr, 1, &iaar};
VkRenderPassCreateInfo rpci = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, &rpiaaci, 0, 1, &attach, 1, &subpass, 0, nullptr};
m_errorMonitor->SetUnexpectedError("VUID-VkRenderPassCreateInfo2-attachment-02525");
TestRenderPassCreate(m_errorMonitor, m_device->device(), &rpci, false, "VUID-VkInputAttachmentAspectReference-aspectMask-01964",
nullptr);
}
TEST_F(VkLayerTest, MessageIdFilterHexInt) {
TEST_DESCRIPTION("Validate that message id hex int filtering is working");
// This test would normally produce an unexpected error or two. Use the message filter instead of
// the error_monitor's SetUnexpectedError to test the filtering.
auto filter_setting = MessageIdFilter("0xa19880e3");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor, filter_setting.pnext));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE2_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_MAINTENANCE2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkAttachmentDescription attach = {0,
VK_FORMAT_R8G8B8A8_UNORM,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkSubpassDescription subpass = {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 1, &ref, 0, nullptr, nullptr, nullptr, 0, nullptr};
VkInputAttachmentAspectReference iaar = {0, 0, VK_IMAGE_ASPECT_METADATA_BIT};
VkRenderPassInputAttachmentAspectCreateInfo rpiaaci = {VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO,
nullptr, 1, &iaar};
VkRenderPassCreateInfo rpci = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, &rpiaaci, 0, 1, &attach, 1, &subpass, 0, nullptr};
m_errorMonitor->SetUnexpectedError("VUID-VkRenderPassCreateInfo2-attachment-02525");
TestRenderPassCreate(m_errorMonitor, m_device->device(), &rpci, false, "VUID-VkInputAttachmentAspectReference-aspectMask-01964",
nullptr);
}
TEST_F(VkLayerTest, MessageIdFilterInt) {
TEST_DESCRIPTION("Validate that message id decimal int filtering is working");
// This test would normally produce an unexpected error or two. Use the message filter instead of
// the error_monitor's SetUnexpectedError to test the filtering.
auto filter_setting = MessageIdFilter("2711126243");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor, filter_setting.pnext));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE2_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_MAINTENANCE2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkAttachmentDescription attach = {0,
VK_FORMAT_R8G8B8A8_UNORM,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkSubpassDescription subpass = {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 1, &ref, 0, nullptr, nullptr, nullptr, 0, nullptr};
VkInputAttachmentAspectReference iaar = {0, 0, VK_IMAGE_ASPECT_METADATA_BIT};
VkRenderPassInputAttachmentAspectCreateInfo rpiaaci = {VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO,
nullptr, 1, &iaar};
VkRenderPassCreateInfo rpci = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, &rpiaaci, 0, 1, &attach, 1, &subpass, 0, nullptr};
m_errorMonitor->SetUnexpectedError("VUID-VkRenderPassCreateInfo2-attachment-02525");
TestRenderPassCreate(m_errorMonitor, m_device->device(), &rpci, false, "VUID-VkInputAttachmentAspectReference-aspectMask-01964",
nullptr);
}
struct LayerStatusCheckData {
std::function<void(const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, LayerStatusCheckData *)> callback;
ErrorMonitor *error_monitor;
};
TEST_F(VkLayerTest, LayerInfoMessages) {
TEST_DESCRIPTION("Ensure layer prints startup status messages.");
auto ici = GetInstanceCreateInfo();
LayerStatusCheckData callback_data;
auto local_callback = [](const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, LayerStatusCheckData *data) {
std::string message(pCallbackData->pMessage);
if ((data->error_monitor->GetMessageFlags() & kInformationBit) &&
(message.find("UNASSIGNED-khronos-validation-createinstance-status-message") == std::string::npos)) {
data->error_monitor->SetError("UNASSIGNED-Khronos-validation-createinstance-status-message-not-found");
} else if ((data->error_monitor->GetMessageFlags() & kPerformanceWarningBit) &&
(message.find("UNASSIGNED-khronos-Validation-debug-build-warning-message") == std::string::npos)) {
data->error_monitor->SetError("UNASSIGNED-khronos-validation-createinstance-debug-warning-message-not-found");
}
};
callback_data.error_monitor = m_errorMonitor;
callback_data.callback = local_callback;
VkInstance local_instance;
auto callback_create_info = lvl_init_struct<VkDebugUtilsMessengerCreateInfoEXT>();
callback_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT;
callback_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT;
callback_create_info.pfnUserCallback = DebugUtilsCallback;
callback_create_info.pUserData = &callback_data;
ici.pNext = &callback_create_info;
// Create an instance, error if layer status INFO message not found
m_errorMonitor->ExpectSuccess();
ASSERT_VK_SUCCESS(vk::CreateInstance(&ici, nullptr, &local_instance));
m_errorMonitor->VerifyNotFound();
vk::DestroyInstance(local_instance, nullptr);
#ifndef NDEBUG
// Create an instance, error if layer DEBUG_BUILD warning message not found
callback_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
callback_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
m_errorMonitor->ExpectSuccess();
ASSERT_VK_SUCCESS(vk::CreateInstance(&ici, nullptr, &local_instance));
m_errorMonitor->VerifyNotFound();
vk::DestroyInstance(local_instance, nullptr);
#endif
}
TEST_F(VkLayerTest, RequiredParameter) {
TEST_DESCRIPTION("Specify VK_NULL_HANDLE, NULL, and 0 for required handle, pointer, array, and array count parameters");
ASSERT_NO_FATAL_FAILURE(Init());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "required parameter pFeatures specified as NULL");
// Specify NULL for a pointer to a handle
// Expected to trigger an error with
// parameter_validation::validate_required_pointer
vk::GetPhysicalDeviceFeatures(gpu(), NULL);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "required parameter pQueueFamilyPropertyCount specified as NULL");
// Specify NULL for pointer to array count
// Expected to trigger an error with parameter_validation::validate_array
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), NULL, NULL);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetViewport-viewportCount-arraylength");
// Specify 0 for a required array count
// Expected to trigger an error with parameter_validation::validate_array
VkViewport viewport = {0.0f, 0.0f, 64.0f, 64.0f, 0.0f, 1.0f};
m_commandBuffer->SetViewport(0, 0, &viewport);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCreateImage-pCreateInfo-parameter");
// Specify a null pImageCreateInfo struct pointer
VkImage test_image;
vk::CreateImage(device(), NULL, NULL, &test_image);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetViewport-pViewports-parameter");
// Specify NULL for a required array
// Expected to trigger an error with parameter_validation::validate_array
m_commandBuffer->SetViewport(0, 1, NULL);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "required parameter memory specified as VK_NULL_HANDLE");
// Specify VK_NULL_HANDLE for a required handle
// Expected to trigger an error with
// parameter_validation::validate_required_handle
vk::UnmapMemory(device(), VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "required parameter pFences[0] specified as VK_NULL_HANDLE");
// Specify VK_NULL_HANDLE for a required handle array entry
// Expected to trigger an error with
// parameter_validation::validate_required_handle_array
VkFence fence = VK_NULL_HANDLE;
vk::ResetFences(device(), 1, &fence);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "required parameter pAllocateInfo specified as NULL");
// Specify NULL for a required struct pointer
// Expected to trigger an error with
// parameter_validation::validate_struct_type
VkDeviceMemory memory = VK_NULL_HANDLE;
vk::AllocateMemory(device(), NULL, NULL, &memory);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "value of faceMask must not be 0");
// Specify 0 for a required VkFlags parameter
// Expected to trigger an error with parameter_validation::validate_flags
m_commandBuffer->SetStencilReference(0, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "value of pSubmits[0].pWaitDstStageMask[0] must not be 0");
// Specify 0 for a required VkFlags array entry
// Expected to trigger an error with
// parameter_validation::validate_flags_array
VkSemaphore semaphore = VK_NULL_HANDLE;
VkPipelineStageFlags stageFlags = 0;
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &semaphore;
submitInfo.pWaitDstStageMask = &stageFlags;
vk::QueueSubmit(m_device->m_queue, 1, &submitInfo, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-sType-sType");
stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
// Set a bogus sType and see what happens
submitInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &semaphore;
submitInfo.pWaitDstStageMask = &stageFlags;
vk::QueueSubmit(m_device->m_queue, 1, &submitInfo, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pWaitSemaphores-parameter");
stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = 1;
// Set a null pointer for pWaitSemaphores
submitInfo.pWaitSemaphores = NULL;
submitInfo.pWaitDstStageMask = &stageFlags;
vk::QueueSubmit(m_device->m_queue, 1, &submitInfo, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCreateRenderPass-pCreateInfo-parameter");
VkRenderPass render_pass;
vk::CreateRenderPass(device(), nullptr, nullptr, &render_pass);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, SpecLinks) {
TEST_DESCRIPTION("Test that spec links in a typical error message are well-formed");
ASSERT_NO_FATAL_FAILURE(InitFramework());
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE2_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME);
}
ASSERT_NO_FATAL_FAILURE(InitState());
#ifdef ANNOTATED_SPEC_LINK
bool test_annotated_spec_link = true;
#else // ANNOTATED_SPEC_LINK
bool test_annotated_spec_link = false;
#endif // ANNOTATED_SPEC_LINK
std::string spec_version;
if (test_annotated_spec_link) {
std::string major_version = std::to_string(VK_VERSION_MAJOR(VK_HEADER_VERSION_COMPLETE));
std::string minor_version = std::to_string(VK_VERSION_MINOR(VK_HEADER_VERSION_COMPLETE));
std::string patch_version = std::to_string(VK_VERSION_PATCH(VK_HEADER_VERSION_COMPLETE));
spec_version = "doc/view/" + major_version + "." + minor_version + "." + patch_version + ".0/windows";
} else {
spec_version = "registry/vulkan/specs";
}
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, spec_version);
vk::GetPhysicalDeviceFeatures(gpu(), NULL);
m_errorMonitor->VerifyFound();
// Now generate a 'default' message and check the link
bool ycbcr_support = (DeviceExtensionEnabled(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME) ||
(DeviceValidationVersion() >= VK_API_VERSION_1_1));
bool maintenance2_support =
(DeviceExtensionEnabled(VK_KHR_MAINTENANCE2_EXTENSION_NAME) || (DeviceValidationVersion() >= VK_API_VERSION_1_1));
if (!((m_device->format_properties(VK_FORMAT_R8_UINT).optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) &&
(ycbcr_support ^ maintenance2_support))) {
printf("%s Device does not support format and extensions required, skipping test case", kSkipPrefix);
return;
}
VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
nullptr,
0,
VK_IMAGE_TYPE_2D,
VK_FORMAT_R8_UINT,
{128, 128, 1},
1,
1,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
VK_SHARING_MODE_EXCLUSIVE,
0,
nullptr,
VK_IMAGE_LAYOUT_UNDEFINED};
imageInfo.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
VkImageObj mutImage(m_device);
mutImage.init(&imageInfo);
ASSERT_TRUE(mutImage.initialized());
VkImageViewCreateInfo imgViewInfo = {};
imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imgViewInfo.format = VK_FORMAT_B8G8R8A8_UNORM; // different than createImage
imgViewInfo.subresourceRange.layerCount = 1;
imgViewInfo.subresourceRange.baseMipLevel = 0;
imgViewInfo.subresourceRange.levelCount = 1;
imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imgViewInfo.image = mutImage.handle();
// VUIDs 01759 and 01760 should generate 'default' spec URLs, to search the registry
CreateImageViewTest(*this, &imgViewInfo, "Vulkan-Docs/search");
}
TEST_F(VkLayerTest, PnextOnlyStructValidation) {
TEST_DESCRIPTION("See if checks occur on structs ONLY used in pnext chains.");
if (!(CheckDescriptorIndexingSupportAndInitFramework(this, m_instance_extension_names, m_device_extension_names, NULL,
m_errorMonitor))) {
printf("Descriptor indexing or one of its dependencies not supported, skipping tests\n");
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
// Create a device passing in a bad PdevFeatures2 value
auto indexing_features = lvl_init_struct<VkPhysicalDeviceDescriptorIndexingFeaturesEXT>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&indexing_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
// Set one of the features values to an invalid boolean value
indexing_features.descriptorBindingUniformBufferUpdateAfterBind = 800;
uint32_t queue_node_count;
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_node_count, NULL);
VkQueueFamilyProperties *queue_props = new VkQueueFamilyProperties[queue_node_count];
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_node_count, queue_props);
float priorities[] = {1.0f};
VkDeviceQueueCreateInfo queue_info{};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = NULL;
queue_info.flags = 0;
queue_info.queueFamilyIndex = 0;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = &priorities[0];
VkDeviceCreateInfo dev_info = {};
dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dev_info.pNext = NULL;
dev_info.queueCreateInfoCount = 1;
dev_info.pQueueCreateInfos = &queue_info;
dev_info.enabledLayerCount = 0;
dev_info.ppEnabledLayerNames = NULL;
dev_info.enabledExtensionCount = m_device_extension_names.size();
dev_info.ppEnabledExtensionNames = m_device_extension_names.data();
dev_info.pNext = &features2;
VkDevice dev;
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "is neither VK_TRUE nor VK_FALSE");
m_errorMonitor->SetUnexpectedError("Failed to create");
vk::CreateDevice(gpu(), &dev_info, NULL, &dev);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, ReservedParameter) {
TEST_DESCRIPTION("Specify a non-zero value for a reserved parameter");
ASSERT_NO_FATAL_FAILURE(Init());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, " must be 0");
// Specify 0 for a reserved VkFlags parameter
// Expected to trigger an error with
// parameter_validation::validate_reserved_flags
VkEvent event_handle = VK_NULL_HANDLE;
VkEventCreateInfo event_info = {};
event_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
event_info.flags = 1;
vk::CreateEvent(device(), &event_info, NULL, &event_handle);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, DebugMarkerNameTest) {
TEST_DESCRIPTION("Ensure debug marker object names are printed in debug report output");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), kValidationLayerName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME);
} else {
printf("%s Debug Marker Extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
PFN_vkDebugMarkerSetObjectNameEXT fpvkDebugMarkerSetObjectNameEXT =
(PFN_vkDebugMarkerSetObjectNameEXT)vk::GetInstanceProcAddr(instance(), "vkDebugMarkerSetObjectNameEXT");
if (!(fpvkDebugMarkerSetObjectNameEXT)) {
printf("%s Can't find fpvkDebugMarkerSetObjectNameEXT; skipped.\n", kSkipPrefix);
return;
}
if (DeviceSimulation()) {
printf("%sSkipping object naming test.\n", kSkipPrefix);
return;
}
VkBuffer buffer;
VkDeviceMemory memory_1, memory_2;
std::string memory_name = "memory_name";
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
buffer_create_info.size = 1;
vk::CreateBuffer(device(), &buffer_create_info, nullptr, &buffer);
VkMemoryRequirements memRequirements;
vk::GetBufferMemoryRequirements(device(), buffer, &memRequirements);
VkMemoryAllocateInfo memory_allocate_info = {};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.allocationSize = memRequirements.size;
memory_allocate_info.memoryTypeIndex = 0;
vk::AllocateMemory(device(), &memory_allocate_info, nullptr, &memory_1);
vk::AllocateMemory(device(), &memory_allocate_info, nullptr, &memory_2);
VkDebugMarkerObjectNameInfoEXT name_info = {};
name_info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT;
name_info.pNext = nullptr;
name_info.object = (uint64_t)memory_2;
name_info.objectType = VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT;
name_info.pObjectName = memory_name.c_str();
fpvkDebugMarkerSetObjectNameEXT(device(), &name_info);
vk::BindBufferMemory(device(), buffer, memory_1, 0);
// Test core_validation layer
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, memory_name);
vk::BindBufferMemory(device(), buffer, memory_2, 0);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), memory_1, nullptr);
memory_1 = VK_NULL_HANDLE;
vk::FreeMemory(device(), memory_2, nullptr);
memory_2 = VK_NULL_HANDLE;
vk::DestroyBuffer(device(), buffer, nullptr);
buffer = VK_NULL_HANDLE;
VkCommandBuffer commandBuffer;
std::string commandBuffer_name = "command_buffer_name";
VkCommandPool commandpool_1;
VkCommandPool commandpool_2;
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = m_device->graphics_queue_node_index_;
pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vk::CreateCommandPool(device(), &pool_create_info, nullptr, &commandpool_1);
vk::CreateCommandPool(device(), &pool_create_info, nullptr, &commandpool_2);
VkCommandBufferAllocateInfo command_buffer_allocate_info{};
command_buffer_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_allocate_info.commandPool = commandpool_1;
command_buffer_allocate_info.commandBufferCount = 1;
command_buffer_allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
vk::AllocateCommandBuffers(device(), &command_buffer_allocate_info, &commandBuffer);
name_info.object = (uint64_t)commandBuffer;
name_info.objectType = VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT;
name_info.pObjectName = commandBuffer_name.c_str();
fpvkDebugMarkerSetObjectNameEXT(device(), &name_info);
VkCommandBufferBeginInfo cb_begin_Info = {};
cb_begin_Info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cb_begin_Info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vk::BeginCommandBuffer(commandBuffer, &cb_begin_Info);
const VkRect2D scissor = {{-1, 0}, {16, 16}};
const VkRect2D scissors[] = {scissor, scissor};
// Test parameter_validation layer
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, commandBuffer_name);
vk::CmdSetScissor(commandBuffer, 0, 1, scissors);
m_errorMonitor->VerifyFound();
// Test object_tracker layer
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, commandBuffer_name);
vk::FreeCommandBuffers(device(), commandpool_2, 1, &commandBuffer);
m_errorMonitor->VerifyFound();
vk::DestroyCommandPool(device(), commandpool_1, NULL);
vk::DestroyCommandPool(device(), commandpool_2, NULL);
}
TEST_F(VkLayerTest, DebugUtilsNameTest) {
TEST_DESCRIPTION("Ensure debug utils object names are printed in debug messenger output");
// Skip test if extension not supported
if (InstanceExtensionSupported(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
} else {
printf("%s Debug Utils Extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
ASSERT_NO_FATAL_FAILURE(InitState());
PFN_vkSetDebugUtilsObjectNameEXT fpvkSetDebugUtilsObjectNameEXT =
(PFN_vkSetDebugUtilsObjectNameEXT)vk::GetInstanceProcAddr(instance(), "vkSetDebugUtilsObjectNameEXT");
ASSERT_TRUE(fpvkSetDebugUtilsObjectNameEXT); // Must be extant if extension is enabled
PFN_vkCreateDebugUtilsMessengerEXT fpvkCreateDebugUtilsMessengerEXT =
(PFN_vkCreateDebugUtilsMessengerEXT)vk::GetInstanceProcAddr(instance(), "vkCreateDebugUtilsMessengerEXT");
ASSERT_TRUE(fpvkCreateDebugUtilsMessengerEXT); // Must be extant if extension is enabled
PFN_vkDestroyDebugUtilsMessengerEXT fpvkDestroyDebugUtilsMessengerEXT =
(PFN_vkDestroyDebugUtilsMessengerEXT)vk::GetInstanceProcAddr(instance(), "vkDestroyDebugUtilsMessengerEXT");
ASSERT_TRUE(fpvkDestroyDebugUtilsMessengerEXT); // Must be extant if extension is enabled
PFN_vkCmdInsertDebugUtilsLabelEXT fpvkCmdInsertDebugUtilsLabelEXT =
(PFN_vkCmdInsertDebugUtilsLabelEXT)vk::GetInstanceProcAddr(instance(), "vkCmdInsertDebugUtilsLabelEXT");
ASSERT_TRUE(fpvkCmdInsertDebugUtilsLabelEXT); // Must be extant if extension is enabled
if (DeviceSimulation()) {
printf("%sSkipping object naming test.\n", kSkipPrefix);
return;
}
DebugUtilsLabelCheckData callback_data;
auto empty_callback = [](const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, DebugUtilsLabelCheckData *data) {
data->count++;
};
callback_data.count = 0;
callback_data.callback = empty_callback;
auto callback_create_info = lvl_init_struct<VkDebugUtilsMessengerCreateInfoEXT>();
callback_create_info.messageSeverity =
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
callback_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT;
callback_create_info.pfnUserCallback = DebugUtilsCallback;
callback_create_info.pUserData = &callback_data;
VkDebugUtilsMessengerEXT my_messenger = VK_NULL_HANDLE;
fpvkCreateDebugUtilsMessengerEXT(instance(), &callback_create_info, nullptr, &my_messenger);
VkBuffer buffer;
VkDeviceMemory memory_1, memory_2;
std::string memory_name = "memory_name";
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
buffer_create_info.size = 1;
vk::CreateBuffer(device(), &buffer_create_info, nullptr, &buffer);
VkMemoryRequirements memRequirements;
vk::GetBufferMemoryRequirements(device(), buffer, &memRequirements);
VkMemoryAllocateInfo memory_allocate_info = {};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.allocationSize = memRequirements.size;
memory_allocate_info.memoryTypeIndex = 0;
vk::AllocateMemory(device(), &memory_allocate_info, nullptr, &memory_1);
vk::AllocateMemory(device(), &memory_allocate_info, nullptr, &memory_2);
VkDebugUtilsObjectNameInfoEXT name_info = {};
name_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
name_info.pNext = nullptr;
name_info.objectType = VK_OBJECT_TYPE_DEVICE_MEMORY;
name_info.pObjectName = memory_name.c_str();
// Pass in bad handle make sure ObjectTracker catches it
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDebugUtilsObjectNameInfoEXT-objectType-02590");
name_info.objectHandle = (uint64_t)0xcadecade;
fpvkSetDebugUtilsObjectNameEXT(device(), &name_info);
m_errorMonitor->VerifyFound();
// Pass in 'unknown' object type and see if parameter validation catches it
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDebugUtilsObjectNameInfoEXT-objectType-02589");
name_info.objectHandle = (uint64_t)memory_2;
name_info.objectType = VK_OBJECT_TYPE_UNKNOWN;
fpvkSetDebugUtilsObjectNameEXT(device(), &name_info);
m_errorMonitor->VerifyFound();
name_info.objectType = VK_OBJECT_TYPE_DEVICE_MEMORY;
fpvkSetDebugUtilsObjectNameEXT(device(), &name_info);
vk::BindBufferMemory(device(), buffer, memory_1, 0);
// Test core_validation layer
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, memory_name);
vk::BindBufferMemory(device(), buffer, memory_2, 0);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), memory_1, nullptr);
memory_1 = VK_NULL_HANDLE;
vk::FreeMemory(device(), memory_2, nullptr);
memory_2 = VK_NULL_HANDLE;
vk::DestroyBuffer(device(), buffer, nullptr);
buffer = VK_NULL_HANDLE;
VkCommandBuffer commandBuffer;
std::string commandBuffer_name = "command_buffer_name";
VkCommandPool commandpool_1;
VkCommandPool commandpool_2;
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = m_device->graphics_queue_node_index_;
pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vk::CreateCommandPool(device(), &pool_create_info, nullptr, &commandpool_1);
vk::CreateCommandPool(device(), &pool_create_info, nullptr, &commandpool_2);
VkCommandBufferAllocateInfo command_buffer_allocate_info{};
command_buffer_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_allocate_info.commandPool = commandpool_1;
command_buffer_allocate_info.commandBufferCount = 1;
command_buffer_allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
vk::AllocateCommandBuffers(device(), &command_buffer_allocate_info, &commandBuffer);
name_info.objectHandle = (uint64_t)commandBuffer;
name_info.objectType = VK_OBJECT_TYPE_COMMAND_BUFFER;
name_info.pObjectName = commandBuffer_name.c_str();
fpvkSetDebugUtilsObjectNameEXT(device(), &name_info);
VkCommandBufferBeginInfo cb_begin_Info = {};
cb_begin_Info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cb_begin_Info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vk::BeginCommandBuffer(commandBuffer, &cb_begin_Info);
const VkRect2D scissor = {{-1, 0}, {16, 16}};
const VkRect2D scissors[] = {scissor, scissor};
auto command_label = lvl_init_struct<VkDebugUtilsLabelEXT>();
command_label.pLabelName = "Command Label 0123";
command_label.color[0] = 0.;
command_label.color[1] = 1.;
command_label.color[2] = 2.;
command_label.color[3] = 3.0;
bool command_label_test = false;
auto command_label_callback = [command_label, &command_label_test](const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
DebugUtilsLabelCheckData *data) {
data->count++;
command_label_test = false;
if (pCallbackData->cmdBufLabelCount == 1) {
command_label_test = pCallbackData->pCmdBufLabels[0] == command_label;
}
};
callback_data.callback = command_label_callback;
fpvkCmdInsertDebugUtilsLabelEXT(commandBuffer, &command_label);
// Test parameter_validation layer
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, commandBuffer_name);
vk::CmdSetScissor(commandBuffer, 0, 1, scissors);
m_errorMonitor->VerifyFound();
// Check the label test
if (!command_label_test) {
ADD_FAILURE() << "Command label '" << command_label.pLabelName << "' not passed to callback.";
}
// Test object_tracker layer
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, commandBuffer_name);
vk::FreeCommandBuffers(device(), commandpool_2, 1, &commandBuffer);
m_errorMonitor->VerifyFound();
vk::DestroyCommandPool(device(), commandpool_1, NULL);
vk::DestroyCommandPool(device(), commandpool_2, NULL);
fpvkDestroyDebugUtilsMessengerEXT(instance(), my_messenger, nullptr);
}
TEST_F(VkLayerTest, InvalidStructSType) {
TEST_DESCRIPTION("Specify an invalid VkStructureType for a Vulkan structure's sType field");
ASSERT_NO_FATAL_FAILURE(Init());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "parameter pAllocateInfo->sType must be");
// Zero struct memory, effectively setting sType to
// VK_STRUCTURE_TYPE_APPLICATION_INFO
// Expected to trigger an error with
// parameter_validation::validate_struct_type
VkMemoryAllocateInfo alloc_info = {};
VkDeviceMemory memory = VK_NULL_HANDLE;
vk::AllocateMemory(device(), &alloc_info, NULL, &memory);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "parameter pSubmits[0].sType must be");
// Zero struct memory, effectively setting sType to
// VK_STRUCTURE_TYPE_APPLICATION_INFO
// Expected to trigger an error with
// parameter_validation::validate_struct_type_array
VkSubmitInfo submit_info = {};
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, InvalidStructPNext) {
TEST_DESCRIPTION("Specify an invalid value for a Vulkan structure's pNext field");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(Init());
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "value of pCreateInfo->pNext must be NULL");
// Set VkMemoryAllocateInfo::pNext to a non-NULL value, when pNext must be NULL.
// Need to pick a function that has no allowed pNext structure types.
// Expected to trigger an error with parameter_validation::validate_struct_pnext
VkEvent event = VK_NULL_HANDLE;
VkEventCreateInfo event_alloc_info = {};
// Zero-initialization will provide the correct sType
VkApplicationInfo app_info = {};
event_alloc_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
event_alloc_info.pNext = &app_info;
vk::CreateEvent(device(), &event_alloc_info, NULL, &event);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, " chain includes a structure with unexpected VkStructureType ");
// Set VkMemoryAllocateInfo::pNext to a non-NULL value, but use
// a function that has allowed pNext structure types and specify
// a structure type that is not allowed.
// Expected to trigger an error with parameter_validation::validate_struct_pnext
VkDeviceMemory memory = VK_NULL_HANDLE;
VkMemoryAllocateInfo memory_alloc_info = {};
memory_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_alloc_info.pNext = &app_info;
vk::AllocateMemory(device(), &memory_alloc_info, NULL, &memory);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, " chain includes a structure with unexpected VkStructureType ");
// Same concept as above, but unlike vkAllocateMemory where VkMemoryAllocateInfo is a const
// in vkGetPhysicalDeviceProperties2, VkPhysicalDeviceProperties2 is not a const
VkPhysicalDeviceProperties2 physical_device_properties2 = {};
physical_device_properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
physical_device_properties2.pNext = &app_info;
vkGetPhysicalDeviceProperties2KHR(gpu(), &physical_device_properties2);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, UnrecognizedValueOutOfRange) {
ASSERT_NO_FATAL_FAILURE(Init());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit,
"does not fall within the begin..end range of the core VkFormat enumeration tokens");
// Specify an invalid VkFormat value
// Expected to trigger an error with
// parameter_validation::validate_ranged_enum
VkFormatProperties format_properties;
vk::GetPhysicalDeviceFormatProperties(gpu(), static_cast<VkFormat>(8000), &format_properties);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, UnrecognizedValueBadMask) {
ASSERT_NO_FATAL_FAILURE(Init());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "contains flag bits that are not recognized members of");
// Specify an invalid VkFlags bitmask value
// Expected to trigger an error with parameter_validation::validate_flags
VkImageFormatProperties image_format_properties;
vk::GetPhysicalDeviceImageFormatProperties(gpu(), VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
static_cast<VkImageUsageFlags>(1 << 25), 0, &image_format_properties);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, UnrecognizedValueBadFlag) {
ASSERT_NO_FATAL_FAILURE(Init());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "contains flag bits that are not recognized members of");
// Specify an invalid VkFlags array entry
// Expected to trigger an error with parameter_validation::validate_flags_array
VkSemaphore semaphore;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore);
// `stage_flags` is set to a value which, currently, is not a defined stage flag
// `VK_IMAGE_ASPECT_FLAG_BITS_MAX_ENUM` works well for this
VkPipelineStageFlags stage_flags = VK_IMAGE_ASPECT_FLAG_BITS_MAX_ENUM;
// `waitSemaphoreCount` *must* be greater than 0 to perform this check
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = &semaphore;
submit_info.pWaitDstStageMask = &stage_flags;
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, UnrecognizedValueBadBool) {
// Make sure using VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE doesn't trigger a false positive.
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME);
} else {
printf("%s VK_KHR_sampler_mirror_clamp_to_edge extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
// Specify an invalid VkBool32 value, expecting a warning with parameter_validation::validate_bool32
VkSamplerCreateInfo sampler_info = SafeSaneSamplerCreateInfo();
sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;
sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;
sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;
// Not VK_TRUE or VK_FALSE
sampler_info.anisotropyEnable = 3;
CreateSamplerTest(*this, &sampler_info, "is neither VK_TRUE nor VK_FALSE");
}
TEST_F(VkLayerTest, UnrecognizedValueMaxEnum) {
ASSERT_NO_FATAL_FAILURE(Init());
// Specify MAX_ENUM
VkFormatProperties format_properties;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "does not fall within the begin..end range");
vk::GetPhysicalDeviceFormatProperties(gpu(), VK_FORMAT_MAX_ENUM, &format_properties);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, SubmitSignaledFence) {
vk_testing::Fence testFence;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "submitted in SIGNALED state. Fences must be reset before being submitted");
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.pNext = NULL;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_commandBuffer->begin();
m_commandBuffer->ClearAllBuffers(m_renderTargets, m_clear_color, nullptr, m_depth_clear_color, m_stencil_clear_color);
m_commandBuffer->end();
testFence.init(*m_device, fenceInfo);
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, testFence.handle());
vk::QueueWaitIdle(m_device->m_queue);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, LeakAnObject) {
TEST_DESCRIPTION("Create a fence and destroy its device without first destroying the fence.");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
// Workaround for overzealous layers checking even the guaranteed 0th queue family
const auto q_props = vk_testing::PhysicalDevice(gpu()).queue_properties();
ASSERT_TRUE(q_props.size() > 0);
ASSERT_TRUE(q_props[0].queueCount > 0);
const float q_priority[] = {1.0f};
VkDeviceQueueCreateInfo queue_ci = {};
queue_ci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_ci.queueFamilyIndex = 0;
queue_ci.queueCount = 1;
queue_ci.pQueuePriorities = q_priority;
VkDeviceCreateInfo device_ci = {};
device_ci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_ci.queueCreateInfoCount = 1;
device_ci.pQueueCreateInfos = &queue_ci;
VkDevice leaky_device;
ASSERT_VK_SUCCESS(vk::CreateDevice(gpu(), &device_ci, nullptr, &leaky_device));
const VkFenceCreateInfo fence_ci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
VkFence leaked_fence;
ASSERT_VK_SUCCESS(vk::CreateFence(leaky_device, &fence_ci, nullptr, &leaked_fence));
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyDevice-device-00378");
vk::DestroyDevice(leaky_device, nullptr);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, UseObjectWithWrongDevice) {
TEST_DESCRIPTION(
"Try to destroy a render pass object using a device other than the one it was created on. This should generate a distinct "
"error from the invalid handle error.");
// Create first device and renderpass
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
// Create second device
float priorities[] = {1.0f};
VkDeviceQueueCreateInfo queue_info{};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = NULL;
queue_info.flags = 0;
queue_info.queueFamilyIndex = 0;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = &priorities[0];
VkDeviceCreateInfo device_create_info = {};
auto features = m_device->phy().features();
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = NULL;
device_create_info.queueCreateInfoCount = 1;
device_create_info.pQueueCreateInfos = &queue_info;
device_create_info.enabledLayerCount = 0;
device_create_info.ppEnabledLayerNames = NULL;
device_create_info.pEnabledFeatures = &features;
VkDevice second_device;
ASSERT_VK_SUCCESS(vk::CreateDevice(gpu(), &device_create_info, NULL, &second_device));
// Try to destroy the renderpass from the first device using the second device
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyRenderPass-renderPass-parent");
vk::DestroyRenderPass(second_device, m_renderPass, NULL);
m_errorMonitor->VerifyFound();
vk::DestroyDevice(second_device, NULL);
}
TEST_F(VkLayerTest, InvalidAllocationCallbacks) {
TEST_DESCRIPTION("Test with invalid VkAllocationCallbacks");
ASSERT_NO_FATAL_FAILURE(Init());
// vk::CreateInstance, and vk::CreateDevice tend to crash in the Loader Trampoline ATM, so choosing vk::CreateCommandPool
const VkCommandPoolCreateInfo cpci = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, nullptr, 0,
DeviceObj()->QueueFamilyMatching(0, 0, true)};
VkCommandPool cmdPool;
struct Alloc {
static VKAPI_ATTR void *VKAPI_CALL alloc(void *, size_t, size_t, VkSystemAllocationScope) { return nullptr; };
static VKAPI_ATTR void *VKAPI_CALL realloc(void *, void *, size_t, size_t, VkSystemAllocationScope) { return nullptr; };
static VKAPI_ATTR void VKAPI_CALL free(void *, void *){};
static VKAPI_ATTR void VKAPI_CALL internalAlloc(void *, size_t, VkInternalAllocationType, VkSystemAllocationScope){};
static VKAPI_ATTR void VKAPI_CALL internalFree(void *, size_t, VkInternalAllocationType, VkSystemAllocationScope){};
};
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAllocationCallbacks-pfnAllocation-00632");
const VkAllocationCallbacks allocator = {nullptr, nullptr, Alloc::realloc, Alloc::free, nullptr, nullptr};
vk::CreateCommandPool(device(), &cpci, &allocator, &cmdPool);
m_errorMonitor->VerifyFound();
}
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAllocationCallbacks-pfnReallocation-00633");
const VkAllocationCallbacks allocator = {nullptr, Alloc::alloc, nullptr, Alloc::free, nullptr, nullptr};
vk::CreateCommandPool(device(), &cpci, &allocator, &cmdPool);
m_errorMonitor->VerifyFound();
}
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAllocationCallbacks-pfnFree-00634");
const VkAllocationCallbacks allocator = {nullptr, Alloc::alloc, Alloc::realloc, nullptr, nullptr, nullptr};
vk::CreateCommandPool(device(), &cpci, &allocator, &cmdPool);
m_errorMonitor->VerifyFound();
}
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAllocationCallbacks-pfnInternalAllocation-00635");
const VkAllocationCallbacks allocator = {nullptr, Alloc::alloc, Alloc::realloc, Alloc::free, nullptr, Alloc::internalFree};
vk::CreateCommandPool(device(), &cpci, &allocator, &cmdPool);
m_errorMonitor->VerifyFound();
}
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAllocationCallbacks-pfnInternalAllocation-00635");
const VkAllocationCallbacks allocator = {nullptr, Alloc::alloc, Alloc::realloc, Alloc::free, Alloc::internalAlloc, nullptr};
vk::CreateCommandPool(device(), &cpci, &allocator, &cmdPool);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, MismatchedQueueFamiliesOnSubmit) {
TEST_DESCRIPTION(
"Submit command buffer created using one queue family and attempt to submit them on a queue created in a different queue "
"family.");
ASSERT_NO_FATAL_FAILURE(Init()); // assumes it initializes all queue families on vk::CreateDevice
// This test is meaningless unless we have multiple queue families
auto queue_family_properties = m_device->phy().queue_properties();
std::vector<uint32_t> queue_families;
for (uint32_t i = 0; i < queue_family_properties.size(); ++i)
if (queue_family_properties[i].queueCount > 0) queue_families.push_back(i);
if (queue_families.size() < 2) {
printf("%s Device only has one queue family; skipped.\n", kSkipPrefix);
return;
}
const uint32_t queue_family = queue_families[0];
const uint32_t other_queue_family = queue_families[1];
VkQueue other_queue;
vk::GetDeviceQueue(m_device->device(), other_queue_family, 0, &other_queue);
VkCommandPoolObj cmd_pool(m_device, queue_family);
VkCommandBufferObj cmd_buff(m_device, &cmd_pool);
cmd_buff.begin();
cmd_buff.end();
// Submit on the wrong queue
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &cmd_buff.handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkQueueSubmit-pCommandBuffers-00074");
vk::QueueSubmit(other_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, TemporaryExternalSemaphore) {
#ifdef _WIN32
const auto extension_name = VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME;
const auto handle_type = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR;
#else
const auto extension_name = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
const auto handle_type = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
#endif
// Check for external semaphore instance extensions
if (InstanceExtensionSupported(VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME);
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s External semaphore extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
// Check for external semaphore device extensions
if (DeviceExtensionSupported(gpu(), nullptr, extension_name)) {
m_device_extension_names.push_back(extension_name);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s External semaphore extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
// Check for external semaphore import and export capability
VkPhysicalDeviceExternalSemaphoreInfoKHR esi = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO_KHR, nullptr,
handle_type};
VkExternalSemaphorePropertiesKHR esp = {VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES_KHR, nullptr};
auto vkGetPhysicalDeviceExternalSemaphorePropertiesKHR =
(PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR)vk::GetInstanceProcAddr(
instance(), "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR");
vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(gpu(), &esi, &esp);
if (!(esp.externalSemaphoreFeatures & VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT_KHR) ||
!(esp.externalSemaphoreFeatures & VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT_KHR)) {
printf("%s External semaphore does not support importing and exporting, skipping test\n", kSkipPrefix);
return;
}
VkResult err;
// Create a semaphore to export payload from
VkExportSemaphoreCreateInfoKHR esci = {VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR, nullptr, handle_type};
VkSemaphoreCreateInfo sci = {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &esci, 0};
VkSemaphore export_semaphore;
err = vk::CreateSemaphore(m_device->device(), &sci, nullptr, &export_semaphore);
ASSERT_VK_SUCCESS(err);
// Create a semaphore to import payload into
sci.pNext = nullptr;
VkSemaphore import_semaphore;
err = vk::CreateSemaphore(m_device->device(), &sci, nullptr, &import_semaphore);
ASSERT_VK_SUCCESS(err);
#ifdef _WIN32
// Export semaphore payload to an opaque handle
HANDLE handle = nullptr;
VkSemaphoreGetWin32HandleInfoKHR ghi = {VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR, nullptr, export_semaphore,
handle_type};
auto vkGetSemaphoreWin32HandleKHR =
(PFN_vkGetSemaphoreWin32HandleKHR)vk::GetDeviceProcAddr(m_device->device(), "vkGetSemaphoreWin32HandleKHR");
err = vkGetSemaphoreWin32HandleKHR(m_device->device(), &ghi, &handle);
ASSERT_VK_SUCCESS(err);
// Import opaque handle exported above *temporarily*
VkImportSemaphoreWin32HandleInfoKHR ihi = {VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR,
nullptr,
import_semaphore,
VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR,
handle_type,
handle,
nullptr};
auto vkImportSemaphoreWin32HandleKHR =
(PFN_vkImportSemaphoreWin32HandleKHR)vk::GetDeviceProcAddr(m_device->device(), "vkImportSemaphoreWin32HandleKHR");
err = vkImportSemaphoreWin32HandleKHR(m_device->device(), &ihi);
ASSERT_VK_SUCCESS(err);
#else
// Export semaphore payload to an opaque handle
int fd = 0;
VkSemaphoreGetFdInfoKHR ghi = {VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR, nullptr, export_semaphore, handle_type};
auto vkGetSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)vk::GetDeviceProcAddr(m_device->device(), "vkGetSemaphoreFdKHR");
err = vkGetSemaphoreFdKHR(m_device->device(), &ghi, &fd);
ASSERT_VK_SUCCESS(err);
// Import opaque handle exported above *temporarily*
VkImportSemaphoreFdInfoKHR ihi = {VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR, nullptr, import_semaphore,
VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR, handle_type, fd};
auto vkImportSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)vk::GetDeviceProcAddr(m_device->device(), "vkImportSemaphoreFdKHR");
err = vkImportSemaphoreFdKHR(m_device->device(), &ihi);
ASSERT_VK_SUCCESS(err);
#endif
// Wait on the imported semaphore twice in vk::QueueSubmit, the second wait should be an error
VkPipelineStageFlags flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
VkSubmitInfo si[] = {
{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, &flags, 0, nullptr, 1, &export_semaphore},
{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 1, &import_semaphore, &flags, 0, nullptr, 0, nullptr},
{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, &flags, 0, nullptr, 1, &export_semaphore},
{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 1, &import_semaphore, &flags, 0, nullptr, 0, nullptr},
};
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "has no way to be signaled");
vk::QueueSubmit(m_device->m_queue, 4, si, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
auto index = m_device->graphics_queue_node_index_;
if (m_device->queue_props[index].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) {
// Wait on the imported semaphore twice in vk::QueueBindSparse, the second wait should be an error
VkBindSparseInfo bi[] = {
{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 1, &export_semaphore},
{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, nullptr, 1, &import_semaphore, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr},
{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 1, &export_semaphore},
{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, nullptr, 1, &import_semaphore, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr},
};
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "has no way to be signaled");
vk::QueueBindSparse(m_device->m_queue, 4, bi, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
// Cleanup
err = vk::QueueWaitIdle(m_device->m_queue);
ASSERT_VK_SUCCESS(err);
vk::DestroySemaphore(m_device->device(), export_semaphore, nullptr);
vk::DestroySemaphore(m_device->device(), import_semaphore, nullptr);
}
TEST_F(VkLayerTest, TemporaryExternalFence) {
#ifdef _WIN32
const auto extension_name = VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME;
const auto handle_type = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR;
#else
const auto extension_name = VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME;
const auto handle_type = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
#endif
// Check for external fence instance extensions
if (InstanceExtensionSupported(VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME);
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s External fence extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
// Check for external fence device extensions
if (DeviceExtensionSupported(gpu(), nullptr, extension_name)) {
m_device_extension_names.push_back(extension_name);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME);
} else {
printf("%s External fence extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
// Check for external fence import and export capability
VkPhysicalDeviceExternalFenceInfoKHR efi = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO_KHR, nullptr, handle_type};
VkExternalFencePropertiesKHR efp = {VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES_KHR, nullptr};
auto vkGetPhysicalDeviceExternalFencePropertiesKHR = (PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR)vk::GetInstanceProcAddr(
instance(), "vkGetPhysicalDeviceExternalFencePropertiesKHR");
vkGetPhysicalDeviceExternalFencePropertiesKHR(gpu(), &efi, &efp);
if (!(efp.externalFenceFeatures & VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT_KHR) ||
!(efp.externalFenceFeatures & VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT_KHR)) {
printf("%s External fence does not support importing and exporting, skipping test\n", kSkipPrefix);
return;
}
VkResult err;
// Create a fence to export payload from
VkFence export_fence;
{
VkExportFenceCreateInfoKHR efci = {VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR, nullptr, handle_type};
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, &efci, 0};
err = vk::CreateFence(m_device->device(), &fci, nullptr, &export_fence);
ASSERT_VK_SUCCESS(err);
}
// Create a fence to import payload into
VkFence import_fence;
{
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, 0};
err = vk::CreateFence(m_device->device(), &fci, nullptr, &import_fence);
ASSERT_VK_SUCCESS(err);
}
#ifdef _WIN32
// Export fence payload to an opaque handle
HANDLE handle = nullptr;
{
VkFenceGetWin32HandleInfoKHR ghi = {VK_STRUCTURE_TYPE_FENCE_GET_WIN32_HANDLE_INFO_KHR, nullptr, export_fence, handle_type};
auto vkGetFenceWin32HandleKHR =
(PFN_vkGetFenceWin32HandleKHR)vk::GetDeviceProcAddr(m_device->device(), "vkGetFenceWin32HandleKHR");
err = vkGetFenceWin32HandleKHR(m_device->device(), &ghi, &handle);
ASSERT_VK_SUCCESS(err);
}
// Import opaque handle exported above
{
VkImportFenceWin32HandleInfoKHR ifi = {VK_STRUCTURE_TYPE_IMPORT_FENCE_WIN32_HANDLE_INFO_KHR,
nullptr,
import_fence,
VK_FENCE_IMPORT_TEMPORARY_BIT_KHR,
handle_type,
handle,
nullptr};
auto vkImportFenceWin32HandleKHR =
(PFN_vkImportFenceWin32HandleKHR)vk::GetDeviceProcAddr(m_device->device(), "vkImportFenceWin32HandleKHR");
err = vkImportFenceWin32HandleKHR(m_device->device(), &ifi);
ASSERT_VK_SUCCESS(err);
}
#else
// Export fence payload to an opaque handle
int fd = 0;
{
VkFenceGetFdInfoKHR gfi = {VK_STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR, nullptr, export_fence, handle_type};
auto vkGetFenceFdKHR = (PFN_vkGetFenceFdKHR)vk::GetDeviceProcAddr(m_device->device(), "vkGetFenceFdKHR");
err = vkGetFenceFdKHR(m_device->device(), &gfi, &fd);
ASSERT_VK_SUCCESS(err);
}
// Import opaque handle exported above
{
VkImportFenceFdInfoKHR ifi = {VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR, nullptr, import_fence,
VK_FENCE_IMPORT_TEMPORARY_BIT_KHR, handle_type, fd};
auto vkImportFenceFdKHR = (PFN_vkImportFenceFdKHR)vk::GetDeviceProcAddr(m_device->device(), "vkImportFenceFdKHR");
err = vkImportFenceFdKHR(m_device->device(), &ifi);
ASSERT_VK_SUCCESS(err);
}
#endif
// Undo the temporary import
vk::ResetFences(m_device->device(), 1, &import_fence);
// Signal the previously imported fence twice, the second signal should produce a validation error
vk::QueueSubmit(m_device->m_queue, 0, nullptr, import_fence);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "is already in use by another submission.");
vk::QueueSubmit(m_device->m_queue, 0, nullptr, import_fence);
m_errorMonitor->VerifyFound();
// Cleanup
err = vk::QueueWaitIdle(m_device->m_queue);
ASSERT_VK_SUCCESS(err);
vk::DestroyFence(m_device->device(), export_fence, nullptr);
vk::DestroyFence(m_device->device(), import_fence, nullptr);
}
TEST_F(VkLayerTest, InvalidCmdBufferEventDestroyed) {
TEST_DESCRIPTION("Attempt to draw with a command buffer that is invalid due to an event dependency being destroyed.");
ASSERT_NO_FATAL_FAILURE(Init());
VkEvent event;
VkEventCreateInfo evci = {};
evci.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
VkResult result = vk::CreateEvent(m_device->device(), &evci, NULL, &event);
ASSERT_VK_SUCCESS(result);
m_commandBuffer->begin();
vk::CmdSetEvent(m_commandBuffer->handle(), event, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
m_commandBuffer->end();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkEvent");
// Destroy event dependency prior to submit to cause ERROR
vk::DestroyEvent(m_device->device(), event, NULL);
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, InvalidCmdBufferQueryPoolDestroyed) {
TEST_DESCRIPTION("Attempt to draw with a command buffer that is invalid due to a query pool dependency being destroyed.");
ASSERT_NO_FATAL_FAILURE(Init());
VkQueryPool query_pool;
VkQueryPoolCreateInfo qpci{};
qpci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
qpci.queryType = VK_QUERY_TYPE_TIMESTAMP;
qpci.queryCount = 1;
VkResult result = vk::CreateQueryPool(m_device->device(), &qpci, nullptr, &query_pool);
ASSERT_VK_SUCCESS(result);
m_commandBuffer->begin();
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
m_commandBuffer->end();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkQueryPool");
// Destroy query pool dependency prior to submit to cause ERROR
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, DeviceFeature2AndVertexAttributeDivisorExtensionUnenabled) {
TEST_DESCRIPTION(
"Test unenabled VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME & "
"VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME.");
VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT vadf = {};
vadf.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT;
VkPhysicalDeviceFeatures2 pd_features2 = {};
pd_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
pd_features2.pNext = &vadf;
ASSERT_NO_FATAL_FAILURE(Init());
vk_testing::QueueCreateInfoArray queue_info(m_device->queue_props);
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &pd_features2;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
VkDevice testDevice;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit,
"VK_KHR_get_physical_device_properties2 must be enabled when it creates an instance");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VK_EXT_vertex_attribute_divisor must be enabled when it creates a device");
m_errorMonitor->SetUnexpectedError("Failed to create device chain");
vk::CreateDevice(gpu(), &device_create_info, NULL, &testDevice);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, Features12AndpNext) {
TEST_DESCRIPTION("Test VkPhysicalDeviceVulkan12Features and illegal struct in pNext");
SetTargetApiVersion(VK_API_VERSION_1_2);
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceValidationVersion() < VK_API_VERSION_1_2) {
printf("%s Vulkan12Struct requires Vulkan 1.2+, skipping test\n", kSkipPrefix);
return;
}
if (!DeviceExtensionSupported(gpu(), nullptr, VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME) ||
!DeviceExtensionSupported(gpu(), nullptr, VK_KHR_8BIT_STORAGE_EXTENSION_NAME) ||
!DeviceExtensionSupported(gpu(), nullptr, VK_KHR_16BIT_STORAGE_EXTENSION_NAME)) {
printf("%s Storage Extension(s) not supported, skipping tests\n", kSkipPrefix);
return;
}
VkPhysicalDevice16BitStorageFeatures sixteen_bit = {};
sixteen_bit.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES;
sixteen_bit.storageBuffer16BitAccess = true;
VkPhysicalDeviceVulkan11Features features11 = {};
features11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
features11.pNext = &sixteen_bit;
features11.storageBuffer16BitAccess = true;
VkPhysicalDevice8BitStorageFeatures eight_bit = {};
eight_bit.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES;
eight_bit.pNext = &features11;
eight_bit.storageBuffer8BitAccess = true;
VkPhysicalDeviceVulkan12Features features12 = {};
features12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
features12.pNext = &eight_bit;
features12.storageBuffer8BitAccess = true;
vk_testing::PhysicalDevice physical_device(gpu());
vk_testing::QueueCreateInfoArray queue_info(physical_device.queue_properties());
std::vector<VkDeviceQueueCreateInfo> create_queue_infos;
auto qci = queue_info.data();
for (uint32_t i = 0; i < queue_info.size(); ++i) {
if (qci[i].queueCount) {
create_queue_infos.push_back(qci[i]);
}
}
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &features12;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
VkDevice testDevice;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-pNext-02829");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-pNext-02830");
m_errorMonitor->SetUnexpectedError("Failed to create device chain");
vk::CreateDevice(gpu(), &device_create_info, NULL, &testDevice);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, Features12Extensions) {
TEST_DESCRIPTION("Checks that 1.2 features are enabled if extension is passed in.");
SetTargetApiVersion(VK_API_VERSION_1_2);
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceValidationVersion() < VK_API_VERSION_1_2) {
printf("%s Vulkan12Struct requires Vulkan 1.2+, skipping test\n", kSkipPrefix);
return;
}
vk_testing::PhysicalDevice physical_device(gpu());
vk_testing::QueueCreateInfoArray queue_info(physical_device.queue_properties());
std::vector<VkDeviceQueueCreateInfo> create_queue_infos;
auto qci = queue_info.data();
for (uint32_t i = 0; i < queue_info.size(); ++i) {
if (qci[i].queueCount) {
create_queue_infos.push_back(qci[i]);
}
}
// Explicity set all tested features to false
VkPhysicalDeviceVulkan12Features features12 = {};
features12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
features12.pNext = nullptr;
features12.drawIndirectCount = VK_FALSE;
features12.samplerMirrorClampToEdge = VK_FALSE;
features12.descriptorIndexing = VK_FALSE;
features12.samplerFilterMinmax = VK_FALSE;
features12.shaderOutputViewportIndex = VK_FALSE;
features12.shaderOutputLayer = VK_TRUE; // Set true since both shader_viewport features need to true
std::vector<const char *> device_extensions;
// Go through each extension and if supported add to list and add failure to check for
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DRAW_INDIRECT_COUNT_EXTENSION_NAME)) {
device_extensions.push_back(VK_KHR_DRAW_INDIRECT_COUNT_EXTENSION_NAME);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-ppEnabledExtensions-02831");
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME)) {
device_extensions.push_back(VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-ppEnabledExtensions-02832");
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME)) {
device_extensions.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
device_extensions.push_back(VK_KHR_MAINTENANCE3_EXTENSION_NAME);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-ppEnabledExtensions-02833");
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME)) {
device_extensions.push_back(VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-ppEnabledExtensions-02834");
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME)) {
device_extensions.push_back(VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-ppEnabledExtensions-02835");
}
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &features12;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
device_create_info.ppEnabledExtensionNames = device_extensions.data();
device_create_info.enabledExtensionCount = device_extensions.size();
VkDevice testDevice;
m_errorMonitor->SetUnexpectedError("Failed to create device chain");
vk::CreateDevice(gpu(), &device_create_info, NULL, &testDevice);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, FeaturesVariablePointer) {
TEST_DESCRIPTION("Checks VK_KHR_variable_pointers features.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
std::vector<const char *> device_extensions;
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME) &&
DeviceExtensionSupported(gpu(), nullptr, VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME)) {
device_extensions.push_back(VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME);
device_extensions.push_back(VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME);
} else {
printf("%s VariablePointer Extension not supported, skipping tests\n", kSkipPrefix);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
// Create a device that enables variablePointers but not variablePointersStorageBuffer
auto variable_features = lvl_init_struct<VkPhysicalDeviceVariablePointersFeatures>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&variable_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (variable_features.variablePointers == VK_FALSE) {
printf("%s variablePointer feature not supported, skipping tests\n", kSkipPrefix);
return;
}
variable_features.variablePointersStorageBuffer = VK_FALSE;
vk_testing::PhysicalDevice physical_device(gpu());
vk_testing::QueueCreateInfoArray queue_info(physical_device.queue_properties());
std::vector<VkDeviceQueueCreateInfo> create_queue_infos;
auto qci = queue_info.data();
for (uint32_t i = 0; i < queue_info.size(); ++i) {
if (qci[i].queueCount) {
create_queue_infos.push_back(qci[i]);
}
}
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &features2;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
device_create_info.ppEnabledExtensionNames = device_extensions.data();
device_create_info.enabledExtensionCount = device_extensions.size();
VkDevice testDevice;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkPhysicalDeviceVariablePointersFeatures-variablePointers-01431");
vk::CreateDevice(gpu(), &device_create_info, NULL, &testDevice);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, FeaturesMultiview) {
TEST_DESCRIPTION("Checks VK_KHR_multiview features.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
std::vector<const char *> device_extensions;
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MULTIVIEW_EXTENSION_NAME)) {
device_extensions.push_back(VK_KHR_MULTIVIEW_EXTENSION_NAME);
} else {
printf("%s Multiview Extension not supported, skipping tests\n", kSkipPrefix);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
auto multiview_features = lvl_init_struct<VkPhysicalDeviceMultiviewFeatures>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&multiview_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
// Set false to trigger VUs
multiview_features.multiview = VK_FALSE;
vk_testing::PhysicalDevice physical_device(gpu());
vk_testing::QueueCreateInfoArray queue_info(physical_device.queue_properties());
std::vector<VkDeviceQueueCreateInfo> create_queue_infos;
auto qci = queue_info.data();
for (uint32_t i = 0; i < queue_info.size(); ++i) {
if (qci[i].queueCount) {
create_queue_infos.push_back(qci[i]);
}
}
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &features2;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
device_create_info.ppEnabledExtensionNames = device_extensions.data();
device_create_info.enabledExtensionCount = device_extensions.size();
VkDevice testDevice;
if ((multiview_features.multiviewGeometryShader == VK_FALSE) && (multiview_features.multiviewTessellationShader == VK_FALSE)) {
printf("%s multiviewGeometryShader and multiviewTessellationShader feature not supported, skipping tests\n", kSkipPrefix);
return;
}
if (multiview_features.multiviewGeometryShader == VK_TRUE) {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkPhysicalDeviceMultiviewFeatures-multiviewGeometryShader-00580");
}
if (multiview_features.multiviewTessellationShader == VK_TRUE) {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkPhysicalDeviceMultiviewFeatures-multiviewTessellationShader-00581");
}
vk::CreateDevice(gpu(), &device_create_info, NULL, &testDevice);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, BeginQueryOnTimestampPool) {
TEST_DESCRIPTION("Call CmdBeginQuery on a TIMESTAMP query pool.");
ASSERT_NO_FATAL_FAILURE(Init());
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryType-02804");
VkCommandBufferBeginInfo begin_info{};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vk::BeginCommandBuffer(m_commandBuffer->handle(), &begin_info);
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
vk::EndCommandBuffer(m_commandBuffer->handle());
m_errorMonitor->VerifyFound();
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
}
TEST_F(VkLayerTest, SwapchainAcquireImageNoSync) {
TEST_DESCRIPTION("Test vkAcquireNextImageKHR with VK_NULL_HANDLE semaphore and fence");
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
ASSERT_TRUE(InitSwapchain());
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkAcquireNextImageKHR-semaphore-01780");
uint32_t dummy;
vk::AcquireNextImageKHR(device(), m_swapchain, UINT64_MAX, VK_NULL_HANDLE, VK_NULL_HANDLE, &dummy);
m_errorMonitor->VerifyFound();
}
DestroySwapchain();
}
TEST_F(VkLayerTest, SwapchainAcquireImageNoSync2KHR) {
TEST_DESCRIPTION("Test vkAcquireNextImage2KHR with VK_NULL_HANDLE semaphore and fence");
SetTargetApiVersion(VK_API_VERSION_1_1);
bool extension_dependency_satisfied = false;
if (InstanceExtensionSupported(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME);
extension_dependency_satisfied = true;
} else if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s vkAcquireNextImage2KHR not supported, skipping test\n", kSkipPrefix);
return;
}
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (extension_dependency_satisfied && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DEVICE_GROUP_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_DEVICE_GROUP_EXTENSION_NAME);
} else if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s vkAcquireNextImage2KHR not supported, skipping test\n", kSkipPrefix);
return;
}
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
ASSERT_TRUE(InitSwapchain());
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAcquireNextImageInfoKHR-semaphore-01782");
VkAcquireNextImageInfoKHR acquire_info = {VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR};
acquire_info.swapchain = m_swapchain;
acquire_info.timeout = UINT64_MAX;
acquire_info.semaphore = VK_NULL_HANDLE;
acquire_info.fence = VK_NULL_HANDLE;
acquire_info.deviceMask = 0x1;
uint32_t dummy;
vk::AcquireNextImage2KHR(device(), &acquire_info, &dummy);
m_errorMonitor->VerifyFound();
}
DestroySwapchain();
}
TEST_F(VkLayerTest, SwapchainAcquireImageNoBinarySemaphore) {
TEST_DESCRIPTION("Test vkAcquireNextImageKHR with non-binary semaphore");
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping test\n", kSkipPrefix);
return;
}
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping test\n", kSkipPrefix);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_TRUE(InitSwapchain());
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkAcquireNextImageKHR-semaphore-03265");
uint32_t image_i;
vk::AcquireNextImageKHR(device(), m_swapchain, UINT64_MAX, semaphore, VK_NULL_HANDLE, &image_i);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
DestroySwapchain();
}
TEST_F(VkLayerTest, SwapchainAcquireImageNoBinarySemaphore2KHR) {
TEST_DESCRIPTION("Test vkAcquireNextImage2KHR with non-binary semaphore");
TEST_DESCRIPTION("Test vkAcquireNextImage2KHR with VK_NULL_HANDLE semaphore and fence");
SetTargetApiVersion(VK_API_VERSION_1_1);
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
bool extension_dependency_satisfied = false;
if (InstanceExtensionSupported(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME);
extension_dependency_satisfied = true;
} else if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s vkAcquireNextImage2KHR not supported, skipping test\n", kSkipPrefix);
return;
}
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (extension_dependency_satisfied && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DEVICE_GROUP_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_DEVICE_GROUP_EXTENSION_NAME);
} else if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s vkAcquireNextImage2KHR not supported, skipping test\n", kSkipPrefix);
return;
}
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping test\n", kSkipPrefix);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_TRUE(InitSwapchain());
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkAcquireNextImageInfoKHR acquire_info = {};
acquire_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR;
acquire_info.swapchain = m_swapchain;
acquire_info.timeout = UINT64_MAX;
acquire_info.semaphore = semaphore;
acquire_info.deviceMask = 0x1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAcquireNextImageInfoKHR-semaphore-03266");
uint32_t image_i;
vk::AcquireNextImage2KHR(device(), &acquire_info, &image_i);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
DestroySwapchain();
}
TEST_F(VkLayerTest, SwapchainAcquireTooManyImages) {
TEST_DESCRIPTION("Acquiring invalid amount of images from the swapchain.");
if (!AddSurfaceInstanceExtension()) return;
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!AddSwapchainDeviceExtension()) return;
ASSERT_NO_FATAL_FAILURE(InitState());
ASSERT_TRUE(InitSwapchain());
uint32_t image_count;
ASSERT_VK_SUCCESS(vk::GetSwapchainImagesKHR(device(), m_swapchain, &image_count, nullptr));
VkSurfaceCapabilitiesKHR caps;
ASSERT_VK_SUCCESS(vk::GetPhysicalDeviceSurfaceCapabilitiesKHR(gpu(), m_surface, &caps));
const uint32_t acquirable_count = image_count - caps.minImageCount + 1;
std::vector<VkFenceObj> fences(acquirable_count);
for (uint32_t i = 0; i < acquirable_count; ++i) {
fences[i].init(*m_device, VkFenceObj::create_info());
uint32_t image_i;
const auto res = vk::AcquireNextImageKHR(device(), m_swapchain, UINT64_MAX, VK_NULL_HANDLE, fences[i].handle(), &image_i);
ASSERT_TRUE(res == VK_SUCCESS || res == VK_SUBOPTIMAL_KHR);
}
VkFenceObj error_fence;
error_fence.init(*m_device, VkFenceObj::create_info());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkAcquireNextImageKHR-swapchain-01802");
uint32_t image_i;
vk::AcquireNextImageKHR(device(), m_swapchain, UINT64_MAX, VK_NULL_HANDLE, error_fence.handle(), &image_i);
m_errorMonitor->VerifyFound();
// Cleanup
vk::WaitForFences(device(), fences.size(), MakeVkHandles<VkFence>(fences).data(), VK_TRUE, UINT64_MAX);
DestroySwapchain();
}
TEST_F(VkLayerTest, SwapchainAcquireTooManyImages2KHR) {
TEST_DESCRIPTION("Acquiring invalid amount of images from the swapchain via vkAcquireNextImage2KHR.");
SetTargetApiVersion(VK_API_VERSION_1_1);
bool extension_dependency_satisfied = false;
if (InstanceExtensionSupported(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME);
extension_dependency_satisfied = true;
} else if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s vkAcquireNextImage2KHR not supported, skipping test\n", kSkipPrefix);
return;
}
if (!AddSurfaceInstanceExtension()) return;
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (extension_dependency_satisfied && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DEVICE_GROUP_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_DEVICE_GROUP_EXTENSION_NAME);
} else if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s vkAcquireNextImage2KHR not supported, skipping test\n", kSkipPrefix);
return;
}
if (!AddSwapchainDeviceExtension()) return;
ASSERT_NO_FATAL_FAILURE(InitState());
ASSERT_TRUE(InitSwapchain());
uint32_t image_count;
ASSERT_VK_SUCCESS(vk::GetSwapchainImagesKHR(device(), m_swapchain, &image_count, nullptr));
VkSurfaceCapabilitiesKHR caps;
ASSERT_VK_SUCCESS(vk::GetPhysicalDeviceSurfaceCapabilitiesKHR(gpu(), m_surface, &caps));
const uint32_t acquirable_count = image_count - caps.minImageCount + 1;
std::vector<VkFenceObj> fences(acquirable_count);
for (uint32_t i = 0; i < acquirable_count; ++i) {
fences[i].init(*m_device, VkFenceObj::create_info());
uint32_t image_i;
const auto res = vk::AcquireNextImageKHR(device(), m_swapchain, UINT64_MAX, VK_NULL_HANDLE, fences[i].handle(), &image_i);
ASSERT_TRUE(res == VK_SUCCESS || res == VK_SUBOPTIMAL_KHR);
}
VkFenceObj error_fence;
error_fence.init(*m_device, VkFenceObj::create_info());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkAcquireNextImage2KHR-swapchain-01803");
VkAcquireNextImageInfoKHR acquire_info = {VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR};
acquire_info.swapchain = m_swapchain;
acquire_info.timeout = UINT64_MAX;
acquire_info.fence = error_fence.handle();
acquire_info.deviceMask = 0x1;
uint32_t image_i;
vk::AcquireNextImage2KHR(device(), &acquire_info, &image_i);
m_errorMonitor->VerifyFound();
// Cleanup
vk::WaitForFences(device(), fences.size(), MakeVkHandles<VkFence>(fences).data(), VK_TRUE, UINT64_MAX);
DestroySwapchain();
}
TEST_F(VkLayerTest, InvalidDeviceMask) {
TEST_DESCRIPTION("Invalid deviceMask.");
SetTargetApiVersion(VK_API_VERSION_1_1);
bool support_surface = true;
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping VkAcquireNextImageInfoKHR test\n", kSkipPrefix);
support_surface = false;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (support_surface) {
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping BindSwapchainImageMemory test\n", kSkipPrefix);
support_surface = false;
}
}
if (DeviceValidationVersion() < VK_API_VERSION_1_1) {
printf("%s Device Groups requires Vulkan 1.1+, skipping test\n", kSkipPrefix);
return;
}
uint32_t physical_device_group_count = 0;
vk::EnumeratePhysicalDeviceGroups(instance(), &physical_device_group_count, nullptr);
if (physical_device_group_count == 0) {
printf("%s physical_device_group_count is 0, skipping test\n", kSkipPrefix);
return;
}
std::vector<VkPhysicalDeviceGroupProperties> physical_device_group(physical_device_group_count,
{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES});
vk::EnumeratePhysicalDeviceGroups(instance(), &physical_device_group_count, physical_device_group.data());
VkDeviceGroupDeviceCreateInfo create_device_pnext = {};
create_device_pnext.sType = VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO;
create_device_pnext.physicalDeviceCount = physical_device_group[0].physicalDeviceCount;
create_device_pnext.pPhysicalDevices = physical_device_group[0].physicalDevices;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &create_device_pnext, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
if (!InitSwapchain()) {
printf("%s Cannot create surface or swapchain, skipping VkAcquireNextImageInfoKHR test\n", kSkipPrefix);
support_surface = false;
}
// Test VkMemoryAllocateFlagsInfo
VkMemoryAllocateFlagsInfo alloc_flags_info = {};
alloc_flags_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO;
alloc_flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT;
alloc_flags_info.deviceMask = 0xFFFFFFFF;
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.pNext = &alloc_flags_info;
alloc_info.memoryTypeIndex = 0;
alloc_info.allocationSize = 32;
VkDeviceMemory mem;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateFlagsInfo-deviceMask-00675");
vk::AllocateMemory(m_device->device(), &alloc_info, NULL, &mem);
m_errorMonitor->VerifyFound();
alloc_flags_info.deviceMask = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateFlagsInfo-deviceMask-00676");
vk::AllocateMemory(m_device->device(), &alloc_info, NULL, &mem);
m_errorMonitor->VerifyFound();
// Test VkDeviceGroupCommandBufferBeginInfo
VkDeviceGroupCommandBufferBeginInfo dev_grp_cmd_buf_info = {};
dev_grp_cmd_buf_info.sType = VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO;
dev_grp_cmd_buf_info.deviceMask = 0xFFFFFFFF;
VkCommandBufferBeginInfo cmd_buf_info = {};
cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cmd_buf_info.pNext = &dev_grp_cmd_buf_info;
m_commandBuffer->reset();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupCommandBufferBeginInfo-deviceMask-00106");
vk::BeginCommandBuffer(m_commandBuffer->handle(), &cmd_buf_info);
m_errorMonitor->VerifyFound();
dev_grp_cmd_buf_info.deviceMask = 0;
m_commandBuffer->reset();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupCommandBufferBeginInfo-deviceMask-00107");
vk::BeginCommandBuffer(m_commandBuffer->handle(), &cmd_buf_info);
m_errorMonitor->VerifyFound();
// Test VkDeviceGroupRenderPassBeginInfo
dev_grp_cmd_buf_info.deviceMask = 0x00000001;
m_commandBuffer->reset();
vk::BeginCommandBuffer(m_commandBuffer->handle(), &cmd_buf_info);
VkDeviceGroupRenderPassBeginInfo dev_grp_rp_info = {};
dev_grp_rp_info.sType = VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO;
dev_grp_rp_info.deviceMask = 0xFFFFFFFF;
m_renderPassBeginInfo.pNext = &dev_grp_rp_info;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00905");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00907");
vk::CmdBeginRenderPass(m_commandBuffer->handle(), &m_renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
m_errorMonitor->VerifyFound();
dev_grp_rp_info.deviceMask = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00906");
vk::CmdBeginRenderPass(m_commandBuffer->handle(), &m_renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
m_errorMonitor->VerifyFound();
dev_grp_rp_info.deviceMask = 0x00000001;
dev_grp_rp_info.deviceRenderAreaCount = physical_device_group[0].physicalDeviceCount + 1;
std::vector<VkRect2D> device_render_areas(dev_grp_rp_info.deviceRenderAreaCount, m_renderPassBeginInfo.renderArea);
dev_grp_rp_info.pDeviceRenderAreas = device_render_areas.data();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceRenderAreaCount-00908");
vk::CmdBeginRenderPass(m_commandBuffer->handle(), &m_renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
m_errorMonitor->VerifyFound();
// Test vk::CmdSetDeviceMask()
vk::CmdSetDeviceMask(m_commandBuffer->handle(), 0x00000001);
dev_grp_rp_info.deviceRenderAreaCount = physical_device_group[0].physicalDeviceCount;
vk::CmdBeginRenderPass(m_commandBuffer->handle(), &m_renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetDeviceMask-deviceMask-00108");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetDeviceMask-deviceMask-00110");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetDeviceMask-deviceMask-00111");
vk::CmdSetDeviceMask(m_commandBuffer->handle(), 0xFFFFFFFF);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetDeviceMask-deviceMask-00109");
vk::CmdSetDeviceMask(m_commandBuffer->handle(), 0);
m_errorMonitor->VerifyFound();
VkSemaphoreCreateInfo semaphore_create_info = {};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkSemaphore semaphore2;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore2));
VkFenceCreateInfo fence_create_info = {};
fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
VkFence fence;
ASSERT_VK_SUCCESS(vk::CreateFence(m_device->device(), &fence_create_info, nullptr, &fence));
if (support_surface) {
// Test VkAcquireNextImageInfoKHR
uint32_t imageIndex;
VkAcquireNextImageInfoKHR acquire_next_image_info = {};
acquire_next_image_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR;
acquire_next_image_info.semaphore = semaphore;
acquire_next_image_info.swapchain = m_swapchain;
acquire_next_image_info.fence = fence;
acquire_next_image_info.deviceMask = 0xFFFFFFFF;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAcquireNextImageInfoKHR-deviceMask-01290");
vk::AcquireNextImage2KHR(m_device->device(), &acquire_next_image_info, &imageIndex);
m_errorMonitor->VerifyFound();
vk::WaitForFences(m_device->device(), 1, &fence, VK_TRUE, std::numeric_limits<int>::max());
vk::ResetFences(m_device->device(), 1, &fence);
acquire_next_image_info.semaphore = semaphore2;
acquire_next_image_info.deviceMask = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAcquireNextImageInfoKHR-deviceMask-01291");
vk::AcquireNextImage2KHR(m_device->device(), &acquire_next_image_info, &imageIndex);
m_errorMonitor->VerifyFound();
DestroySwapchain();
}
// Test VkDeviceGroupSubmitInfo
VkDeviceGroupSubmitInfo device_group_submit_info = {};
device_group_submit_info.sType = VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO;
device_group_submit_info.commandBufferCount = 1;
std::array<uint32_t, 1> command_buffer_device_masks = {{0xFFFFFFFF}};
device_group_submit_info.pCommandBufferDeviceMasks = command_buffer_device_masks.data();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &device_group_submit_info;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
m_commandBuffer->reset();
vk::BeginCommandBuffer(m_commandBuffer->handle(), &cmd_buf_info);
vk::EndCommandBuffer(m_commandBuffer->handle());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceGroupSubmitInfo-pCommandBufferDeviceMasks-00086");
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
vk::WaitForFences(m_device->device(), 1, &fence, VK_TRUE, std::numeric_limits<int>::max());
vk::DestroyFence(m_device->device(), fence, nullptr);
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
vk::DestroySemaphore(m_device->device(), semaphore2, nullptr);
}
TEST_F(VkLayerTest, ValidationCacheTestBadMerge) {
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), kValidationLayerName, VK_EXT_VALIDATION_CACHE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_EXT_VALIDATION_CACHE_EXTENSION_NAME);
} else {
printf("%s %s not supported, skipping test\n", kSkipPrefix, VK_EXT_VALIDATION_CACHE_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
// Load extension functions
auto fpCreateValidationCache =
(PFN_vkCreateValidationCacheEXT)vk::GetDeviceProcAddr(m_device->device(), "vkCreateValidationCacheEXT");
auto fpDestroyValidationCache =
(PFN_vkDestroyValidationCacheEXT)vk::GetDeviceProcAddr(m_device->device(), "vkDestroyValidationCacheEXT");
auto fpMergeValidationCaches =
(PFN_vkMergeValidationCachesEXT)vk::GetDeviceProcAddr(m_device->device(), "vkMergeValidationCachesEXT");
if (!fpCreateValidationCache || !fpDestroyValidationCache || !fpMergeValidationCaches) {
printf("%s Failed to load function pointers for %s\n", kSkipPrefix, VK_EXT_VALIDATION_CACHE_EXTENSION_NAME);
return;
}
VkValidationCacheCreateInfoEXT validationCacheCreateInfo;
validationCacheCreateInfo.sType = VK_STRUCTURE_TYPE_VALIDATION_CACHE_CREATE_INFO_EXT;
validationCacheCreateInfo.pNext = NULL;
validationCacheCreateInfo.initialDataSize = 0;
validationCacheCreateInfo.pInitialData = NULL;
validationCacheCreateInfo.flags = 0;
VkValidationCacheEXT validationCache = VK_NULL_HANDLE;
VkResult res = fpCreateValidationCache(m_device->device(), &validationCacheCreateInfo, nullptr, &validationCache);
ASSERT_VK_SUCCESS(res);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkMergeValidationCachesEXT-dstCache-01536");
res = fpMergeValidationCaches(m_device->device(), validationCache, 1, &validationCache);
m_errorMonitor->VerifyFound();
fpDestroyValidationCache(m_device->device(), validationCache, nullptr);
}
TEST_F(VkLayerTest, InvalidQueueFamilyIndex) {
// Miscellaneous queueFamilyIndex validation tests
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkBufferCreateInfo buffCI = {};
buffCI.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffCI.size = 1024;
buffCI.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buffCI.queueFamilyIndexCount = 2;
// Introduce failure by specifying invalid queue_family_index
uint32_t qfi[2];
qfi[0] = 777;
qfi[1] = 0;
buffCI.pQueueFamilyIndices = qfi;
buffCI.sharingMode = VK_SHARING_MODE_CONCURRENT; // qfi only matters in CONCURRENT mode
// Test for queue family index out of range
CreateBufferTest(*this, &buffCI, "VUID-VkBufferCreateInfo-sharingMode-01419");
// Test for non-unique QFI in array
qfi[0] = 0;
CreateBufferTest(*this, &buffCI, "VUID-VkBufferCreateInfo-sharingMode-01419");
if (m_device->queue_props.size() > 2) {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "which was not created allowing concurrent");
// Create buffer shared to queue families 1 and 2, but submitted on queue family 0
buffCI.queueFamilyIndexCount = 2;
qfi[0] = 1;
qfi[1] = 2;
VkBufferObj ib;
ib.init(*m_device, buffCI);
m_commandBuffer->begin();
vk::CmdFillBuffer(m_commandBuffer->handle(), ib.handle(), 0, 16, 5);
m_commandBuffer->end();
m_commandBuffer->QueueCommandBuffer(false);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, InvalidQueryPoolCreate) {
TEST_DESCRIPTION("Attempt to create a query pool for PIPELINE_STATISTICS without enabling pipeline stats for the device.");
ASSERT_NO_FATAL_FAILURE(Init());
vk_testing::QueueCreateInfoArray queue_info(m_device->queue_props);
VkDevice local_device;
VkDeviceCreateInfo device_create_info = {};
auto features = m_device->phy().features();
// Intentionally disable pipeline stats
features.pipelineStatisticsQuery = VK_FALSE;
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = NULL;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
device_create_info.enabledLayerCount = 0;
device_create_info.ppEnabledLayerNames = NULL;
device_create_info.pEnabledFeatures = &features;
VkResult err = vk::CreateDevice(gpu(), &device_create_info, nullptr, &local_device);
ASSERT_VK_SUCCESS(err);
VkQueryPoolCreateInfo qpci{};
qpci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
qpci.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS;
qpci.queryCount = 1;
VkQueryPool query_pool;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkQueryPoolCreateInfo-queryType-00791");
vk::CreateQueryPool(local_device, &qpci, nullptr, &query_pool);
m_errorMonitor->VerifyFound();
qpci.queryType = VK_QUERY_TYPE_OCCLUSION;
qpci.queryCount = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkQueryPoolCreateInfo-queryCount-02763");
vk::CreateQueryPool(local_device, &qpci, nullptr, &query_pool);
m_errorMonitor->VerifyFound();
vk::DestroyDevice(local_device, nullptr);
}
TEST_F(VkLayerTest, InvalidQuerySizes) {
TEST_DESCRIPTION("Invalid size of using queries commands.");
ASSERT_NO_FATAL_FAILURE(Init());
if (IsPlatform(kPixel2XL)) {
printf("%s This test should not run on Pixel 2 XL\n", kSkipPrefix);
return;
}
uint32_t queue_count;
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_count, NULL);
VkQueueFamilyProperties *queue_props = new VkQueueFamilyProperties[queue_count];
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_count, queue_props);
const uint32_t timestampValidBits = queue_props[m_device->graphics_queue_node_index_].timestampValidBits;
VkBufferObj buffer;
buffer.init(*m_device, 128, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkMemoryRequirements mem_reqs = {};
vk::GetBufferMemoryRequirements(m_device->device(), buffer.handle(), &mem_reqs);
const VkDeviceSize buffer_size = mem_reqs.size;
const uint32_t query_pool_size = 4;
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_OCCLUSION;
query_pool_create_info.queryCount = query_pool_size;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
m_commandBuffer->begin();
// firstQuery is too large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdResetQueryPool-firstQuery-00796");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdResetQueryPool-firstQuery-00797");
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, query_pool_size, 1);
m_errorMonitor->VerifyFound();
// sum of firstQuery and queryCount is too large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdResetQueryPool-firstQuery-00797");
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 1, query_pool_size);
m_errorMonitor->VerifyFound();
// Actually reset all queries so they can be used
m_errorMonitor->ExpectSuccess();
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, query_pool_size);
m_errorMonitor->VerifyNotFound();
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
// query index to large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdEndQuery-query-00810");
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, query_pool_size);
m_errorMonitor->VerifyFound();
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, 0);
// firstQuery is too large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-firstQuery-00820");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-firstQuery-00821");
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, query_pool_size, 1, buffer.handle(), 0, 0, 0);
m_errorMonitor->VerifyFound();
// sum of firstQuery and queryCount is too large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-firstQuery-00821");
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 1, query_pool_size, buffer.handle(), 0, 0, 0);
m_errorMonitor->VerifyFound();
// offset larger than buffer size
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-dstOffset-00819");
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 0, 1, buffer.handle(), buffer_size + 4, 0, 0);
m_errorMonitor->VerifyFound();
// Query is not a timestamp type
if (timestampValidBits == 0) {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdWriteTimestamp-timestampValidBits-00829");
}
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdWriteTimestamp-queryPool-01416");
vk::CmdWriteTimestamp(m_commandBuffer->handle(), VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, query_pool, 0);
m_errorMonitor->VerifyFound();
m_commandBuffer->end();
const size_t out_data_size = 128;
uint8_t data[out_data_size];
// firstQuery is too large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-firstQuery-00813");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-firstQuery-00816");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "UNASSIGNED-CoreValidation-DrawState-InvalidQuery");
vk::GetQueryPoolResults(m_device->device(), query_pool, query_pool_size, 1, out_data_size, &data, 0, 0);
m_errorMonitor->VerifyFound();
// sum of firstQuery and queryCount is too large
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-firstQuery-00816");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "UNASSIGNED-CoreValidation-DrawState-InvalidQuery");
vk::GetQueryPoolResults(m_device->device(), query_pool, 1, query_pool_size, out_data_size, &data, 0, 0);
m_errorMonitor->VerifyFound();
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
}
TEST_F(VkLayerTest, UnclosedAndDuplicateQueries) {
TEST_DESCRIPTION("End a command buffer with a query still in progress, create nested queries.");
ASSERT_NO_FATAL_FAILURE(Init());
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(m_device->device(), m_device->graphics_queue_node_index_, 0, &queue);
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info = {};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_OCCLUSION;
query_pool_create_info.queryCount = 5;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
m_commandBuffer->begin();
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 5);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryPool-01922");
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 1, 0);
// Attempt to begin a query that has the same type as an active query
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 3, 0);
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkEndCommandBuffer-commandBuffer-00061");
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
vk::EndCommandBuffer(m_commandBuffer->handle());
m_errorMonitor->VerifyFound();
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
}
TEST_F(VkLayerTest, QueryPreciseBit) {
TEST_DESCRIPTION("Check for correct Query Precise Bit circumstances.");
ASSERT_NO_FATAL_FAILURE(Init());
// These tests require that the device support pipeline statistics query
VkPhysicalDeviceFeatures device_features = {};
ASSERT_NO_FATAL_FAILURE(GetPhysicalDeviceFeatures(&device_features));
if (VK_TRUE != device_features.pipelineStatisticsQuery) {
printf("%s Test requires unsupported pipelineStatisticsQuery feature. Skipped.\n", kSkipPrefix);
return;
}
std::vector<const char *> device_extension_names;
auto features = m_device->phy().features();
// Test for precise bit when query type is not OCCLUSION
if (features.occlusionQueryPrecise) {
VkEvent event;
VkEventCreateInfo event_create_info{};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->handle(), &event_create_info, nullptr, &event);
m_commandBuffer->begin();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryType-00800");
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info = {};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->handle(), &query_pool_create_info, nullptr, &query_pool);
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, VK_QUERY_CONTROL_PRECISE_BIT);
m_errorMonitor->VerifyFound();
m_commandBuffer->end();
vk::DestroyQueryPool(m_device->handle(), query_pool, nullptr);
vk::DestroyEvent(m_device->handle(), event, nullptr);
}
// Test for precise bit when precise feature is not available
features.occlusionQueryPrecise = false;
VkDeviceObj test_device(0, gpu(), device_extension_names, &features);
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = test_device.graphics_queue_node_index_;
VkCommandPool command_pool;
vk::CreateCommandPool(test_device.handle(), &pool_create_info, nullptr, &command_pool);
VkCommandBufferAllocateInfo cmd = {};
cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmd.pNext = NULL;
cmd.commandPool = command_pool;
cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmd.commandBufferCount = 1;
VkCommandBuffer cmd_buffer;
VkResult err = vk::AllocateCommandBuffers(test_device.handle(), &cmd, &cmd_buffer);
ASSERT_VK_SUCCESS(err);
VkEvent event;
VkEventCreateInfo event_create_info{};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(test_device.handle(), &event_create_info, nullptr, &event);
VkCommandBufferBeginInfo begin_info = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr};
vk::BeginCommandBuffer(cmd_buffer, &begin_info);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryType-00800");
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info = {};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_OCCLUSION;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(test_device.handle(), &query_pool_create_info, nullptr, &query_pool);
vk::CmdResetQueryPool(cmd_buffer, query_pool, 0, 1);
vk::CmdBeginQuery(cmd_buffer, query_pool, 0, VK_QUERY_CONTROL_PRECISE_BIT);
m_errorMonitor->VerifyFound();
vk::EndCommandBuffer(cmd_buffer);
vk::DestroyQueryPool(test_device.handle(), query_pool, nullptr);
vk::DestroyEvent(test_device.handle(), event, nullptr);
vk::DestroyCommandPool(test_device.handle(), command_pool, nullptr);
}
TEST_F(VkLayerTest, StageMaskGsTsEnabled) {
TEST_DESCRIPTION(
"Attempt to use a stageMask w/ geometry shader and tesselation shader bits enabled when those features are disabled on the "
"device.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
std::vector<const char *> device_extension_names;
auto features = m_device->phy().features();
// Make sure gs & ts are disabled
features.geometryShader = false;
features.tessellationShader = false;
// The sacrificial device object
VkDeviceObj test_device(0, gpu(), device_extension_names, &features);
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = test_device.graphics_queue_node_index_;
VkCommandPool command_pool;
vk::CreateCommandPool(test_device.handle(), &pool_create_info, nullptr, &command_pool);
VkCommandBufferAllocateInfo cmd = {};
cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmd.pNext = NULL;
cmd.commandPool = command_pool;
cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmd.commandBufferCount = 1;
VkCommandBuffer cmd_buffer;
VkResult err = vk::AllocateCommandBuffers(test_device.handle(), &cmd, &cmd_buffer);
ASSERT_VK_SUCCESS(err);
VkEvent event;
VkEventCreateInfo evci = {};
evci.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
VkResult result = vk::CreateEvent(test_device.handle(), &evci, NULL, &event);
ASSERT_VK_SUCCESS(result);
VkCommandBufferBeginInfo cbbi = {};
cbbi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vk::BeginCommandBuffer(cmd_buffer, &cbbi);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetEvent-stageMask-04090");
vk::CmdSetEvent(cmd_buffer, event, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetEvent-stageMask-04091");
vk::CmdSetEvent(cmd_buffer, event, VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT);
m_errorMonitor->VerifyFound();
vk::DestroyEvent(test_device.handle(), event, NULL);
vk::DestroyCommandPool(test_device.handle(), command_pool, NULL);
}
TEST_F(VkLayerTest, StageMaskHost) {
TEST_DESCRIPTION("Test invalid usage of VK_PIPELINE_STAGE_HOST_BIT.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkEvent event;
VkEventCreateInfo event_create_info{};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
m_commandBuffer->begin();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetEvent-stageMask-01149");
vk::CmdSetEvent(m_commandBuffer->handle(), event, VK_PIPELINE_STAGE_HOST_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdResetEvent-stageMask-01153");
vk::CmdResetEvent(m_commandBuffer->handle(), event, VK_PIPELINE_STAGE_HOST_BIT);
m_errorMonitor->VerifyFound();
m_commandBuffer->end();
VkSemaphoreCreateInfo semaphore_create_info = {};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkPipelineStageFlags stage_flags = VK_PIPELINE_STAGE_HOST_BIT;
VkSubmitInfo submit_info = {};
// Signal the semaphore so the next test can wait on it.
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &semaphore;
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyNotFound();
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = nullptr;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = &semaphore;
submit_info.pWaitDstStageMask = &stage_flags;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pWaitDstStageMask-00078");
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::DestroyEvent(m_device->device(), event, nullptr);
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
}
TEST_F(VkLayerTest, DescriptorPoolInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete a DescriptorPool with a DescriptorSet that is in use.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
// Create image to update the descriptor with
VkImageObj image(m_device);
image.Init(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_TILING_OPTIMAL, 0);
ASSERT_TRUE(image.initialized());
VkImageView view = image.targetView(VK_FORMAT_B8G8R8A8_UNORM);
// Create Sampler
VkSamplerCreateInfo sampler_ci = SafeSaneSamplerCreateInfo();
VkSampler sampler;
VkResult err = vk::CreateSampler(m_device->device(), &sampler_ci, NULL, &sampler);
ASSERT_VK_SUCCESS(err);
// Create PSO to be used for draw-time errors below
VkShaderObj fs(m_device, bindStateFragSamplerShaderText, VK_SHADER_STAGE_FRAGMENT_BIT, this);
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.shader_stages_ = {pipe.vs_->GetStageCreateInfo(), fs.GetStageCreateInfo()};
pipe.dsl_bindings_ = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, nullptr},
};
const VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dyn_state_ci = {};
dyn_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dyn_state_ci.dynamicStateCount = size(dyn_states);
dyn_state_ci.pDynamicStates = dyn_states;
pipe.dyn_state_ci_ = dyn_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
// Update descriptor with image and sampler
pipe.descriptor_set_->WriteDescriptorImageInfo(0, view, sampler, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
pipe.descriptor_set_->UpdateDescriptorSets();
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,
&pipe.descriptor_set_->set_, 0, NULL);
VkViewport viewport = {0, 0, 16, 16, 0, 1};
VkRect2D scissor = {{0, 0}, {16, 16}};
vk::CmdSetViewport(m_commandBuffer->handle(), 0, 1, &viewport);
vk::CmdSetScissor(m_commandBuffer->handle(), 0, 1, &scissor);
m_commandBuffer->Draw(1, 0, 0, 0);
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
// Submit cmd buffer to put pool in-flight
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
// Destroy pool while in-flight, causing error
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyDescriptorPool-descriptorPool-00303");
vk::DestroyDescriptorPool(m_device->device(), pipe.descriptor_set_->pool_, NULL);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
// Cleanup
vk::DestroySampler(m_device->device(), sampler, NULL);
m_errorMonitor->SetUnexpectedError(
"If descriptorPool is not VK_NULL_HANDLE, descriptorPool must be a valid VkDescriptorPool handle");
m_errorMonitor->SetUnexpectedError("Unable to remove DescriptorPool obj");
// TODO : It seems Validation layers think ds_pool was already destroyed, even though it wasn't?
}
TEST_F(VkLayerTest, FramebufferInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use framebuffer.");
ASSERT_NO_FATAL_FAILURE(Init());
VkFormatProperties format_properties;
VkResult err = VK_SUCCESS;
vk::GetPhysicalDeviceFormatProperties(gpu(), VK_FORMAT_B8G8R8A8_UNORM, &format_properties);
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkImageObj image(m_device);
image.Init(256, 256, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);
ASSERT_TRUE(image.initialized());
VkImageView view = image.targetView(VK_FORMAT_B8G8R8A8_UNORM);
VkFramebufferCreateInfo fci = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, nullptr, 0, m_renderPass, 1, &view, 256, 256, 1};
VkFramebuffer fb;
err = vk::CreateFramebuffer(m_device->device(), &fci, nullptr, &fb);
ASSERT_VK_SUCCESS(err);
// Just use default renderpass with our framebuffer
m_renderPassBeginInfo.framebuffer = fb;
// Create Null cmd buffer for submit
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
// Submit cmd buffer to put it in-flight
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
// Destroy framebuffer while in-flight
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyFramebuffer-framebuffer-00892");
vk::DestroyFramebuffer(m_device->device(), fb, NULL);
m_errorMonitor->VerifyFound();
// Wait for queue to complete so we can safely destroy everything
vk::QueueWaitIdle(m_device->m_queue);
m_errorMonitor->SetUnexpectedError("If framebuffer is not VK_NULL_HANDLE, framebuffer must be a valid VkFramebuffer handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Framebuffer obj");
vk::DestroyFramebuffer(m_device->device(), fb, nullptr);
}
TEST_F(VkLayerTest, FramebufferImageInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use image that's child of framebuffer.");
ASSERT_NO_FATAL_FAILURE(Init());
VkFormatProperties format_properties;
VkResult err = VK_SUCCESS;
vk::GetPhysicalDeviceFormatProperties(gpu(), VK_FORMAT_B8G8R8A8_UNORM, &format_properties);
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkImageCreateInfo image_ci = {};
image_ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_ci.pNext = NULL;
image_ci.imageType = VK_IMAGE_TYPE_2D;
image_ci.format = VK_FORMAT_B8G8R8A8_UNORM;
image_ci.extent.width = 256;
image_ci.extent.height = 256;
image_ci.extent.depth = 1;
image_ci.mipLevels = 1;
image_ci.arrayLayers = 1;
image_ci.samples = VK_SAMPLE_COUNT_1_BIT;
image_ci.tiling = VK_IMAGE_TILING_OPTIMAL;
image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
image_ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_ci.flags = 0;
VkImageObj image(m_device);
image.init(&image_ci);
VkImageView view = image.targetView(VK_FORMAT_B8G8R8A8_UNORM);
VkFramebufferCreateInfo fci = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, nullptr, 0, m_renderPass, 1, &view, 256, 256, 1};
VkFramebuffer fb;
err = vk::CreateFramebuffer(m_device->device(), &fci, nullptr, &fb);
ASSERT_VK_SUCCESS(err);
// Just use default renderpass with our framebuffer
m_renderPassBeginInfo.framebuffer = fb;
// Create Null cmd buffer for submit
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
// Submit cmd buffer to put it (and attached imageView) in-flight
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
// Submit cmd buffer to put framebuffer and children in-flight
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
// Destroy image attached to framebuffer while in-flight
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyImage-image-01000");
vk::DestroyImage(m_device->device(), image.handle(), NULL);
m_errorMonitor->VerifyFound();
// Wait for queue to complete so we can safely destroy image and other objects
vk::QueueWaitIdle(m_device->m_queue);
m_errorMonitor->SetUnexpectedError("If image is not VK_NULL_HANDLE, image must be a valid VkImage handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Image obj");
vk::DestroyFramebuffer(m_device->device(), fb, nullptr);
}
TEST_F(VkLayerTest, EventInUseDestroyedSignaled) {
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_commandBuffer->begin();
VkEvent event;
VkEventCreateInfo event_create_info = {};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
vk::CmdSetEvent(m_commandBuffer->handle(), event, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
m_commandBuffer->end();
vk::DestroyEvent(m_device->device(), event, nullptr);
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "that is invalid because bound");
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, InUseDestroyedSignaled) {
TEST_DESCRIPTION(
"Use vkCmdExecuteCommands with invalid state in primary and secondary command buffers. Delete objects that are in use. "
"Call VkQueueSubmit with an event that has been deleted.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_errorMonitor->ExpectSuccess();
VkSemaphoreCreateInfo semaphore_create_info = {};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkFenceCreateInfo fence_create_info = {};
fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
VkFence fence;
ASSERT_VK_SUCCESS(vk::CreateFence(m_device->device(), &fence_create_info, nullptr, &fence));
VkBufferTest buffer_test(m_device, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.InitState();
pipe.CreateGraphicsPipeline();
pipe.descriptor_set_->WriteDescriptorBufferInfo(0, buffer_test.GetBuffer(), 1024, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
pipe.descriptor_set_->UpdateDescriptorSets();
VkEvent event;
VkEventCreateInfo event_create_info = {};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
m_commandBuffer->begin();
vk::CmdSetEvent(m_commandBuffer->handle(), event, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,
&pipe.descriptor_set_->set_, 0, NULL);
m_commandBuffer->end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &semaphore;
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, fence);
m_errorMonitor->Reset(); // resume logmsg processing
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyEvent-event-01145");
vk::DestroyEvent(m_device->device(), event, nullptr);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroySemaphore-semaphore-01137");
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyFence-fence-01120");
vk::DestroyFence(m_device->device(), fence, nullptr);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
m_errorMonitor->SetUnexpectedError("If semaphore is not VK_NULL_HANDLE, semaphore must be a valid VkSemaphore handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Semaphore obj");
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
m_errorMonitor->SetUnexpectedError("If fence is not VK_NULL_HANDLE, fence must be a valid VkFence handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Fence obj");
vk::DestroyFence(m_device->device(), fence, nullptr);
m_errorMonitor->SetUnexpectedError("If event is not VK_NULL_HANDLE, event must be a valid VkEvent handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Event obj");
vk::DestroyEvent(m_device->device(), event, nullptr);
}
TEST_F(VkLayerTest, EventStageMaskOneCommandBufferPass) {
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkCommandBufferObj commandBuffer1(m_device, m_commandPool);
VkCommandBufferObj commandBuffer2(m_device, m_commandPool);
VkEvent event;
VkEventCreateInfo event_create_info = {};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
commandBuffer1.begin();
vk::CmdSetEvent(commandBuffer1.handle(), event, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
vk::CmdWaitEvents(commandBuffer1.handle(), 1, &event, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, nullptr, 0, nullptr, 0, nullptr);
commandBuffer1.end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &commandBuffer1.handle();
m_errorMonitor->ExpectSuccess();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyNotFound();
vk::QueueWaitIdle(m_device->m_queue);
vk::DestroyEvent(m_device->device(), event, nullptr);
}
TEST_F(VkLayerTest, EventStageMaskOneCommandBufferFail) {
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkCommandBufferObj commandBuffer1(m_device, m_commandPool);
VkCommandBufferObj commandBuffer2(m_device, m_commandPool);
VkEvent event;
VkEventCreateInfo event_create_info = {};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
commandBuffer1.begin();
vk::CmdSetEvent(commandBuffer1.handle(), event, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
// wrong srcStageMask
vk::CmdWaitEvents(commandBuffer1.handle(), 1, &event, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, nullptr, 0, nullptr, 0, nullptr);
commandBuffer1.end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &commandBuffer1.handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdWaitEvents-srcStageMask-parameter");
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
vk::DestroyEvent(m_device->device(), event, nullptr);
}
TEST_F(VkLayerTest, EventStageMaskTwoCommandBufferPass) {
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkCommandBufferObj commandBuffer1(m_device, m_commandPool);
VkCommandBufferObj commandBuffer2(m_device, m_commandPool);
VkEvent event;
VkEventCreateInfo event_create_info = {};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
commandBuffer1.begin();
vk::CmdSetEvent(commandBuffer1.handle(), event, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
commandBuffer1.end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &commandBuffer1.handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
commandBuffer2.begin();
vk::CmdWaitEvents(commandBuffer2.handle(), 1, &event, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, nullptr, 0, nullptr, 0, nullptr);
commandBuffer2.end();
submit_info.pCommandBuffers = &commandBuffer2.handle();
m_errorMonitor->ExpectSuccess();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyNotFound();
vk::QueueWaitIdle(m_device->m_queue);
vk::DestroyEvent(m_device->device(), event, nullptr);
}
TEST_F(VkLayerTest, EventStageMaskTwoCommandBufferFail) {
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkCommandBufferObj commandBuffer1(m_device, m_commandPool);
VkCommandBufferObj commandBuffer2(m_device, m_commandPool);
VkEvent event;
VkEventCreateInfo event_create_info = {};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
commandBuffer1.begin();
vk::CmdSetEvent(commandBuffer1.handle(), event, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
commandBuffer1.end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &commandBuffer1.handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
commandBuffer2.begin();
// wrong srcStageMask
vk::CmdWaitEvents(commandBuffer2.handle(), 1, &event, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, nullptr, 0, nullptr, 0, nullptr);
commandBuffer2.end();
submit_info.pCommandBuffers = &commandBuffer2.handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdWaitEvents-srcStageMask-parameter");
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
vk::DestroyEvent(m_device->device(), event, nullptr);
}
TEST_F(VkLayerTest, QueryPoolPartialTimestamp) {
TEST_DESCRIPTION("Request partial result on timestamp query.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
uint32_t queue_count;
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_count, NULL);
VkQueueFamilyProperties *queue_props = new VkQueueFamilyProperties[queue_count];
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_count, queue_props);
if (queue_props[m_device->graphics_queue_node_index_].timestampValidBits == 0) {
printf("%s Device graphic queue has timestampValidBits of 0, skipping.\n", kSkipPrefix);
return;
}
VkBufferObj buffer;
buffer.init(*m_device, 128, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_ci.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_ci, nullptr, &query_pool);
// Use setup as a positive test...
m_errorMonitor->ExpectSuccess();
m_commandBuffer->begin();
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
vk::CmdWriteTimestamp(m_commandBuffer->handle(), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, query_pool, 0);
m_errorMonitor->VerifyNotFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-queryType-00827");
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 0, 1, buffer.handle(), 0, 8, VK_QUERY_RESULT_PARTIAL_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->ExpectSuccess();
m_commandBuffer->end();
// Submit cmd buffer and wait for it.
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(m_device->m_queue);
m_errorMonitor->VerifyNotFound();
// Attempt to obtain partial results.
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-queryType-00818");
uint32_t data_space[16];
m_errorMonitor->SetUnexpectedError("Cannot get query results on queryPool");
vk::GetQueryPoolResults(m_device->handle(), query_pool, 0, 1, sizeof(data_space), &data_space, sizeof(uint32_t),
VK_QUERY_RESULT_PARTIAL_BIT);
m_errorMonitor->VerifyFound();
// Destroy query pool.
vk::DestroyQueryPool(m_device->handle(), query_pool, NULL);
}
TEST_F(VkLayerTest, QueryPoolInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use query pool.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_ci.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_ci, nullptr, &query_pool);
m_commandBuffer->begin();
// Use query pool to create binding with cmd buffer
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
vk::CmdWriteTimestamp(m_commandBuffer->handle(), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, query_pool, 0);
m_commandBuffer->end();
// Submit cmd buffer and then destroy query pool while in-flight
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyQueryPool-queryPool-00793");
vk::DestroyQueryPool(m_device->handle(), query_pool, NULL);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
// Now that cmd buffer done we can safely destroy query_pool
m_errorMonitor->SetUnexpectedError("If queryPool is not VK_NULL_HANDLE, queryPool must be a valid VkQueryPool handle");
m_errorMonitor->SetUnexpectedError("Unable to remove QueryPool obj");
vk::DestroyQueryPool(m_device->handle(), query_pool, NULL);
}
TEST_F(VkLayerTest, PipelineInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use pipeline.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
const VkPipelineLayoutObj pipeline_layout(m_device);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyPipeline-pipeline-00765");
// Create PSO to be used for draw-time errors below
// Store pipeline handle so we can actually delete it before test finishes
VkPipeline delete_this_pipeline;
{ // Scope pipeline so it will be auto-deleted
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.InitState();
pipe.CreateGraphicsPipeline();
delete_this_pipeline = pipe.pipeline_;
m_commandBuffer->begin();
// Bind pipeline to cmd buffer
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
m_commandBuffer->end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
// Submit cmd buffer and then pipeline destroyed while in-flight
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
} // Pipeline deletion triggered here
m_errorMonitor->VerifyFound();
// Make sure queue finished and then actually delete pipeline
vk::QueueWaitIdle(m_device->m_queue);
m_errorMonitor->SetUnexpectedError("If pipeline is not VK_NULL_HANDLE, pipeline must be a valid VkPipeline handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Pipeline obj");
vk::DestroyPipeline(m_device->handle(), delete_this_pipeline, nullptr);
}
TEST_F(VkLayerTest, ImageViewInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use imageView.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkSamplerCreateInfo sampler_ci = SafeSaneSamplerCreateInfo();
VkSampler sampler;
VkResult err;
err = vk::CreateSampler(m_device->device(), &sampler_ci, NULL, &sampler);
ASSERT_VK_SUCCESS(err);
VkImageObj image(m_device);
image.Init(128, 128, 1, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_TILING_OPTIMAL, 0);
ASSERT_TRUE(image.initialized());
VkImageView view = image.targetView(VK_FORMAT_R8G8B8A8_UNORM);
// Create PSO to use the sampler
VkShaderObj fs(m_device, bindStateFragSamplerShaderText, VK_SHADER_STAGE_FRAGMENT_BIT, this);
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.shader_stages_ = {pipe.vs_->GetStageCreateInfo(), fs.GetStageCreateInfo()};
pipe.dsl_bindings_ = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, nullptr},
};
const VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dyn_state_ci = {};
dyn_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dyn_state_ci.dynamicStateCount = size(dyn_states);
dyn_state_ci.pDynamicStates = dyn_states;
pipe.dyn_state_ci_ = dyn_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
pipe.descriptor_set_->WriteDescriptorImageInfo(0, view, sampler, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
pipe.descriptor_set_->UpdateDescriptorSets();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyImageView-imageView-01026");
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
// Bind pipeline to cmd buffer
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,
&pipe.descriptor_set_->set_, 0, nullptr);
VkViewport viewport = {0, 0, 16, 16, 0, 1};
VkRect2D scissor = {{0, 0}, {16, 16}};
vk::CmdSetViewport(m_commandBuffer->handle(), 0, 1, &viewport);
vk::CmdSetScissor(m_commandBuffer->handle(), 0, 1, &scissor);
m_commandBuffer->Draw(1, 0, 0, 0);
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
// Submit cmd buffer then destroy sampler
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
// Submit cmd buffer and then destroy imageView while in-flight
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::DestroyImageView(m_device->device(), view, nullptr);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
// Now we can actually destroy imageView
m_errorMonitor->SetUnexpectedError("If imageView is not VK_NULL_HANDLE, imageView must be a valid VkImageView handle");
m_errorMonitor->SetUnexpectedError("Unable to remove ImageView obj");
vk::DestroySampler(m_device->device(), sampler, nullptr);
}
TEST_F(VkLayerTest, BufferViewInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use bufferView.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
uint32_t queue_family_index = 0;
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.size = 1024;
buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
buffer_create_info.queueFamilyIndexCount = 1;
buffer_create_info.pQueueFamilyIndices = &queue_family_index;
VkBufferObj buffer;
buffer.init(*m_device, buffer_create_info);
VkBufferView view;
VkBufferViewCreateInfo bvci = {};
bvci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
bvci.buffer = buffer.handle();
bvci.format = VK_FORMAT_R32_SFLOAT;
bvci.range = VK_WHOLE_SIZE;
VkResult err = vk::CreateBufferView(m_device->device(), &bvci, NULL, &view);
ASSERT_VK_SUCCESS(err);
char const *fsSource =
"#version 450\n"
"\n"
"layout(set=0, binding=0, r32f) uniform readonly imageBuffer s;\n"
"layout(location=0) out vec4 x;\n"
"void main(){\n"
" x = imageLoad(s, 0);\n"
"}\n";
VkShaderObj fs(m_device, fsSource, VK_SHADER_STAGE_FRAGMENT_BIT, this);
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.shader_stages_ = {pipe.vs_->GetStageCreateInfo(), fs.GetStageCreateInfo()};
pipe.dsl_bindings_ = {
{0, VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1, VK_SHADER_STAGE_ALL, nullptr},
};
const VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dyn_state_ci = {};
dyn_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dyn_state_ci.dynamicStateCount = size(dyn_states);
dyn_state_ci.pDynamicStates = dyn_states;
pipe.dyn_state_ci_ = dyn_state_ci;
pipe.InitState();
err = pipe.CreateGraphicsPipeline();
if (err != VK_SUCCESS) {
printf("%s Unable to compile shader, skipping.\n", kSkipPrefix);
return;
}
pipe.descriptor_set_->WriteDescriptorBufferView(0, view, VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
pipe.descriptor_set_->UpdateDescriptorSets();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroyBufferView-bufferView-00936");
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
VkViewport viewport = {0, 0, 16, 16, 0, 1};
vk::CmdSetViewport(m_commandBuffer->handle(), 0, 1, &viewport);
VkRect2D scissor = {{0, 0}, {16, 16}};
vk::CmdSetScissor(m_commandBuffer->handle(), 0, 1, &scissor);
// Bind pipeline to cmd buffer
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,
&pipe.descriptor_set_->set_, 0, nullptr);
m_commandBuffer->Draw(1, 0, 0, 0);
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
// Submit cmd buffer and then destroy bufferView while in-flight
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::DestroyBufferView(m_device->device(), view, nullptr);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
// Now we can actually destroy bufferView
m_errorMonitor->SetUnexpectedError("If bufferView is not VK_NULL_HANDLE, bufferView must be a valid VkBufferView handle");
m_errorMonitor->SetUnexpectedError("Unable to remove BufferView obj");
vk::DestroyBufferView(m_device->device(), view, NULL);
}
TEST_F(VkLayerTest, SamplerInUseDestroyedSignaled) {
TEST_DESCRIPTION("Delete in-use sampler.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkSamplerCreateInfo sampler_ci = SafeSaneSamplerCreateInfo();
VkSampler sampler;
VkResult err;
err = vk::CreateSampler(m_device->device(), &sampler_ci, NULL, &sampler);
ASSERT_VK_SUCCESS(err);
VkImageObj image(m_device);
image.Init(128, 128, 1, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_TILING_OPTIMAL, 0);
ASSERT_TRUE(image.initialized());
VkImageView view = image.targetView(VK_FORMAT_R8G8B8A8_UNORM);
// Create PSO to use the sampler
VkShaderObj fs(m_device, bindStateFragSamplerShaderText, VK_SHADER_STAGE_FRAGMENT_BIT, this);
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.shader_stages_ = {pipe.vs_->GetStageCreateInfo(), fs.GetStageCreateInfo()};
pipe.dsl_bindings_ = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, nullptr},
};
const VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dyn_state_ci = {};
dyn_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dyn_state_ci.dynamicStateCount = size(dyn_states);
dyn_state_ci.pDynamicStates = dyn_states;
pipe.dyn_state_ci_ = dyn_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
pipe.descriptor_set_->WriteDescriptorImageInfo(0, view, sampler, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
pipe.descriptor_set_->UpdateDescriptorSets();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkDestroySampler-sampler-01082");
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
// Bind pipeline to cmd buffer
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,
&pipe.descriptor_set_->set_, 0, nullptr);
VkViewport viewport = {0, 0, 16, 16, 0, 1};
VkRect2D scissor = {{0, 0}, {16, 16}};
vk::CmdSetViewport(m_commandBuffer->handle(), 0, 1, &viewport);
vk::CmdSetScissor(m_commandBuffer->handle(), 0, 1, &scissor);
m_commandBuffer->Draw(1, 0, 0, 0);
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
// Submit cmd buffer then destroy sampler
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
// Submit cmd buffer and then destroy sampler while in-flight
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::DestroySampler(m_device->device(), sampler, nullptr); // Destroyed too soon
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(m_device->m_queue);
// Now we can actually destroy sampler
m_errorMonitor->SetUnexpectedError("If sampler is not VK_NULL_HANDLE, sampler must be a valid VkSampler handle");
m_errorMonitor->SetUnexpectedError("Unable to remove Sampler obj");
vk::DestroySampler(m_device->device(), sampler, NULL); // Destroyed for real
}
TEST_F(VkLayerTest, QueueForwardProgressFenceWait) {
TEST_DESCRIPTION("Call VkQueueSubmit with a semaphore that is already signaled but not waited on by the queue.");
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
const char *queue_forward_progress_message = "UNASSIGNED-CoreValidation-DrawState-QueueForwardProgress";
VkCommandBufferObj cb1(m_device, m_commandPool);
cb1.begin();
cb1.end();
VkSemaphoreCreateInfo semaphore_create_info = {};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &cb1.handle();
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &semaphore;
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_commandBuffer->begin();
m_commandBuffer->end();
submit_info.pCommandBuffers = &m_commandBuffer->handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, queue_forward_progress_message);
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::DeviceWaitIdle(m_device->device());
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
}
#if GTEST_IS_THREADSAFE
TEST_F(VkLayerTest, ThreadCommandBufferCollision) {
test_platform_thread thread;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "THREADING ERROR");
m_errorMonitor->SetAllowedFailureMsg("THREADING ERROR"); // Ignore any extra threading errors found beyond the first one
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
// Calls AllocateCommandBuffers
VkCommandBufferObj commandBuffer(m_device, m_commandPool);
commandBuffer.begin();
VkEventCreateInfo event_info;
VkEvent event;
VkResult err;
memset(&event_info, 0, sizeof(event_info));
event_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
err = vk::CreateEvent(device(), &event_info, NULL, &event);
ASSERT_VK_SUCCESS(err);
err = vk::ResetEvent(device(), event);
ASSERT_VK_SUCCESS(err);
struct thread_data_struct data;
data.commandBuffer = commandBuffer.handle();
data.event = event;
bool bailout = false;
data.bailout = &bailout;
m_errorMonitor->SetBailout(data.bailout);
// First do some correct operations using multiple threads.
// Add many entries to command buffer from another thread.
test_platform_thread_create(&thread, AddToCommandBuffer, (void *)&data);
// Make non-conflicting calls from this thread at the same time.
for (int i = 0; i < 80000; i++) {
uint32_t count;
vk::EnumeratePhysicalDevices(instance(), &count, NULL);
}
test_platform_thread_join(thread, NULL);
// Then do some incorrect operations using multiple threads.
// Add many entries to command buffer from another thread.
test_platform_thread_create(&thread, AddToCommandBuffer, (void *)&data);
// Add many entries to command buffer from this thread at the same time.
AddToCommandBuffer(&data);
test_platform_thread_join(thread, NULL);
commandBuffer.end();
m_errorMonitor->SetBailout(NULL);
m_errorMonitor->VerifyFound();
vk::DestroyEvent(device(), event, NULL);
}
TEST_F(VkLayerTest, ThreadUpdateDescriptorCollision) {
TEST_DESCRIPTION("Two threads updating the same descriptor set, expected to generate a threading error");
test_platform_thread thread;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "THREADING ERROR : vkUpdateDescriptorSets");
m_errorMonitor->SetAllowedFailureMsg("THREADING ERROR"); // Ignore any extra threading errors found beyond the first one
ASSERT_NO_FATAL_FAILURE(Init());
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
OneOffDescriptorSet normal_descriptor_set(m_device,
{
{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr},
},
0);
VkBufferObj buffer;
buffer.init(*m_device, 256, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
struct thread_data_struct data;
data.device = device();
data.descriptorSet = normal_descriptor_set.set_;
data.binding = 0;
data.buffer = buffer.handle();
bool bailout = false;
data.bailout = &bailout;
m_errorMonitor->SetBailout(data.bailout);
// Update descriptors from another thread.
test_platform_thread_create(&thread, UpdateDescriptor, (void *)&data);
// Update descriptors from this thread at the same time.
struct thread_data_struct data2;
data2.device = device();
data2.descriptorSet = normal_descriptor_set.set_;
data2.binding = 1;
data2.buffer = buffer.handle();
data2.bailout = &bailout;
UpdateDescriptor(&data2);
test_platform_thread_join(thread, NULL);
m_errorMonitor->SetBailout(NULL);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, ThreadUpdateDescriptorUpdateAfterBindNoCollision) {
TEST_DESCRIPTION("Two threads updating the same UAB descriptor set, expected not to generate a threading error");
test_platform_thread thread;
m_errorMonitor->ExpectSuccess();
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) &&
DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE3_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE3_EXTENSION_NAME);
} else {
printf("%s Descriptor Indexing or Maintenance3 Extension not supported, skipping tests\n", kSkipPrefix);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
// Create a device that enables descriptorBindingStorageBufferUpdateAfterBind
auto indexing_features = lvl_init_struct<VkPhysicalDeviceDescriptorIndexingFeaturesEXT>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&indexing_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (VK_FALSE == indexing_features.descriptorBindingStorageBufferUpdateAfterBind) {
printf("%s Test requires (unsupported) descriptorBindingStorageBufferUpdateAfterBind, skipping\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
std::array<VkDescriptorBindingFlagsEXT, 2> flags = {
{VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT, VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT}};
auto flags_create_info = lvl_init_struct<VkDescriptorSetLayoutBindingFlagsCreateInfoEXT>();
flags_create_info.bindingCount = (uint32_t)flags.size();
flags_create_info.pBindingFlags = flags.data();
OneOffDescriptorSet normal_descriptor_set(m_device,
{
{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr},
},
VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT, &flags_create_info,
VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT);
VkBufferObj buffer;
buffer.init(*m_device, 256, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
struct thread_data_struct data;
data.device = device();
data.descriptorSet = normal_descriptor_set.set_;
data.binding = 0;
data.buffer = buffer.handle();
bool bailout = false;
data.bailout = &bailout;
m_errorMonitor->SetBailout(data.bailout);
// Update descriptors from another thread.
test_platform_thread_create(&thread, UpdateDescriptor, (void *)&data);
// Update descriptors from this thread at the same time.
struct thread_data_struct data2;
data2.device = device();
data2.descriptorSet = normal_descriptor_set.set_;
data2.binding = 1;
data2.buffer = buffer.handle();
data2.bailout = &bailout;
UpdateDescriptor(&data2);
test_platform_thread_join(thread, NULL);
m_errorMonitor->SetBailout(NULL);
m_errorMonitor->VerifyNotFound();
}
#endif // GTEST_IS_THREADSAFE
TEST_F(VkLayerTest, ExecuteUnrecordedPrimaryCB) {
TEST_DESCRIPTION("Attempt vkQueueSubmit with a CB in the initial state");
ASSERT_NO_FATAL_FAILURE(Init());
// never record m_commandBuffer
VkSubmitInfo si = {};
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
si.commandBufferCount = 1;
si.pCommandBuffers = &m_commandBuffer->handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkQueueSubmit-pCommandBuffers-00072");
vk::QueueSubmit(m_device->m_queue, 1, &si, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, Maintenance1AndNegativeViewport) {
TEST_DESCRIPTION("Attempt to enable AMD_negative_viewport_height and Maintenance1_KHR extension simultaneously");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!((DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME)) &&
(DeviceExtensionSupported(gpu(), nullptr, VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME)))) {
printf("%s Maintenance1 and AMD_negative viewport height extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
vk_testing::QueueCreateInfoArray queue_info(m_device->queue_props);
const char *extension_names[2] = {"VK_KHR_maintenance1", "VK_AMD_negative_viewport_height"};
VkDevice testDevice;
VkDeviceCreateInfo device_create_info = {};
auto features = m_device->phy().features();
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = NULL;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
device_create_info.enabledLayerCount = 0;
device_create_info.ppEnabledLayerNames = NULL;
device_create_info.enabledExtensionCount = 2;
device_create_info.ppEnabledExtensionNames = (const char *const *)extension_names;
device_create_info.pEnabledFeatures = &features;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceCreateInfo-ppEnabledExtensionNames-00374");
// The following unexpected error is coming from the LunarG loader. Do not make it a desired message because platforms that do
// not use the LunarG loader (e.g. Android) will not see the message and the test will fail.
m_errorMonitor->SetUnexpectedError("Failed to create device chain.");
vk::CreateDevice(gpu(), &device_create_info, NULL, &testDevice);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, HostQueryResetNotEnabled) {
TEST_DESCRIPTION("Use vkResetQueryPoolEXT without enabling the feature");
if (!InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
ASSERT_NO_FATAL_FAILURE(InitState());
auto fpvkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)vk::GetDeviceProcAddr(m_device->device(), "vkResetQueryPoolEXT");
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkResetQueryPool-None-02665");
fpvkResetQueryPoolEXT(m_device->device(), query_pool, 0, 1);
m_errorMonitor->VerifyFound();
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
}
TEST_F(VkLayerTest, HostQueryResetBadFirstQuery) {
TEST_DESCRIPTION("Bad firstQuery in vkResetQueryPoolEXT");
if (!InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
SetTargetApiVersion(VK_API_VERSION_1_2);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
VkPhysicalDeviceHostQueryResetFeaturesEXT host_query_reset_features{};
host_query_reset_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT;
host_query_reset_features.hostQueryReset = VK_TRUE;
VkPhysicalDeviceFeatures2 pd_features2{};
pd_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
pd_features2.pNext = &host_query_reset_features;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &pd_features2));
auto fpvkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)vk::GetDeviceProcAddr(m_device->device(), "vkResetQueryPoolEXT");
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkResetQueryPool-firstQuery-02666");
fpvkResetQueryPoolEXT(m_device->device(), query_pool, 1, 0);
m_errorMonitor->VerifyFound();
if (DeviceValidationVersion() >= VK_API_VERSION_1_2) {
auto fpvkResetQueryPool = (PFN_vkResetQueryPool)vk::GetDeviceProcAddr(m_device->device(), "vkResetQueryPool");
if (nullptr == fpvkResetQueryPool) {
m_errorMonitor->ExpectSuccess();
m_errorMonitor->SetError("No ProcAddr for 1.2 core vkResetQueryPool");
m_errorMonitor->VerifyNotFound();
} else {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkResetQueryPool-firstQuery-02666");
fpvkResetQueryPool(m_device->device(), query_pool, 1, 0);
m_errorMonitor->VerifyFound();
}
}
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
}
TEST_F(VkLayerTest, HostQueryResetBadRange) {
TEST_DESCRIPTION("Bad range in vkResetQueryPoolEXT");
if (!InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
VkPhysicalDeviceHostQueryResetFeaturesEXT host_query_reset_features{};
host_query_reset_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT;
host_query_reset_features.hostQueryReset = VK_TRUE;
VkPhysicalDeviceFeatures2 pd_features2{};
pd_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
pd_features2.pNext = &host_query_reset_features;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &pd_features2));
auto fpvkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)vk::GetDeviceProcAddr(m_device->device(), "vkResetQueryPoolEXT");
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkResetQueryPool-firstQuery-02667");
fpvkResetQueryPoolEXT(m_device->device(), query_pool, 0, 2);
m_errorMonitor->VerifyFound();
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
}
TEST_F(VkLayerTest, HostQueryResetInvalidQueryPool) {
TEST_DESCRIPTION("Invalid queryPool in vkResetQueryPoolEXT");
if (!InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
VkPhysicalDeviceHostQueryResetFeaturesEXT host_query_reset_features{};
host_query_reset_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT;
host_query_reset_features.hostQueryReset = VK_TRUE;
VkPhysicalDeviceFeatures2 pd_features2{};
pd_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
pd_features2.pNext = &host_query_reset_features;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &pd_features2));
auto fpvkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)vk::GetDeviceProcAddr(m_device->device(), "vkResetQueryPoolEXT");
// Create and destroy a query pool.
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
// Attempt to reuse the query pool handle.
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkResetQueryPool-queryPool-parameter");
fpvkResetQueryPoolEXT(m_device->device(), query_pool, 0, 1);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, HostQueryResetWrongDevice) {
TEST_DESCRIPTION("Device not matching queryPool in vkResetQueryPoolEXT");
if (!InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
VkPhysicalDeviceHostQueryResetFeaturesEXT host_query_reset_features{};
host_query_reset_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT;
host_query_reset_features.hostQueryReset = VK_TRUE;
VkPhysicalDeviceFeatures2 pd_features2{};
pd_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
pd_features2.pNext = &host_query_reset_features;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &pd_features2));
auto fpvkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)vk::GetDeviceProcAddr(m_device->device(), "vkResetQueryPoolEXT");
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_create_info{};
query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_create_info.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_create_info, nullptr, &query_pool);
// Create a second device with the feature enabled.
vk_testing::QueueCreateInfoArray queue_info(m_device->queue_props);
auto features = m_device->phy().features();
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &host_query_reset_features;
device_create_info.queueCreateInfoCount = queue_info.size();
device_create_info.pQueueCreateInfos = queue_info.data();
device_create_info.pEnabledFeatures = &features;
device_create_info.enabledExtensionCount = m_device_extension_names.size();
device_create_info.ppEnabledExtensionNames = m_device_extension_names.data();
VkDevice second_device;
ASSERT_VK_SUCCESS(vk::CreateDevice(gpu(), &device_create_info, nullptr, &second_device));
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkResetQueryPool-queryPool-parent");
// Run vk::ResetQueryPoolExt on the wrong device.
fpvkResetQueryPoolEXT(second_device, query_pool, 0, 1);
m_errorMonitor->VerifyFound();
vk::DestroyQueryPool(m_device->device(), query_pool, nullptr);
vk::DestroyDevice(second_device, nullptr);
}
TEST_F(VkLayerTest, ResetEventThenSet) {
TEST_DESCRIPTION("Reset an event then set it after the reset has been submitted.");
ASSERT_NO_FATAL_FAILURE(Init());
VkEvent event;
VkEventCreateInfo event_create_info{};
event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);
VkCommandPool command_pool;
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = m_device->graphics_queue_node_index_;
pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vk::CreateCommandPool(m_device->device(), &pool_create_info, nullptr, &command_pool);
VkCommandBuffer command_buffer;
VkCommandBufferAllocateInfo command_buffer_allocate_info{};
command_buffer_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_allocate_info.commandPool = command_pool;
command_buffer_allocate_info.commandBufferCount = 1;
command_buffer_allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
vk::AllocateCommandBuffers(m_device->device(), &command_buffer_allocate_info, &command_buffer);
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(m_device->device(), m_device->graphics_queue_node_index_, 0, &queue);
{
VkCommandBufferBeginInfo begin_info{};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vk::BeginCommandBuffer(command_buffer, &begin_info);
vk::CmdResetEvent(command_buffer, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
vk::EndCommandBuffer(command_buffer);
}
{
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command_buffer;
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = nullptr;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
}
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "that is already in use by a command buffer.");
vk::SetEvent(m_device->device(), event);
m_errorMonitor->VerifyFound();
}
vk::QueueWaitIdle(queue);
vk::DestroyEvent(m_device->device(), event, nullptr);
vk::FreeCommandBuffers(m_device->device(), command_pool, 1, &command_buffer);
vk::DestroyCommandPool(m_device->device(), command_pool, NULL);
}
TEST_F(VkLayerTest, ShadingRateImageNV) {
TEST_DESCRIPTION("Test VK_NV_shading_rate_image.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
std::array<const char *, 1> required_device_extensions = {{VK_NV_SHADING_RATE_IMAGE_EXTENSION_NAME}};
for (auto device_extension : required_device_extensions) {
if (DeviceExtensionSupported(gpu(), nullptr, device_extension)) {
m_device_extension_names.push_back(device_extension);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix, device_extension);
return;
}
}
if (IsPlatform(kMockICD) || DeviceSimulation()) {
printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
// Create a device that enables shading_rate_image but disables multiViewport
auto shading_rate_image_features = lvl_init_struct<VkPhysicalDeviceShadingRateImageFeaturesNV>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&shading_rate_image_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
features2.features.multiViewport = VK_FALSE;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2));
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
// Test shading rate image creation
VkResult result = VK_RESULT_MAX_ENUM;
VkImageCreateInfo image_create_info = {};
image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_create_info.pNext = NULL;
image_create_info.imageType = VK_IMAGE_TYPE_2D;
image_create_info.format = VK_FORMAT_R8_UINT;
image_create_info.extent.width = 4;
image_create_info.extent.height = 4;
image_create_info.extent.depth = 1;
image_create_info.mipLevels = 1;
image_create_info.arrayLayers = 1;
image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV;
image_create_info.queueFamilyIndexCount = 0;
image_create_info.pQueueFamilyIndices = NULL;
image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_create_info.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
// image type must be 2D
image_create_info.imageType = VK_IMAGE_TYPE_3D;
CreateImageTest(*this, &image_create_info, "VUID-VkImageCreateInfo-imageType-02082");
image_create_info.imageType = VK_IMAGE_TYPE_2D;
image_create_info.arrayLayers = 6;
// must be single sample
image_create_info.samples = VK_SAMPLE_COUNT_2_BIT;
CreateImageTest(*this, &image_create_info, "VUID-VkImageCreateInfo-samples-02083");
image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;
// tiling must be optimal
image_create_info.tiling = VK_IMAGE_TILING_LINEAR;
CreateImageTest(*this, &image_create_info, "VUID-VkImageCreateInfo-tiling-02084");
image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;
// Should succeed.
VkImageObj image(m_device);
image.init(&image_create_info);
// Test image view creation
VkImageView view;
VkImageViewCreateInfo ivci = {};
ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
ivci.image = image.handle();
ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
ivci.format = VK_FORMAT_R8_UINT;
ivci.subresourceRange.layerCount = 1;
ivci.subresourceRange.baseMipLevel = 0;
ivci.subresourceRange.levelCount = 1;
ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
// view type must be 2D or 2D_ARRAY
ivci.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
ivci.subresourceRange.layerCount = 6;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-02086");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-01003");
result = vk::CreateImageView(m_device->device(), &ivci, nullptr, &view);
m_errorMonitor->VerifyFound();
if (VK_SUCCESS == result) {
vk::DestroyImageView(m_device->device(), view, NULL);
view = VK_NULL_HANDLE;
}
ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
ivci.subresourceRange.layerCount = 1;
// format must be R8_UINT
ivci.format = VK_FORMAT_R8_UNORM;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-02087");
result = vk::CreateImageView(m_device->device(), &ivci, nullptr, &view);
m_errorMonitor->VerifyFound();
if (VK_SUCCESS == result) {
vk::DestroyImageView(m_device->device(), view, NULL);
view = VK_NULL_HANDLE;
}
ivci.format = VK_FORMAT_R8_UINT;
vk::CreateImageView(m_device->device(), &ivci, nullptr, &view);
m_errorMonitor->VerifyNotFound();
// Test pipeline creation
VkPipelineViewportShadingRateImageStateCreateInfoNV vsrisci = {
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV};
VkViewport viewport = {0.0f, 0.0f, 64.0f, 64.0f, 0.0f, 1.0f};
VkViewport viewports[20] = {viewport, viewport};
VkRect2D scissor = {{0, 0}, {64, 64}};
VkRect2D scissors[20] = {scissor, scissor};
VkDynamicState dynPalette = VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV;
VkPipelineDynamicStateCreateInfo dyn = {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, nullptr, 0, 1, &dynPalette};
// viewportCount must be 0 or 1 when multiViewport is disabled
{
const auto break_vp = [&](CreatePipelineHelper &helper) {
helper.vp_state_ci_.viewportCount = 2;
helper.vp_state_ci_.pViewports = viewports;
helper.vp_state_ci_.scissorCount = 2;
helper.vp_state_ci_.pScissors = scissors;
helper.vp_state_ci_.pNext = &vsrisci;
helper.dyn_state_ci_ = dyn;
vsrisci.shadingRateImageEnable = VK_TRUE;
vsrisci.viewportCount = 2;
};
CreatePipelineHelper::OneshotTest(
*this, break_vp, kErrorBit,
vector<std::string>({"VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-viewportCount-02054",
"VUID-VkPipelineViewportStateCreateInfo-viewportCount-01216",
"VUID-VkPipelineViewportStateCreateInfo-scissorCount-01217"}));
}
// viewportCounts must match
{
const auto break_vp = [&](CreatePipelineHelper &helper) {
helper.vp_state_ci_.viewportCount = 1;
helper.vp_state_ci_.pViewports = viewports;
helper.vp_state_ci_.scissorCount = 1;
helper.vp_state_ci_.pScissors = scissors;
helper.vp_state_ci_.pNext = &vsrisci;
helper.dyn_state_ci_ = dyn;
vsrisci.shadingRateImageEnable = VK_TRUE;
vsrisci.viewportCount = 0;
};
CreatePipelineHelper::OneshotTest(
*this, break_vp, kErrorBit,
vector<std::string>({"VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-shadingRateImageEnable-02056"}));
}
// pShadingRatePalettes must not be NULL.
{
const auto break_vp = [&](CreatePipelineHelper &helper) {
helper.vp_state_ci_.viewportCount = 1;
helper.vp_state_ci_.pViewports = viewports;
helper.vp_state_ci_.scissorCount = 1;
helper.vp_state_ci_.pScissors = scissors;
helper.vp_state_ci_.pNext = &vsrisci;
vsrisci.shadingRateImageEnable = VK_TRUE;
vsrisci.viewportCount = 1;
};
CreatePipelineHelper::OneshotTest(*this, break_vp, kErrorBit,
vector<std::string>({"VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04057"}));
}
// Create an image without the SRI bit
VkImageObj nonSRIimage(m_device);
nonSRIimage.Init(256, 256, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);
ASSERT_TRUE(nonSRIimage.initialized());
VkImageView nonSRIview = nonSRIimage.targetView(VK_FORMAT_B8G8R8A8_UNORM);
// Test SRI layout on non-SRI image
VkImageMemoryBarrier img_barrier = {};
img_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
img_barrier.pNext = nullptr;
img_barrier.srcAccessMask = 0;
img_barrier.dstAccessMask = 0;
img_barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
img_barrier.newLayout = VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV;
img_barrier.image = nonSRIimage.handle();
img_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
img_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
img_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
img_barrier.subresourceRange.baseArrayLayer = 0;
img_barrier.subresourceRange.baseMipLevel = 0;
img_barrier.subresourceRange.layerCount = 1;
img_barrier.subresourceRange.levelCount = 1;
m_commandBuffer->begin();
// Error trying to convert it to SRI layout
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageMemoryBarrier-oldLayout-02088");
vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &img_barrier);
m_errorMonitor->VerifyFound();
// succeed converting it to GENERAL
img_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &img_barrier);
m_errorMonitor->VerifyNotFound();
// Test vk::CmdBindShadingRateImageNV errors
auto vkCmdBindShadingRateImageNV =
(PFN_vkCmdBindShadingRateImageNV)vk::GetDeviceProcAddr(m_device->device(), "vkCmdBindShadingRateImageNV");
// if the view is non-NULL, it must be R8_UINT, USAGE_SRI, image layout must match, layout must be valid
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBindShadingRateImageNV-imageView-02060");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBindShadingRateImageNV-imageView-02061");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBindShadingRateImageNV-imageView-02062");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBindShadingRateImageNV-imageLayout-02063");
vkCmdBindShadingRateImageNV(m_commandBuffer->handle(), nonSRIview, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
m_errorMonitor->VerifyFound();
// Test vk::CmdSetViewportShadingRatePaletteNV errors
auto vkCmdSetViewportShadingRatePaletteNV =
(PFN_vkCmdSetViewportShadingRatePaletteNV)vk::GetDeviceProcAddr(m_device->device(), "vkCmdSetViewportShadingRatePaletteNV");
VkShadingRatePaletteEntryNV paletteEntries[100] = {};
VkShadingRatePaletteNV palette = {100, paletteEntries};
VkShadingRatePaletteNV palettes[] = {palette, palette};
// errors on firstViewport/viewportCount
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02066");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02067");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02068");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetViewportShadingRatePaletteNV-viewportCount-02069");
vkCmdSetViewportShadingRatePaletteNV(m_commandBuffer->handle(), 20, 2, palettes);
m_errorMonitor->VerifyFound();
// shadingRatePaletteEntryCount must be in range
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkShadingRatePaletteNV-shadingRatePaletteEntryCount-02071");
vkCmdSetViewportShadingRatePaletteNV(m_commandBuffer->handle(), 0, 1, palettes);
m_errorMonitor->VerifyFound();
VkCoarseSampleLocationNV locations[100] = {
{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 1, 1}, // duplicate
{1000, 0, 0}, // pixelX too large
{0, 1000, 0}, // pixelY too large
{0, 0, 1000}, // sample too large
};
// Test custom sample orders, both via pipeline state and via dynamic state
{
VkCoarseSampleOrderCustomNV sampOrdBadShadingRate = {VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV, 1, 1,
locations};
VkCoarseSampleOrderCustomNV sampOrdBadSampleCount = {VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, 3, 1,
locations};
VkCoarseSampleOrderCustomNV sampOrdBadSampleLocationCount = {VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV,
2, 2, locations};
VkCoarseSampleOrderCustomNV sampOrdDuplicateLocations = {VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, 2,
1 * 2 * 2, &locations[1]};
VkCoarseSampleOrderCustomNV sampOrdOutOfRangeLocations = {VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, 2,
1 * 2 * 2, &locations[4]};
VkCoarseSampleOrderCustomNV sampOrdTooLargeSampleLocationCount = {
VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV, 4, 64, &locations[8]};
VkCoarseSampleOrderCustomNV sampOrdGood = {VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, 2, 1 * 2 * 2,
&locations[0]};
VkPipelineViewportCoarseSampleOrderStateCreateInfoNV csosci = {
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV};
csosci.sampleOrderType = VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV;
csosci.customSampleOrderCount = 1;
using std::vector;
struct TestCase {
const VkCoarseSampleOrderCustomNV *order;
vector<std::string> vuids;
};
vector<TestCase> test_cases = {
{&sampOrdBadShadingRate, {"VUID-VkCoarseSampleOrderCustomNV-shadingRate-02073"}},
{&sampOrdBadSampleCount,
{"VUID-VkCoarseSampleOrderCustomNV-sampleCount-02074", "VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02075"}},
{&sampOrdBadSampleLocationCount, {"VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02075"}},
{&sampOrdDuplicateLocations, {"VUID-VkCoarseSampleOrderCustomNV-pSampleLocations-02077"}},
{&sampOrdOutOfRangeLocations,
{"VUID-VkCoarseSampleOrderCustomNV-pSampleLocations-02077", "VUID-VkCoarseSampleLocationNV-pixelX-02078",
"VUID-VkCoarseSampleLocationNV-pixelY-02079", "VUID-VkCoarseSampleLocationNV-sample-02080"}},
{&sampOrdTooLargeSampleLocationCount,
{"VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02076",
"VUID-VkCoarseSampleOrderCustomNV-pSampleLocations-02077"}},
{&sampOrdGood, {}},
};
for (const auto &test_case : test_cases) {
const auto break_vp = [&](CreatePipelineHelper &helper) {
helper.vp_state_ci_.pNext = &csosci;
csosci.pCustomSampleOrders = test_case.order;
};
CreatePipelineHelper::OneshotTest(*this, break_vp, kErrorBit, test_case.vuids);
}
// Test vk::CmdSetCoarseSampleOrderNV errors
auto vkCmdSetCoarseSampleOrderNV =
(PFN_vkCmdSetCoarseSampleOrderNV)vk::GetDeviceProcAddr(m_device->device(), "vkCmdSetCoarseSampleOrderNV");
for (const auto &test_case : test_cases) {
for (uint32_t i = 0; i < test_case.vuids.size(); ++i) {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, test_case.vuids[i]);
}
vkCmdSetCoarseSampleOrderNV(m_commandBuffer->handle(), VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV, 1, test_case.order);
if (test_case.vuids.size()) {
m_errorMonitor->VerifyFound();
} else {
m_errorMonitor->VerifyNotFound();
}
}
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetCoarseSampleOrderNV-sampleOrderType-02081");
vkCmdSetCoarseSampleOrderNV(m_commandBuffer->handle(), VK_COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV, 1, &sampOrdGood);
m_errorMonitor->VerifyFound();
}
m_commandBuffer->end();
vk::DestroyImageView(m_device->device(), view, NULL);
}
#ifdef VK_USE_PLATFORM_ANDROID_KHR
#include "android_ndk_types.h"
TEST_F(VkLayerTest, AndroidHardwareBufferImageCreate) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer image create info.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkDevice dev = m_device->device();
VkImage img = VK_NULL_HANDLE;
auto reset_img = [&img, dev]() {
if (VK_NULL_HANDLE != img) vk::DestroyImage(dev, img, NULL);
img = VK_NULL_HANDLE;
};
VkImageCreateInfo ici = {};
ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
ici.pNext = nullptr;
ici.imageType = VK_IMAGE_TYPE_2D;
ici.arrayLayers = 1;
ici.extent = {64, 64, 1};
ici.format = VK_FORMAT_UNDEFINED;
ici.mipLevels = 1;
ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
ici.samples = VK_SAMPLE_COUNT_1_BIT;
ici.tiling = VK_IMAGE_TILING_OPTIMAL;
ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
// undefined format
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-01975");
// Various extra errors for having VK_FORMAT_UNDEFINED without VkExternalFormatANDROID
m_errorMonitor->SetUnexpectedError("VUID_Undefined");
m_errorMonitor->SetUnexpectedError("UNASSIGNED-CoreValidation-Image-FormatNotSupported");
m_errorMonitor->SetUnexpectedError("VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
// also undefined format
VkExternalFormatANDROID efa = {};
efa.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
efa.externalFormat = 0;
ici.pNext = &efa;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-01975");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
// undefined format with an unknown external format
efa.externalFormat = 0xBADC0DE;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkExternalFormatANDROID-externalFormat-01894");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
AHardwareBuffer *ahb;
AHardwareBuffer_Desc ahb_desc = {};
ahb_desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.width = 64;
ahb_desc.height = 64;
ahb_desc.layers = 1;
// Allocate an AHardwareBuffer
AHardwareBuffer_allocate(&ahb_desc, &ahb);
// Retrieve it's properties to make it's external format 'known' (AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM)
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_fmt_props = {};
ahb_fmt_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props.pNext = &ahb_fmt_props;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID pfn_GetAHBProps =
(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vk::GetDeviceProcAddr(dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
ASSERT_TRUE(pfn_GetAHBProps != nullptr);
pfn_GetAHBProps(dev, ahb, &ahb_props);
// a defined image format with a non-zero external format
ici.format = VK_FORMAT_R8G8B8A8_UNORM;
efa.externalFormat = ahb_fmt_props.externalFormat;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-01974");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
ici.format = VK_FORMAT_UNDEFINED;
// external format while MUTABLE
ici.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-02396");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
ici.flags = 0;
// external format while usage other than SAMPLED
ici.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-02397");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
// external format while tiline other than OPTIMAL
ici.tiling = VK_IMAGE_TILING_LINEAR;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-02398");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
ici.tiling = VK_IMAGE_TILING_OPTIMAL;
// imageType
VkExternalMemoryImageCreateInfo emici = {};
emici.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
emici.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
ici.pNext = &emici; // remove efa from chain, insert emici
ici.format = VK_FORMAT_R8G8B8A8_UNORM;
ici.imageType = VK_IMAGE_TYPE_3D;
ici.extent = {64, 64, 64};
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-02393");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
// wrong mipLevels
ici.imageType = VK_IMAGE_TYPE_2D;
ici.extent = {64, 64, 1};
ici.mipLevels = 6; // should be 7
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-02394");
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyFound();
reset_img();
}
TEST_F(VkLayerTest, AndroidHardwareBufferFetchUnboundImageInfo) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer retreive image properties while memory unbound.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkDevice dev = m_device->device();
VkImage img = VK_NULL_HANDLE;
auto reset_img = [&img, dev]() {
if (VK_NULL_HANDLE != img) vk::DestroyImage(dev, img, NULL);
img = VK_NULL_HANDLE;
};
VkImageCreateInfo ici = {};
ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
ici.pNext = nullptr;
ici.imageType = VK_IMAGE_TYPE_2D;
ici.arrayLayers = 1;
ici.extent = {64, 64, 1};
ici.format = VK_FORMAT_R8G8B8A8_UNORM;
ici.mipLevels = 1;
ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
ici.samples = VK_SAMPLE_COUNT_1_BIT;
ici.tiling = VK_IMAGE_TILING_LINEAR;
ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
VkExternalMemoryImageCreateInfo emici = {};
emici.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
emici.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
ici.pNext = &emici;
m_errorMonitor->ExpectSuccess();
vk::CreateImage(dev, &ici, NULL, &img);
m_errorMonitor->VerifyNotFound();
// attempt to fetch layout from unbound image
VkImageSubresource sub_rsrc = {};
sub_rsrc.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
VkSubresourceLayout sub_layout = {};
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetImageSubresourceLayout-image-01895");
vk::GetImageSubresourceLayout(dev, img, &sub_rsrc, &sub_layout);
m_errorMonitor->VerifyFound();
// attempt to get memory reqs from unbound image
VkImageMemoryRequirementsInfo2 imri = {};
imri.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2;
imri.image = img;
VkMemoryRequirements2 mem_reqs = {};
mem_reqs.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageMemoryRequirementsInfo2-image-01897");
vk::GetImageMemoryRequirements2(dev, &imri, &mem_reqs);
m_errorMonitor->VerifyFound();
reset_img();
}
TEST_F(VkLayerTest, AndroidHardwareBufferMemoryAllocation) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer memory allocation.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (IsPlatform(kGalaxyS10)) {
printf("%s This test should not run on Galaxy S10\n", kSkipPrefix);
return;
}
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkDevice dev = m_device->device();
VkImage img = VK_NULL_HANDLE;
auto reset_img = [&img, dev]() {
if (VK_NULL_HANDLE != img) vk::DestroyImage(dev, img, NULL);
img = VK_NULL_HANDLE;
};
VkDeviceMemory mem_handle = VK_NULL_HANDLE;
auto reset_mem = [&mem_handle, dev]() {
if (VK_NULL_HANDLE != mem_handle) vk::FreeMemory(dev, mem_handle, NULL);
mem_handle = VK_NULL_HANDLE;
};
PFN_vkGetAndroidHardwareBufferPropertiesANDROID pfn_GetAHBProps =
(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vk::GetDeviceProcAddr(dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
ASSERT_TRUE(pfn_GetAHBProps != nullptr);
// AHB structs
AHardwareBuffer *ahb = nullptr;
AHardwareBuffer_Desc ahb_desc = {};
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_fmt_props = {};
ahb_fmt_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props.pNext = &ahb_fmt_props;
VkImportAndroidHardwareBufferInfoANDROID iahbi = {};
iahbi.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
// destroy and re-acquire an AHB, and fetch it's properties
auto recreate_ahb = [&ahb, &iahbi, &ahb_desc, &ahb_props, dev, pfn_GetAHBProps]() {
if (ahb) AHardwareBuffer_release(ahb);
ahb = nullptr;
AHardwareBuffer_allocate(&ahb_desc, &ahb);
if (ahb) {
pfn_GetAHBProps(dev, ahb, &ahb_props);
iahbi.buffer = ahb;
}
};
// Allocate an AHardwareBuffer
ahb_desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.width = 64;
ahb_desc.height = 64;
ahb_desc.layers = 1;
recreate_ahb();
// Create an image w/ external format
VkExternalFormatANDROID efa = {};
efa.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
efa.externalFormat = ahb_fmt_props.externalFormat;
VkImageCreateInfo ici = {};
ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
ici.pNext = &efa;
ici.imageType = VK_IMAGE_TYPE_2D;
ici.arrayLayers = 1;
ici.extent = {64, 64, 1};
ici.format = VK_FORMAT_UNDEFINED;
ici.mipLevels = 1;
ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
ici.samples = VK_SAMPLE_COUNT_1_BIT;
ici.tiling = VK_IMAGE_TILING_OPTIMAL;
ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
VkResult res = vk::CreateImage(dev, &ici, NULL, &img);
ASSERT_VK_SUCCESS(res);
VkMemoryAllocateInfo mai = {};
mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mai.pNext = &iahbi; // Chained import struct
mai.allocationSize = ahb_props.allocationSize;
mai.memoryTypeIndex = 32;
// Set index to match one of the bits in ahb_props
for (int i = 0; i < 32; i++) {
if (ahb_props.memoryTypeBits & (1 << i)) {
mai.memoryTypeIndex = i;
break;
}
}
ASSERT_NE(32, mai.memoryTypeIndex);
// Import w/ non-dedicated memory allocation
// Import requires format AHB_FMT_BLOB and usage AHB_USAGE_GPU_DATA_BUFFER
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02384");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
// Allocation size mismatch
ahb_desc.format = AHARDWAREBUFFER_FORMAT_BLOB;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;
ahb_desc.height = 1;
recreate_ahb();
mai.allocationSize = ahb_props.allocationSize + 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-allocationSize-02383");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
mai.allocationSize = ahb_props.allocationSize;
reset_mem();
// memoryTypeIndex mismatch
mai.memoryTypeIndex++;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-memoryTypeIndex-02385");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
mai.memoryTypeIndex--;
reset_mem();
// Insert dedicated image memory allocation to mai chain
VkMemoryDedicatedAllocateInfo mdai = {};
mdai.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
mdai.image = img;
mdai.buffer = VK_NULL_HANDLE;
mdai.pNext = mai.pNext;
mai.pNext = &mdai;
// Dedicated allocation with unmatched usage bits for Color
ahb_desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
ahb_desc.height = 64;
recreate_ahb();
mai.allocationSize = ahb_props.allocationSize;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02390");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
// Dedicated allocation with unmatched usage bits for Depth/Stencil
ahb_desc.format = AHARDWAREBUFFER_FORMAT_S8_UINT;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
ahb_desc.height = 64;
recreate_ahb();
mai.allocationSize = ahb_props.allocationSize;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02390");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
// Dedicated allocation with incomplete mip chain
reset_img();
ici.mipLevels = 2;
vk::CreateImage(dev, &ici, NULL, &img);
mdai.image = img;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE;
recreate_ahb();
if (ahb) {
mai.allocationSize = ahb_props.allocationSize;
for (int i = 0; i < 32; i++) {
if (ahb_props.memoryTypeBits & (1 << i)) {
mai.memoryTypeIndex = i;
break;
}
}
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02389");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
} else {
// ERROR: AHardwareBuffer_allocate() with MIPMAP_COMPLETE fails. It returns -12, NO_MEMORY.
// The problem seems to happen in Pixel 2, not Pixel 3.
printf("%s AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE not supported, skipping tests\n", kSkipPrefix);
return;
}
// Dedicated allocation with mis-matched dimension
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.height = 32;
ahb_desc.width = 128;
recreate_ahb();
mai.allocationSize = ahb_props.allocationSize;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02388");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
// Dedicated allocation with mis-matched VkFormat
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.height = 64;
ahb_desc.width = 64;
recreate_ahb();
mai.allocationSize = ahb_props.allocationSize;
ici.mipLevels = 1;
ici.format = VK_FORMAT_B8G8R8A8_UNORM;
ici.pNext = NULL;
VkImage img2;
vk::CreateImage(dev, &ici, NULL, &img2);
mdai.image = img2;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02387");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
vk::DestroyImage(dev, img2, NULL);
mdai.image = img;
reset_mem();
// Missing required ahb usage
ahb_desc.usage = AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetAndroidHardwareBufferPropertiesANDROID-buffer-01884");
recreate_ahb();
m_errorMonitor->VerifyFound();
// Dedicated allocation with missing usage bits
// Setting up this test also triggers a slew of others
mai.allocationSize = ahb_props.allocationSize + 1;
mai.memoryTypeIndex = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02390");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-memoryTypeIndex-02385");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-allocationSize-02383");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02386");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
// Non-import allocation - replace import struct in chain with export struct
VkExportMemoryAllocateInfo emai = {};
emai.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
emai.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
mai.pNext = &emai;
emai.pNext = &mdai; // still dedicated
mdai.pNext = nullptr;
// Export with allocation size non-zero
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
recreate_ahb();
mai.allocationSize = ahb_props.allocationSize;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryDedicatedAllocateInfo-image-02964");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-01874");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
reset_mem();
AHardwareBuffer_release(ahb);
reset_mem();
reset_img();
}
TEST_F(VkLayerTest, AndroidHardwareBufferCreateYCbCrSampler) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer YCbCr sampler creation.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
// Enable Ycbcr Conversion Features
VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcr_features = {};
ycbcr_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
ycbcr_features.samplerYcbcrConversion = VK_TRUE;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &ycbcr_features));
VkDevice dev = m_device->device();
VkSamplerYcbcrConversion ycbcr_conv = VK_NULL_HANDLE;
VkSamplerYcbcrConversionCreateInfo sycci = {};
sycci.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO;
sycci.format = VK_FORMAT_UNDEFINED;
sycci.ycbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
sycci.ycbcrRange = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSamplerYcbcrConversionCreateInfo-format-04061");
m_errorMonitor->SetUnexpectedError("VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01651");
vk::CreateSamplerYcbcrConversion(dev, &sycci, NULL, &ycbcr_conv);
m_errorMonitor->VerifyFound();
VkExternalFormatANDROID efa = {};
efa.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
efa.externalFormat = AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM;
sycci.format = VK_FORMAT_R8G8B8A8_UNORM;
sycci.pNext = &efa;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSamplerYcbcrConversionCreateInfo-format-01904");
m_errorMonitor->SetUnexpectedError("VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01651");
vk::CreateSamplerYcbcrConversion(dev, &sycci, NULL, &ycbcr_conv);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, AndroidHardwareBufferPhysDevImageFormatProp2) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer GetPhysicalDeviceImageFormatProperties.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping test\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
if ((DeviceValidationVersion() < VK_API_VERSION_1_1) &&
!InstanceExtensionEnabled(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
printf("%s %s extension not supported, skipping test\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
VkImageFormatProperties2 ifp = {};
ifp.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
VkPhysicalDeviceImageFormatInfo2 pdifi = {};
pdifi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
pdifi.format = VK_FORMAT_R8G8B8A8_UNORM;
pdifi.tiling = VK_IMAGE_TILING_OPTIMAL;
pdifi.type = VK_IMAGE_TYPE_2D;
pdifi.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
VkAndroidHardwareBufferUsageANDROID ahbu = {};
ahbu.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
ahbu.androidHardwareBufferUsage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ifp.pNext = &ahbu;
// AHB_usage chained to input without a matching external image format struc chained to output
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetPhysicalDeviceImageFormatProperties2-pNext-01868");
vk::GetPhysicalDeviceImageFormatProperties2(m_device->phy().handle(), &pdifi, &ifp);
m_errorMonitor->VerifyFound();
// output struct chained, but does not include VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID usage
VkPhysicalDeviceExternalImageFormatInfo pdeifi = {};
pdeifi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
pdeifi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
pdifi.pNext = &pdeifi;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetPhysicalDeviceImageFormatProperties2-pNext-01868");
vk::GetPhysicalDeviceImageFormatProperties2(m_device->phy().handle(), &pdifi, &ifp);
m_errorMonitor->VerifyFound();
}
#if DISABLEUNTILAHBWORKS
TEST_F(VkLayerTest, AndroidHardwareBufferCreateImageView) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer image view creation.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkDevice dev = m_device->device();
// Allocate an AHB and fetch its properties
AHardwareBuffer *ahb = nullptr;
AHardwareBuffer_Desc ahb_desc = {};
ahb_desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.width = 64;
ahb_desc.height = 64;
ahb_desc.layers = 1;
AHardwareBuffer_allocate(&ahb_desc, &ahb);
// Retrieve AHB properties to make it's external format 'known'
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_fmt_props = {};
ahb_fmt_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props.pNext = &ahb_fmt_props;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID pfn_GetAHBProps =
(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vk::GetDeviceProcAddr(dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
ASSERT_TRUE(pfn_GetAHBProps != nullptr);
pfn_GetAHBProps(dev, ahb, &ahb_props);
AHardwareBuffer_release(ahb);
VkExternalMemoryImageCreateInfo emici = {};
emici.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
emici.pNext = nullptr;
emici.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
// Give image an external format
VkExternalFormatANDROID efa = {};
efa.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
efa.pNext = (void *)&emici;
efa.externalFormat = ahb_fmt_props.externalFormat;
ahb_desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.width = 64;
ahb_desc.height = 1;
ahb_desc.layers = 1;
AHardwareBuffer_allocate(&ahb_desc, &ahb);
// Create another VkExternalFormatANDROID for test VUID-VkImageViewCreateInfo-image-02400
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_fmt_props_Ycbcr = {};
ahb_fmt_props_Ycbcr.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID ahb_props_Ycbcr = {};
ahb_props_Ycbcr.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props_Ycbcr.pNext = &ahb_fmt_props_Ycbcr;
pfn_GetAHBProps(dev, ahb, &ahb_props_Ycbcr);
AHardwareBuffer_release(ahb);
VkExternalFormatANDROID efa_Ycbcr = {};
efa_Ycbcr.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
efa_Ycbcr.externalFormat = ahb_fmt_props_Ycbcr.externalFormat;
// Need to make sure format has sample bit needed for image usage
if ((ahb_fmt_props_Ycbcr.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) == 0) {
printf("%s VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT feature bit not supported for format %" PRIu64 ".", kSkipPrefix,
ahb_fmt_props_Ycbcr.externalFormat);
return;
}
// Create the image
VkImage img = VK_NULL_HANDLE;
VkImageCreateInfo ici = {};
ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
ici.pNext = &efa;
ici.imageType = VK_IMAGE_TYPE_2D;
ici.arrayLayers = 1;
ici.extent = {64, 64, 1};
ici.format = VK_FORMAT_UNDEFINED;
ici.mipLevels = 1;
ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
ici.samples = VK_SAMPLE_COUNT_1_BIT;
ici.tiling = VK_IMAGE_TILING_OPTIMAL;
ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
vk::CreateImage(dev, &ici, NULL, &img);
// Set up memory allocation
VkDeviceMemory img_mem = VK_NULL_HANDLE;
VkMemoryAllocateInfo mai = {};
mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mai.allocationSize = 64 * 64 * 4;
mai.memoryTypeIndex = 0;
vk::AllocateMemory(dev, &mai, NULL, &img_mem);
// It shouldn't use vk::GetImageMemoryRequirements for imported AndroidHardwareBuffer when memory isn't bound yet
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetImageMemoryRequirements-image-04004");
VkMemoryRequirements img_mem_reqs = {};
vk::GetImageMemoryRequirements(m_device->device(), img, &img_mem_reqs);
m_errorMonitor->VerifyFound();
vk::BindImageMemory(dev, img, img_mem, 0);
// Bind image to memory
vk::DestroyImage(dev, img, NULL);
vk::FreeMemory(dev, img_mem, NULL);
vk::CreateImage(dev, &ici, NULL, &img);
vk::AllocateMemory(dev, &mai, NULL, &img_mem);
vk::BindImageMemory(dev, img, img_mem, 0);
// Create a YCbCr conversion, with different external format, chain to view
VkSamplerYcbcrConversion ycbcr_conv = VK_NULL_HANDLE;
VkSamplerYcbcrConversionCreateInfo sycci = {};
sycci.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO;
sycci.pNext = &efa_Ycbcr;
sycci.format = VK_FORMAT_UNDEFINED;
sycci.ycbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
sycci.ycbcrRange = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
vk::CreateSamplerYcbcrConversion(dev, &sycci, NULL, &ycbcr_conv);
VkSamplerYcbcrConversionInfo syci = {};
syci.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO;
syci.conversion = ycbcr_conv;
// Create a view
VkImageView image_view = VK_NULL_HANDLE;
VkImageViewCreateInfo ivci = {};
ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
ivci.pNext = &syci;
ivci.image = img;
ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
ivci.format = VK_FORMAT_UNDEFINED;
ivci.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
auto reset_view = [&image_view, dev]() {
if (VK_NULL_HANDLE != image_view) vk::DestroyImageView(dev, image_view, NULL);
image_view = VK_NULL_HANDLE;
};
// Up to this point, no errors expected
m_errorMonitor->VerifyNotFound();
// Chained ycbcr conversion has different (external) format than image
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-02400");
// Also causes "unsupported format" - should be removed in future spec update
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-None-02273");
vk::CreateImageView(dev, &ivci, NULL, &image_view);
m_errorMonitor->VerifyFound();
reset_view();
vk::DestroySamplerYcbcrConversion(dev, ycbcr_conv, NULL);
sycci.pNext = &efa;
vk::CreateSamplerYcbcrConversion(dev, &sycci, NULL, &ycbcr_conv);
syci.conversion = ycbcr_conv;
// View component swizzle not IDENTITY
ivci.components.r = VK_COMPONENT_SWIZZLE_B;
ivci.components.b = VK_COMPONENT_SWIZZLE_R;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-02401");
// Also causes "unsupported format" - should be removed in future spec update
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-None-02273");
vk::CreateImageView(dev, &ivci, NULL, &image_view);
m_errorMonitor->VerifyFound();
reset_view();
ivci.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
ivci.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
// View with external format, when format is not UNDEFINED
ivci.format = VK_FORMAT_R5G6B5_UNORM_PACK16;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-02399");
// Also causes "view format different from image format"
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageViewCreateInfo-image-01762");
vk::CreateImageView(dev, &ivci, NULL, &image_view);
m_errorMonitor->VerifyFound();
reset_view();
vk::DestroySamplerYcbcrConversion(dev, ycbcr_conv, NULL);
vk::DestroyImageView(dev, image_view, NULL);
vk::DestroyImage(dev, img, NULL);
vk::FreeMemory(dev, img_mem, NULL);
}
#endif // DISABLEUNTILAHBWORKS
TEST_F(VkLayerTest, AndroidHardwareBufferImportBuffer) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer import as buffer.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (IsPlatform(kGalaxyS10)) {
printf("%s This test should not run on Galaxy S10\n", kSkipPrefix);
return;
}
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkDevice dev = m_device->device();
VkDeviceMemory mem_handle = VK_NULL_HANDLE;
auto reset_mem = [&mem_handle, dev]() {
if (VK_NULL_HANDLE != mem_handle) vk::FreeMemory(dev, mem_handle, NULL);
mem_handle = VK_NULL_HANDLE;
};
PFN_vkGetAndroidHardwareBufferPropertiesANDROID pfn_GetAHBProps =
(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vk::GetDeviceProcAddr(dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
ASSERT_TRUE(pfn_GetAHBProps != nullptr);
// AHB structs
AHardwareBuffer *ahb = nullptr;
AHardwareBuffer_Desc ahb_desc = {};
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
VkImportAndroidHardwareBufferInfoANDROID iahbi = {};
iahbi.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
// Allocate an AHardwareBuffer
ahb_desc.format = AHARDWAREBUFFER_FORMAT_BLOB;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA; // non USAGE_GPU_*
ahb_desc.width = 512;
ahb_desc.height = 1;
ahb_desc.layers = 1;
AHardwareBuffer_allocate(&ahb_desc, &ahb);
m_errorMonitor->SetUnexpectedError("VUID-vkGetAndroidHardwareBufferPropertiesANDROID-buffer-01884");
pfn_GetAHBProps(dev, ahb, &ahb_props);
iahbi.buffer = ahb;
// Create export and import buffers
VkExternalMemoryBufferCreateInfo ext_buf_info = {};
ext_buf_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR;
ext_buf_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
VkBufferCreateInfo bci = {};
bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bci.pNext = &ext_buf_info;
bci.size = ahb_props.allocationSize;
bci.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VkBuffer buf = VK_NULL_HANDLE;
vk::CreateBuffer(dev, &bci, NULL, &buf);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(dev, buf, &mem_reqs);
// Allocation info
VkMemoryAllocateInfo mai = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, mem_reqs, 0);
mai.pNext = &iahbi; // Chained import struct
VkPhysicalDeviceMemoryProperties memory_info;
vk::GetPhysicalDeviceMemoryProperties(gpu(), &memory_info);
unsigned int i;
for (i = 0; i < memory_info.memoryTypeCount; i++) {
if ((ahb_props.memoryTypeBits & (1 << i))) {
mai.memoryTypeIndex = i;
break;
}
}
if (i >= memory_info.memoryTypeCount) {
printf("%s No invalid memory type index could be found; skipped.\n", kSkipPrefix);
AHardwareBuffer_release(ahb);
reset_mem();
vk::DestroyBuffer(dev, buf, NULL);
return;
}
// Import as buffer requires usage AHB_USAGE_GPU_DATA_BUFFER
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImportAndroidHardwareBufferInfoANDROID-buffer-01881");
// Also causes "non-dedicated allocation format/usage" error
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryAllocateInfo-pNext-02384");
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
m_errorMonitor->VerifyFound();
AHardwareBuffer_release(ahb);
reset_mem();
vk::DestroyBuffer(dev, buf, NULL);
}
TEST_F(VkLayerTest, AndroidHardwareBufferExporttBuffer) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer export memory as AHB.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (IsPlatform(kGalaxyS10)) {
printf("%s This test should not run on Galaxy S10\n", kSkipPrefix);
return;
}
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkDevice dev = m_device->device();
VkDeviceMemory mem_handle = VK_NULL_HANDLE;
// Allocate device memory, no linked export struct indicating AHB handle type
VkMemoryAllocateInfo mai = {};
mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mai.allocationSize = 65536;
mai.memoryTypeIndex = 0;
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
PFN_vkGetMemoryAndroidHardwareBufferANDROID pfn_GetMemAHB =
(PFN_vkGetMemoryAndroidHardwareBufferANDROID)vk::GetDeviceProcAddr(dev, "vkGetMemoryAndroidHardwareBufferANDROID");
ASSERT_TRUE(pfn_GetMemAHB != nullptr);
VkMemoryGetAndroidHardwareBufferInfoANDROID mgahbi = {};
mgahbi.sType = VK_STRUCTURE_TYPE_MEMORY_GET_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
mgahbi.memory = mem_handle;
AHardwareBuffer *ahb = nullptr;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-handleTypes-01882");
pfn_GetMemAHB(dev, &mgahbi, &ahb);
m_errorMonitor->VerifyFound();
if (ahb) AHardwareBuffer_release(ahb);
ahb = nullptr;
if (VK_NULL_HANDLE != mem_handle) vk::FreeMemory(dev, mem_handle, NULL);
mem_handle = VK_NULL_HANDLE;
// Add an export struct with AHB handle type to allocation info
VkExportMemoryAllocateInfo emai = {};
emai.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
emai.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
mai.pNext = &emai;
// Create an image, do not bind memory
VkImage img = VK_NULL_HANDLE;
VkImageCreateInfo ici = {};
ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
ici.imageType = VK_IMAGE_TYPE_2D;
ici.arrayLayers = 1;
ici.extent = {128, 128, 1};
ici.format = VK_FORMAT_R8G8B8A8_UNORM;
ici.mipLevels = 1;
ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
ici.samples = VK_SAMPLE_COUNT_1_BIT;
ici.tiling = VK_IMAGE_TILING_OPTIMAL;
ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
vk::CreateImage(dev, &ici, NULL, &img);
ASSERT_TRUE(VK_NULL_HANDLE != img);
// Add image to allocation chain as dedicated info, re-allocate
VkMemoryDedicatedAllocateInfo mdai = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO};
mdai.image = img;
emai.pNext = &mdai;
mai.allocationSize = 0;
vk::AllocateMemory(dev, &mai, NULL, &mem_handle);
mgahbi.memory = mem_handle;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-pNext-01883");
pfn_GetMemAHB(dev, &mgahbi, &ahb);
m_errorMonitor->VerifyFound();
if (ahb) AHardwareBuffer_release(ahb);
if (VK_NULL_HANDLE != mem_handle) vk::FreeMemory(dev, mem_handle, NULL);
vk::DestroyImage(dev, img, NULL);
}
TEST_F(VkLayerTest, AndroidHardwareBufferUnboundBuffer) {
TEST_DESCRIPTION("Verify AndroidHardwareBuffer can't be queried for mem requirements while unbound.");
SetTargetApiVersion(VK_API_VERSION_1_1);
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkExternalMemoryBufferCreateInfo ext_buf_info = {};
ext_buf_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR;
ext_buf_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.pNext = &ext_buf_info;
buffer_create_info.size = 512;
buffer_create_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VkBuffer buffer = VK_NULL_HANDLE;
vk::CreateBuffer(m_device->device(), &buffer_create_info, nullptr, &buffer);
// Try to get memory requirements prior to binding memory
VkMemoryRequirements mem_reqs;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetBufferMemoryRequirements-buffer-04003");
vk::GetBufferMemoryRequirements(m_device->device(), buffer, &mem_reqs);
m_errorMonitor->VerifyFound();
// Tests consecutive calls
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetBufferMemoryRequirements-buffer-04003");
vk::GetBufferMemoryRequirements(m_device->device(), buffer, &mem_reqs);
m_errorMonitor->VerifyFound();
// Test bind memory 2 extension
VkBufferMemoryRequirementsInfo2 buffer_mem_reqs2 = {};
buffer_mem_reqs2.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2;
buffer_mem_reqs2.pNext = nullptr;
buffer_mem_reqs2.buffer = buffer;
VkMemoryRequirements2 mem_reqs2;
mem_reqs2.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2;
mem_reqs2.pNext = nullptr;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBufferMemoryRequirementsInfo2-buffer-04005");
vk::GetBufferMemoryRequirements2(m_device->device(), &buffer_mem_reqs2, &mem_reqs2);
m_errorMonitor->VerifyFound();
vk::DestroyBuffer(m_device->device(), buffer, nullptr);
}
TEST_F(VkLayerTest, AndroidHardwareBufferImportBufferHandleType) {
TEST_DESCRIPTION("Don't use proper resource handleType for import buffer");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (IsPlatform(kGalaxyS10)) {
printf("%s This test should not run on Galaxy S10\n", kSkipPrefix);
return;
}
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
PFN_vkGetAndroidHardwareBufferPropertiesANDROID pfn_GetAHBProps =
(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vk::GetDeviceProcAddr(m_device->device(),
"vkGetAndroidHardwareBufferPropertiesANDROID");
PFN_vkBindBufferMemory2KHR vkBindBufferMemory2Function =
(PFN_vkBindBufferMemory2KHR)vk::GetDeviceProcAddr(m_device->handle(), "vkBindBufferMemory2KHR");
m_errorMonitor->ExpectSuccess();
AHardwareBuffer *ahb;
AHardwareBuffer_Desc ahb_desc = {};
ahb_desc.format = AHARDWAREBUFFER_FORMAT_BLOB;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;
ahb_desc.width = 64;
ahb_desc.height = 1;
ahb_desc.layers = 1;
ahb_desc.stride = 1;
AHardwareBuffer_allocate(&ahb_desc, &ahb);
// Create buffer without VkExternalMemoryBufferCreateInfo
VkBuffer buffer = VK_NULL_HANDLE;
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.pNext = nullptr;
buffer_create_info.size = 512;
buffer_create_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
vk::CreateBuffer(m_device->device(), &buffer_create_info, nullptr, &buffer);
VkImportAndroidHardwareBufferInfoANDROID import_ahb_Info = {};
import_ahb_Info.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
import_ahb_Info.pNext = nullptr;
import_ahb_Info.buffer = ahb;
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props.pNext = nullptr;
pfn_GetAHBProps(m_device->device(), ahb, &ahb_props);
VkMemoryAllocateInfo memory_allocate_info = {};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.pNext = &import_ahb_Info;
memory_allocate_info.allocationSize = ahb_props.allocationSize;
// driver won't expose correct memoryType since resource was not created as an import operation
// so just need any valid memory type returned from GetAHBInfo
for (int i = 0; i < 32; i++) {
if (ahb_props.memoryTypeBits & (1 << i)) {
memory_allocate_info.memoryTypeIndex = i;
break;
}
}
VkDeviceMemory memory;
vk::AllocateMemory(m_device->device(), &memory_allocate_info, nullptr, &memory);
m_errorMonitor->VerifyNotFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkBindBufferMemory-memory-02986");
m_errorMonitor->SetUnexpectedError("VUID-vkBindBufferMemory-memory-01035");
vk::BindBufferMemory(m_device->device(), buffer, memory, 0);
m_errorMonitor->VerifyFound();
VkBindBufferMemoryInfo bind_buffer_info = {};
bind_buffer_info.sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO;
bind_buffer_info.pNext = nullptr;
bind_buffer_info.buffer = buffer;
bind_buffer_info.memory = memory;
bind_buffer_info.memoryOffset = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindBufferMemoryInfo-memory-02988");
m_errorMonitor->SetUnexpectedError("VUID-VkBindBufferMemoryInfo-memory-01599");
vkBindBufferMemory2Function(m_device->device(), 1, &bind_buffer_info);
m_errorMonitor->VerifyFound();
vk::DestroyBuffer(m_device->device(), buffer, nullptr);
vk::FreeMemory(m_device->device(), memory, nullptr);
}
TEST_F(VkLayerTest, AndroidHardwareBufferImportImageHandleType) {
TEST_DESCRIPTION("Don't use proper resource handleType for import image");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (IsPlatform(kGalaxyS10)) {
printf("%s This test should not run on Galaxy S10\n", kSkipPrefix);
return;
}
if ((DeviceExtensionSupported(gpu(), nullptr, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME)) &&
// Also skip on devices that advertise AHB, but not the pre-requisite foreign_queue extension
(DeviceExtensionSupported(gpu(), nullptr, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME))) {
m_device_extension_names.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
m_device_extension_names.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
} else {
printf("%s %s extension not supported, skipping tests\n", kSkipPrefix,
VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
PFN_vkGetAndroidHardwareBufferPropertiesANDROID pfn_GetAHBProps =
(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vk::GetDeviceProcAddr(m_device->device(),
"vkGetAndroidHardwareBufferPropertiesANDROID");
PFN_vkBindImageMemory2KHR vkBindImageMemory2Function =
(PFN_vkBindImageMemory2KHR)vk::GetDeviceProcAddr(m_device->handle(), "vkBindImageMemory2KHR");
m_errorMonitor->ExpectSuccess();
AHardwareBuffer *ahb;
AHardwareBuffer_Desc ahb_desc = {};
ahb_desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
ahb_desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
ahb_desc.width = 64;
ahb_desc.height = 64;
ahb_desc.layers = 1;
ahb_desc.stride = 1;
AHardwareBuffer_allocate(&ahb_desc, &ahb);
// Create buffer without VkExternalMemoryImageCreateInfo
VkImage image = VK_NULL_HANDLE;
VkImageCreateInfo image_create_info = {};
image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_create_info.pNext = nullptr;
image_create_info.flags = 0;
image_create_info.imageType = VK_IMAGE_TYPE_2D;
image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_create_info.extent = {64, 64, 1};
image_create_info.mipLevels = 1;
image_create_info.arrayLayers = 1;
image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
vk::CreateImage(m_device->device(), &image_create_info, nullptr, &image);
VkMemoryDedicatedAllocateInfo memory_dedicated_info = {};
memory_dedicated_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
memory_dedicated_info.pNext = nullptr;
memory_dedicated_info.image = image;
memory_dedicated_info.buffer = VK_NULL_HANDLE;
VkImportAndroidHardwareBufferInfoANDROID import_ahb_Info = {};
import_ahb_Info.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
import_ahb_Info.pNext = &memory_dedicated_info;
import_ahb_Info.buffer = ahb;
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props.pNext = nullptr;
pfn_GetAHBProps(m_device->device(), ahb, &ahb_props);
VkMemoryAllocateInfo memory_allocate_info = {};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.pNext = &import_ahb_Info;
memory_allocate_info.allocationSize = ahb_props.allocationSize;
// driver won't expose correct memoryType since resource was not created as an import operation
// so just need any valid memory type returned from GetAHBInfo
for (int i = 0; i < 32; i++) {
if (ahb_props.memoryTypeBits & (1 << i)) {
memory_allocate_info.memoryTypeIndex = i;
break;
}
}
VkDeviceMemory memory;
vk::AllocateMemory(m_device->device(), &memory_allocate_info, nullptr, &memory);
m_errorMonitor->VerifyNotFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkBindImageMemory-memory-02990");
m_errorMonitor->SetUnexpectedError("VUID-vkBindImageMemory-memory-01047");
m_errorMonitor->SetUnexpectedError("VUID-vkBindImageMemory-size-01049");
vk::BindImageMemory(m_device->device(), image, memory, 0);
m_errorMonitor->VerifyFound();
VkBindImageMemoryInfo bind_image_info = {};
bind_image_info.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
bind_image_info.pNext = nullptr;
bind_image_info.image = image;
bind_image_info.memory = memory;
bind_image_info.memoryOffset = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindImageMemoryInfo-memory-02992");
m_errorMonitor->SetUnexpectedError("VUID-VkBindImageMemoryInfo-pNext-01617");
m_errorMonitor->SetUnexpectedError("VUID-VkBindImageMemoryInfo-pNext-01615");
vkBindImageMemory2Function(m_device->device(), 1, &bind_image_info);
m_errorMonitor->VerifyFound();
vk::DestroyImage(m_device->device(), image, nullptr);
vk::FreeMemory(m_device->device(), memory, nullptr);
}
#endif // VK_USE_PLATFORM_ANDROID_KHR
TEST_F(VkLayerTest, ValidateStride) {
TEST_DESCRIPTION("Validate Stride.");
ASSERT_NO_FATAL_FAILURE(Init(nullptr, nullptr, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));
if (IsPlatform(kPixelC)) {
printf("%s This test should not run on Pixel C\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkQueryPool query_pool;
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.queryType = VK_QUERY_TYPE_TIMESTAMP;
query_pool_ci.queryCount = 1;
vk::CreateQueryPool(m_device->device(), &query_pool_ci, nullptr, &query_pool);
m_commandBuffer->begin();
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
vk::CmdWriteTimestamp(m_commandBuffer->handle(), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, query_pool, 0);
m_commandBuffer->end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(m_device->m_queue);
char data_space;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-flags-02827");
vk::GetQueryPoolResults(m_device->handle(), query_pool, 0, 1, sizeof(data_space), &data_space, 1, VK_QUERY_RESULT_WAIT_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-flags-00815");
vk::GetQueryPoolResults(m_device->handle(), query_pool, 0, 1, sizeof(data_space), &data_space, 1,
(VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT));
m_errorMonitor->VerifyFound();
char data_space4[4] = "";
m_errorMonitor->ExpectSuccess();
vk::GetQueryPoolResults(m_device->handle(), query_pool, 0, 1, sizeof(data_space4), &data_space4, 4, VK_QUERY_RESULT_WAIT_BIT);
m_errorMonitor->VerifyNotFound();
char data_space8[8] = "";
m_errorMonitor->ExpectSuccess();
vk::GetQueryPoolResults(m_device->handle(), query_pool, 0, 1, sizeof(data_space8), &data_space8, 8,
(VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT));
m_errorMonitor->VerifyNotFound();
uint32_t qfi = 0;
VkBufferCreateInfo buff_create_info = {};
buff_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buff_create_info.size = 128;
buff_create_info.usage =
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
buff_create_info.queueFamilyIndexCount = 1;
buff_create_info.pQueueFamilyIndices = &qfi;
VkBufferObj buffer;
buffer.init(*m_device, buff_create_info);
m_commandBuffer->reset();
m_commandBuffer->begin();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-flags-00822");
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 0, 1, buffer.handle(), 1, 1, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyQueryPoolResults-flags-00823");
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 0, 1, buffer.handle(), 1, 1, VK_QUERY_RESULT_64_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->ExpectSuccess();
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 0, 1, buffer.handle(), 4, 4, 0);
m_errorMonitor->VerifyNotFound();
m_errorMonitor->ExpectSuccess();
vk::CmdCopyQueryPoolResults(m_commandBuffer->handle(), query_pool, 0, 1, buffer.handle(), 8, 8, VK_QUERY_RESULT_64_BIT);
m_errorMonitor->VerifyNotFound();
if (m_device->phy().features().multiDrawIndirect) {
CreatePipelineHelper helper(*this);
helper.InitInfo();
helper.InitState();
helper.CreateGraphicsPipeline();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, helper.pipeline_);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdDrawIndirect-drawCount-00476");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdDrawIndirect-drawCount-00488");
vk::CmdDrawIndirect(m_commandBuffer->handle(), buffer.handle(), 0, 100, 2);
m_errorMonitor->VerifyFound();
m_errorMonitor->ExpectSuccess();
vk::CmdDrawIndirect(m_commandBuffer->handle(), buffer.handle(), 0, 2, 24);
m_errorMonitor->VerifyNotFound();
vk::CmdBindIndexBuffer(m_commandBuffer->handle(), buffer.handle(), 0, VK_INDEX_TYPE_UINT16);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdDrawIndexedIndirect-drawCount-00528");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdDrawIndexedIndirect-drawCount-00540");
vk::CmdDrawIndexedIndirect(m_commandBuffer->handle(), buffer.handle(), 0, 100, 2);
m_errorMonitor->VerifyFound();
m_errorMonitor->ExpectSuccess();
vk::CmdDrawIndexedIndirect(m_commandBuffer->handle(), buffer.handle(), 0, 2, 24);
m_errorMonitor->VerifyNotFound();
vk::CmdEndRenderPass(m_commandBuffer->handle());
m_commandBuffer->end();
} else {
printf("%s Test requires unsupported multiDrawIndirect feature. Skipped.\n", kSkipPrefix);
}
vk::DestroyQueryPool(m_device->handle(), query_pool, NULL);
}
TEST_F(VkLayerTest, WarningSwapchainCreateInfoPreTransform) {
TEST_DESCRIPTION("Print warning when preTransform doesn't match curretTransform");
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-CoreValidation-SwapchainPreTransform");
m_errorMonitor->SetUnexpectedError("VUID-VkSwapchainCreateInfoKHR-preTransform-01279");
InitSwapchain(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR);
m_errorMonitor->VerifyFound();
DestroySwapchain();
}
TEST_F(VkLayerTest, ValidateGeometryNV) {
TEST_DESCRIPTION("Validate acceleration structure geometries.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
VkBufferObj vbo;
vbo.init(*m_device, 1024, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV);
VkBufferObj ibo;
ibo.init(*m_device, 1024, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV);
VkBufferObj tbo;
tbo.init(*m_device, 1024, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV);
VkBufferObj aabbbo;
aabbbo.init(*m_device, 1024, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV);
VkBufferCreateInfo unbound_buffer_ci = {};
unbound_buffer_ci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
unbound_buffer_ci.size = 1024;
unbound_buffer_ci.usage = VK_BUFFER_USAGE_RAY_TRACING_BIT_NV;
VkBufferObj unbound_buffer;
unbound_buffer.init_no_mem(*m_device, unbound_buffer_ci);
const std::vector<float> vertices = {1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f};
const std::vector<uint32_t> indicies = {0, 1, 2};
const std::vector<float> aabbs = {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f};
const std::vector<float> transforms = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
uint8_t *mapped_vbo_buffer_data = (uint8_t *)vbo.memory().map();
std::memcpy(mapped_vbo_buffer_data, (uint8_t *)vertices.data(), sizeof(float) * vertices.size());
vbo.memory().unmap();
uint8_t *mapped_ibo_buffer_data = (uint8_t *)ibo.memory().map();
std::memcpy(mapped_ibo_buffer_data, (uint8_t *)indicies.data(), sizeof(uint32_t) * indicies.size());
ibo.memory().unmap();
uint8_t *mapped_tbo_buffer_data = (uint8_t *)tbo.memory().map();
std::memcpy(mapped_tbo_buffer_data, (uint8_t *)transforms.data(), sizeof(float) * transforms.size());
tbo.memory().unmap();
uint8_t *mapped_aabbbo_buffer_data = (uint8_t *)aabbbo.memory().map();
std::memcpy(mapped_aabbbo_buffer_data, (uint8_t *)aabbs.data(), sizeof(float) * aabbs.size());
aabbbo.memory().unmap();
VkGeometryNV valid_geometry_triangles = {};
valid_geometry_triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_NV;
valid_geometry_triangles.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_NV;
valid_geometry_triangles.geometry.triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV;
valid_geometry_triangles.geometry.triangles.vertexData = vbo.handle();
valid_geometry_triangles.geometry.triangles.vertexOffset = 0;
valid_geometry_triangles.geometry.triangles.vertexCount = 3;
valid_geometry_triangles.geometry.triangles.vertexStride = 12;
valid_geometry_triangles.geometry.triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT;
valid_geometry_triangles.geometry.triangles.indexData = ibo.handle();
valid_geometry_triangles.geometry.triangles.indexOffset = 0;
valid_geometry_triangles.geometry.triangles.indexCount = 3;
valid_geometry_triangles.geometry.triangles.indexType = VK_INDEX_TYPE_UINT32;
valid_geometry_triangles.geometry.triangles.transformData = tbo.handle();
valid_geometry_triangles.geometry.triangles.transformOffset = 0;
valid_geometry_triangles.geometry.aabbs = {};
valid_geometry_triangles.geometry.aabbs.sType = VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV;
VkGeometryNV valid_geometry_aabbs = {};
valid_geometry_aabbs.sType = VK_STRUCTURE_TYPE_GEOMETRY_NV;
valid_geometry_aabbs.geometryType = VK_GEOMETRY_TYPE_AABBS_NV;
valid_geometry_aabbs.geometry.triangles = {};
valid_geometry_aabbs.geometry.triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV;
valid_geometry_aabbs.geometry.aabbs = {};
valid_geometry_aabbs.geometry.aabbs.sType = VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV;
valid_geometry_aabbs.geometry.aabbs.aabbData = aabbbo.handle();
valid_geometry_aabbs.geometry.aabbs.numAABBs = 1;
valid_geometry_aabbs.geometry.aabbs.offset = 0;
valid_geometry_aabbs.geometry.aabbs.stride = 24;
PFN_vkCreateAccelerationStructureNV vkCreateAccelerationStructureNV = reinterpret_cast<PFN_vkCreateAccelerationStructureNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkCreateAccelerationStructureNV"));
assert(vkCreateAccelerationStructureNV != nullptr);
const auto GetCreateInfo = [](const VkGeometryNV &geometry) {
VkAccelerationStructureCreateInfoNV as_create_info = {};
as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
as_create_info.info.instanceCount = 0;
as_create_info.info.geometryCount = 1;
as_create_info.info.pGeometries = &geometry;
return as_create_info;
};
VkAccelerationStructureNV as;
// Invalid vertex format.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.vertexFormat = VK_FORMAT_R64_UINT;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-vertexFormat-02430");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid vertex offset - not multiple of component size.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.vertexOffset = 1;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-vertexOffset-02429");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid vertex offset - bigger than buffer.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.vertexOffset = 12 * 1024;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-vertexOffset-02428");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid vertex buffer - no such buffer.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.vertexData = VkBuffer(123456789);
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-vertexData-parameter");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
#if 0
// XXX Subtest disabled because this is the wrong VUID.
// No VUIDs currently exist to require memory is bound (spec bug).
// Invalid vertex buffer - no memory bound.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.vertexData = unbound_buffer.handle();
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-vertexOffset-02428");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
#endif
// Invalid index offset - not multiple of index size.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.indexOffset = 1;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-indexOffset-02432");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid index offset - bigger than buffer.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.indexOffset = 2048;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-indexOffset-02431");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid index count - must be 0 if type is VK_INDEX_TYPE_NONE_NV.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.indexType = VK_INDEX_TYPE_NONE_NV;
geometry.geometry.triangles.indexData = VK_NULL_HANDLE;
geometry.geometry.triangles.indexCount = 1;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-indexCount-02436");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid index data - must be VK_NULL_HANDLE if type is VK_INDEX_TYPE_NONE_NV.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.indexType = VK_INDEX_TYPE_NONE_NV;
geometry.geometry.triangles.indexData = ibo.handle();
geometry.geometry.triangles.indexCount = 0;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-indexData-02434");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid transform offset - not multiple of 16.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.transformOffset = 1;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-transformOffset-02438");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid transform offset - bigger than buffer.
{
VkGeometryNV geometry = valid_geometry_triangles;
geometry.geometry.triangles.transformOffset = 2048;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryTrianglesNV-transformOffset-02437");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid aabb offset - not multiple of 8.
{
VkGeometryNV geometry = valid_geometry_aabbs;
geometry.geometry.aabbs.offset = 1;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryAABBNV-offset-02440");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid aabb offset - bigger than buffer.
{
VkGeometryNV geometry = valid_geometry_aabbs;
geometry.geometry.aabbs.offset = 8 * 1024;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryAABBNV-offset-02439");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Invalid aabb stride - not multiple of 8.
{
VkGeometryNV geometry = valid_geometry_aabbs;
geometry.geometry.aabbs.stride = 1;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryAABBNV-stride-02441");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// geometryType must be VK_GEOMETRY_TYPE_TRIANGLES_NV or VK_GEOMETRY_TYPE_AABBS_NV
{
VkGeometryNV geometry = valid_geometry_aabbs;
geometry.geometry.aabbs.stride = 1;
geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
VkAccelerationStructureCreateInfoNV as_create_info = GetCreateInfo(geometry);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkGeometryNV-geometryType-03503");
vkCreateAccelerationStructureNV(m_device->handle(), &as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateCreateAccelerationStructureNV) {
TEST_DESCRIPTION("Validate acceleration structure creation.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
PFN_vkCreateAccelerationStructureNV vkCreateAccelerationStructureNV = reinterpret_cast<PFN_vkCreateAccelerationStructureNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkCreateAccelerationStructureNV"));
assert(vkCreateAccelerationStructureNV != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
VkGeometryNV geometry;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometry);
VkAccelerationStructureCreateInfoNV as_create_info = {};
as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
VkAccelerationStructureNV as = VK_NULL_HANDLE;
// Top level can not have geometry
{
VkAccelerationStructureCreateInfoNV bad_top_level_create_info = as_create_info;
bad_top_level_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV;
bad_top_level_create_info.info.instanceCount = 0;
bad_top_level_create_info.info.geometryCount = 1;
bad_top_level_create_info.info.pGeometries = &geometry;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureInfoNV-type-02425");
vkCreateAccelerationStructureNV(m_device->handle(), &bad_top_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Bot level can not have instances
{
VkAccelerationStructureCreateInfoNV bad_bot_level_create_info = as_create_info;
bad_bot_level_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
bad_bot_level_create_info.info.instanceCount = 1;
bad_bot_level_create_info.info.geometryCount = 0;
bad_bot_level_create_info.info.pGeometries = nullptr;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureInfoNV-type-02426");
vkCreateAccelerationStructureNV(m_device->handle(), &bad_bot_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Can not prefer both fast trace and fast build
{
VkAccelerationStructureCreateInfoNV bad_flags_level_create_info = as_create_info;
bad_flags_level_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
bad_flags_level_create_info.info.instanceCount = 0;
bad_flags_level_create_info.info.geometryCount = 1;
bad_flags_level_create_info.info.pGeometries = &geometry;
bad_flags_level_create_info.info.flags =
VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_NV | VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_NV;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureInfoNV-flags-02592");
vkCreateAccelerationStructureNV(m_device->handle(), &bad_flags_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Can not have geometry or instance for compacting
{
VkAccelerationStructureCreateInfoNV bad_compacting_as_create_info = as_create_info;
bad_compacting_as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
bad_compacting_as_create_info.info.instanceCount = 0;
bad_compacting_as_create_info.info.geometryCount = 1;
bad_compacting_as_create_info.info.pGeometries = &geometry;
bad_compacting_as_create_info.info.flags = 0;
bad_compacting_as_create_info.compactedSize = 1024;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureCreateInfoNV-compactedSize-02421");
vkCreateAccelerationStructureNV(m_device->handle(), &bad_compacting_as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Can not mix different geometry types into single bottom level acceleration structure
{
VkGeometryNV aabb_geometry = {};
aabb_geometry.sType = VK_STRUCTURE_TYPE_GEOMETRY_NV;
aabb_geometry.geometryType = VK_GEOMETRY_TYPE_AABBS_NV;
aabb_geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV;
aabb_geometry.geometry.aabbs = {};
aabb_geometry.geometry.aabbs.sType = VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV;
// Buffer contents do not matter for this test.
aabb_geometry.geometry.aabbs.aabbData = geometry.geometry.triangles.vertexData;
aabb_geometry.geometry.aabbs.numAABBs = 1;
aabb_geometry.geometry.aabbs.offset = 0;
aabb_geometry.geometry.aabbs.stride = 24;
std::vector<VkGeometryNV> geometries = {geometry, aabb_geometry};
VkAccelerationStructureCreateInfoNV mix_geometry_types_as_create_info = as_create_info;
mix_geometry_types_as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
mix_geometry_types_as_create_info.info.instanceCount = 0;
mix_geometry_types_as_create_info.info.geometryCount = static_cast<uint32_t>(geometries.size());
mix_geometry_types_as_create_info.info.pGeometries = geometries.data();
mix_geometry_types_as_create_info.info.flags = 0;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, "VUID-VkAccelerationStructureInfoNV-type-02786");
vkCreateAccelerationStructureNV(m_device->handle(), &mix_geometry_types_as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateCreateAccelerationStructureKHR) {
TEST_DESCRIPTION("Validate acceleration structure creation.");
if (!InitFrameworkForRayTracingTest(this, true, m_instance_extension_names, m_device_extension_names, m_errorMonitor, false,
false, true)) {
return;
}
auto ray_tracing_features = lvl_init_struct<VkPhysicalDeviceRayTracingFeaturesKHR>();
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&ray_tracing_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (ray_tracing_features.rayQuery == VK_FALSE && ray_tracing_features.rayTracing == VK_FALSE) {
printf("%s Both of the required features rayQuery and rayTracing are not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &ray_tracing_features));
PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR = reinterpret_cast<PFN_vkCreateAccelerationStructureKHR>(
vk::GetDeviceProcAddr(m_device->handle(), "vkCreateAccelerationStructureKHR"));
assert(vkCreateAccelerationStructureKHR != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
// Get an NV geometry in the helper, then pull out the bits we need for Create
VkGeometryNV geometryNV;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometryNV);
VkAccelerationStructureCreateGeometryTypeInfoKHR geometryInfo = {};
geometryInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_GEOMETRY_TYPE_INFO_KHR;
geometryInfo.geometryType = geometryNV.geometryType;
geometryInfo.maxPrimitiveCount = 1024;
geometryInfo.indexType = geometryNV.geometry.triangles.indexType;
geometryInfo.maxVertexCount = 1024;
geometryInfo.vertexFormat = geometryNV.geometry.triangles.vertexFormat;
geometryInfo.allowsTransforms = VK_TRUE;
VkAccelerationStructureCreateInfoKHR as_create_info = {};
as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR;
VkAccelerationStructureKHR as = VK_NULL_HANDLE;
// Top level can not have geometry
{
VkAccelerationStructureCreateInfoKHR bad_top_level_create_info = as_create_info;
bad_top_level_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
bad_top_level_create_info.maxGeometryCount = 1;
bad_top_level_create_info.pGeometryInfos = &geometryInfo;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, "VUID-VkAccelerationStructureCreateInfoKHR-type-03496");
vkCreateAccelerationStructureKHR(m_device->handle(), &bad_top_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// If type is VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR
// and compactedSize is 0, maxGeometryCount must be 1
// also tests If compactedSize is 0 then maxGeometryCount must not be 0
{
VkAccelerationStructureCreateInfoKHR bad_top_level_create_info = as_create_info;
bad_top_level_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
bad_top_level_create_info.maxGeometryCount = 0;
bad_top_level_create_info.compactedSize = 0;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,
"VUID-VkAccelerationStructureCreateInfoKHR-compactedSize-02993");
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, "VUID-VkAccelerationStructureCreateInfoKHR-type-03495");
vkCreateAccelerationStructureKHR(m_device->handle(), &bad_top_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Bot level can not have instances
{
VkAccelerationStructureCreateInfoKHR bad_bot_level_create_info = as_create_info;
bad_bot_level_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
bad_bot_level_create_info.maxGeometryCount = 1;
VkAccelerationStructureCreateGeometryTypeInfoKHR geometryInfo2 = geometryInfo;
geometryInfo2.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
bad_bot_level_create_info.pGeometryInfos = &geometryInfo2;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, "VUID-VkAccelerationStructureCreateInfoKHR-type-03497");
vkCreateAccelerationStructureKHR(m_device->handle(), &bad_bot_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Can not prefer both fast trace and fast build
{
VkAccelerationStructureCreateInfoKHR bad_flags_level_create_info = as_create_info;
bad_flags_level_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
bad_flags_level_create_info.maxGeometryCount = 1;
bad_flags_level_create_info.pGeometryInfos = &geometryInfo;
bad_flags_level_create_info.flags =
VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,
"VUID-VkAccelerationStructureCreateInfoKHR-flags-03499");
vkCreateAccelerationStructureKHR(m_device->handle(), &bad_flags_level_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Can not have geometry or instance for compacting
{
VkAccelerationStructureCreateInfoKHR bad_compacting_as_create_info = as_create_info;
bad_compacting_as_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
bad_compacting_as_create_info.maxGeometryCount = 1;
bad_compacting_as_create_info.pGeometryInfos = &geometryInfo;
bad_compacting_as_create_info.flags = 0;
bad_compacting_as_create_info.compactedSize = 1024;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,
"VUID-VkAccelerationStructureCreateInfoKHR-compactedSize-03490");
vkCreateAccelerationStructureKHR(m_device->handle(), &bad_compacting_as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// Can not mix different geometry types into single bottom level acceleration structure
{
VkAccelerationStructureCreateGeometryTypeInfoKHR aabb_geometry = {};
aabb_geometry = geometryInfo;
aabb_geometry.geometryType = VK_GEOMETRY_TYPE_AABBS_KHR;
std::vector<VkAccelerationStructureCreateGeometryTypeInfoKHR> geometries = {geometryInfo, aabb_geometry};
VkAccelerationStructureCreateInfoKHR mix_geometry_types_as_create_info = as_create_info;
mix_geometry_types_as_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
mix_geometry_types_as_create_info.maxGeometryCount = static_cast<uint32_t>(geometries.size());
mix_geometry_types_as_create_info.pGeometryInfos = geometries.data();
mix_geometry_types_as_create_info.flags = 0;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, "VUID-VkAccelerationStructureCreateInfoKHR-type-03498");
vkCreateAccelerationStructureKHR(m_device->handle(), &mix_geometry_types_as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// If geometryType is VK_GEOMETRY_TYPE_TRIANGLES_KHR, indexType must be
// VK_INDEX_TYPE_UINT16, VK_INDEX_TYPE_UINT32, or VK_INDEX_TYPE_NONE_KHR
{
VkAccelerationStructureCreateGeometryTypeInfoKHR invalid_index = geometryInfo;
invalid_index.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR;
invalid_index.indexType = VK_INDEX_TYPE_UINT8_EXT;
VkAccelerationStructureCreateInfoKHR invalid_index_geometry_types_as_create_info = as_create_info;
invalid_index_geometry_types_as_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
invalid_index_geometry_types_as_create_info.pGeometryInfos = &invalid_index;
invalid_index_geometry_types_as_create_info.maxGeometryCount = 1;
invalid_index_geometry_types_as_create_info.flags = 0;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,
"VUID-VkAccelerationStructureCreateGeometryTypeInfoKHR-geometryType-03502");
vkCreateAccelerationStructureKHR(m_device->handle(), &invalid_index_geometry_types_as_create_info, nullptr, &as);
m_errorMonitor->VerifyFound();
}
// flags must be a valid combination of VkBuildAccelerationStructureFlagBitsNV
{
VkAccelerationStructureCreateInfoKHR invalid_flag = as_create_info;
invalid_flag.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
invalid_flag.flags = VK_BUILD_ACCELERATION_STRUCTURE_FLAG_BITS_MAX_ENUM_KHR;
invalid_flag.pGeometryInfos = &geometryInfo;
invalid_flag.maxGeometryCount = 1;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,
"VUID-VkAccelerationStructureCreateInfoKHR-flags-parameter");
vkCreateAccelerationStructureKHR(m_device->handle(), &invalid_flag, nullptr, &as);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateBindAccelerationStructureNV) {
TEST_DESCRIPTION("Validate acceleration structure binding.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
PFN_vkBindAccelerationStructureMemoryNV vkBindAccelerationStructureMemoryNV =
reinterpret_cast<PFN_vkBindAccelerationStructureMemoryNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkBindAccelerationStructureMemoryNV"));
assert(vkBindAccelerationStructureMemoryNV != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
VkGeometryNV geometry;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometry);
VkAccelerationStructureCreateInfoNV as_create_info = {};
as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
as_create_info.info.geometryCount = 1;
as_create_info.info.pGeometries = &geometry;
as_create_info.info.instanceCount = 0;
VkAccelerationStructureObj as(*m_device, as_create_info, false);
m_errorMonitor->VerifyNotFound();
VkMemoryRequirements as_memory_requirements = as.memory_requirements().memoryRequirements;
VkBindAccelerationStructureMemoryInfoNV as_bind_info = {};
as_bind_info.sType = VK_STRUCTURE_TYPE_BIND_ACCELERATION_STRUCTURE_MEMORY_INFO_NV;
as_bind_info.accelerationStructure = as.handle();
VkMemoryAllocateInfo as_memory_alloc = {};
as_memory_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
as_memory_alloc.allocationSize = as_memory_requirements.size;
ASSERT_TRUE(m_device->phy().set_memory_type(as_memory_requirements.memoryTypeBits, &as_memory_alloc, 0));
// Can not bind already freed memory
{
VkDeviceMemory as_memory_freed = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc, NULL, &as_memory_freed));
vk::FreeMemory(device(), as_memory_freed, NULL);
VkBindAccelerationStructureMemoryInfoNV as_bind_info_freed = as_bind_info;
as_bind_info_freed.memory = as_memory_freed;
as_bind_info_freed.memoryOffset = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindAccelerationStructureMemoryInfoKHR-memory-parameter");
(void)vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_freed);
m_errorMonitor->VerifyFound();
}
// Can not bind with bad alignment
if (as_memory_requirements.alignment > 1) {
VkMemoryAllocateInfo as_memory_alloc_bad_alignment = as_memory_alloc;
as_memory_alloc_bad_alignment.allocationSize += 1;
VkDeviceMemory as_memory_bad_alignment = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc_bad_alignment, NULL, &as_memory_bad_alignment));
VkBindAccelerationStructureMemoryInfoNV as_bind_info_bad_alignment = as_bind_info;
as_bind_info_bad_alignment.memory = as_memory_bad_alignment;
as_bind_info_bad_alignment.memoryOffset = 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindAccelerationStructureMemoryInfoKHR-memoryOffset-02594");
(void)vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_bad_alignment);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), as_memory_bad_alignment, NULL);
}
// Can not bind with offset outside the allocation
{
VkDeviceMemory as_memory_bad_offset = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc, NULL, &as_memory_bad_offset));
VkBindAccelerationStructureMemoryInfoNV as_bind_info_bad_offset = as_bind_info;
as_bind_info_bad_offset.memory = as_memory_bad_offset;
as_bind_info_bad_offset.memoryOffset =
(as_memory_alloc.allocationSize + as_memory_requirements.alignment) & ~(as_memory_requirements.alignment - 1);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindAccelerationStructureMemoryInfoKHR-memoryOffset-02451");
(void)vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_bad_offset);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), as_memory_bad_offset, NULL);
}
// Can not bind with offset that doesn't leave enough size
{
VkDeviceSize offset = (as_memory_requirements.size - 1) & ~(as_memory_requirements.alignment - 1);
if (offset > 0 && (as_memory_requirements.size < (as_memory_alloc.allocationSize - as_memory_requirements.alignment))) {
VkDeviceMemory as_memory_bad_offset = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc, NULL, &as_memory_bad_offset));
VkBindAccelerationStructureMemoryInfoNV as_bind_info_bad_offset = as_bind_info;
as_bind_info_bad_offset.memory = as_memory_bad_offset;
as_bind_info_bad_offset.memoryOffset = offset;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindAccelerationStructureMemoryInfoKHR-size-02595");
(void)vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_bad_offset);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), as_memory_bad_offset, NULL);
}
}
// Can not bind with memory that has unsupported memory type
{
VkPhysicalDeviceMemoryProperties memory_properties = {};
vk::GetPhysicalDeviceMemoryProperties(m_device->phy().handle(), &memory_properties);
uint32_t supported_memory_type_bits = as_memory_requirements.memoryTypeBits;
uint32_t unsupported_mem_type_bits = ((1 << memory_properties.memoryTypeCount) - 1) & ~supported_memory_type_bits;
if (unsupported_mem_type_bits != 0) {
VkMemoryAllocateInfo as_memory_alloc_bad_type = as_memory_alloc;
ASSERT_TRUE(m_device->phy().set_memory_type(unsupported_mem_type_bits, &as_memory_alloc_bad_type, 0));
VkDeviceMemory as_memory_bad_type = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc_bad_type, NULL, &as_memory_bad_type));
VkBindAccelerationStructureMemoryInfoNV as_bind_info_bad_type = as_bind_info;
as_bind_info_bad_type.memory = as_memory_bad_type;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindAccelerationStructureMemoryInfoKHR-memory-02593");
(void)vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_bad_type);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), as_memory_bad_type, NULL);
}
}
// Can not bind memory twice
{
VkAccelerationStructureObj as_twice(*m_device, as_create_info, false);
VkDeviceMemory as_memory_twice_1 = VK_NULL_HANDLE;
VkDeviceMemory as_memory_twice_2 = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc, NULL, &as_memory_twice_1));
ASSERT_VK_SUCCESS(vk::AllocateMemory(device(), &as_memory_alloc, NULL, &as_memory_twice_2));
VkBindAccelerationStructureMemoryInfoNV as_bind_info_twice_1 = as_bind_info;
VkBindAccelerationStructureMemoryInfoNV as_bind_info_twice_2 = as_bind_info;
as_bind_info_twice_1.accelerationStructure = as_twice.handle();
as_bind_info_twice_2.accelerationStructure = as_twice.handle();
as_bind_info_twice_1.memory = as_memory_twice_1;
as_bind_info_twice_2.memory = as_memory_twice_2;
ASSERT_VK_SUCCESS(vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_twice_1));
m_errorMonitor->VerifyNotFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit,
"VUID-VkBindAccelerationStructureMemoryInfoKHR-accelerationStructure-02450");
(void)vkBindAccelerationStructureMemoryNV(device(), 1, &as_bind_info_twice_2);
m_errorMonitor->VerifyFound();
vk::FreeMemory(device(), as_memory_twice_1, NULL);
vk::FreeMemory(device(), as_memory_twice_2, NULL);
}
}
TEST_F(VkLayerTest, ValidateWriteDescriptorSetAccelerationStructureNV) {
TEST_DESCRIPTION("Validate acceleration structure descriptor writing.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
OneOffDescriptorSet ds(m_device,
{
{0, VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, 1, VK_SHADER_STAGE_RAYGEN_BIT_NV, nullptr},
});
VkWriteDescriptorSet descriptor_write = {};
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = ds.set_;
descriptor_write.dstBinding = 0;
descriptor_write.descriptorCount = 1;
descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV;
VkAccelerationStructureNV badHandle = (VkAccelerationStructureNV)12345678;
VkWriteDescriptorSetAccelerationStructureKHR acc = {};
acc.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_NV;
acc.accelerationStructureCount = 1;
acc.pAccelerationStructures = &badHandle;
descriptor_write.pNext = &acc;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit,
"VUID-VkWriteDescriptorSetAccelerationStructureKHR-pAccelerationStructures-parameter");
vk::UpdateDescriptorSets(m_device->device(), 1, &descriptor_write, 0, NULL);
m_errorMonitor->VerifyFound();
VkAccelerationStructureCreateInfoNV top_level_as_create_info = {};
top_level_as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
top_level_as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
top_level_as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV;
top_level_as_create_info.info.instanceCount = 1;
top_level_as_create_info.info.geometryCount = 0;
VkAccelerationStructureObj top_level_as(*m_device, top_level_as_create_info);
acc.pAccelerationStructures = &top_level_as.handle();
m_errorMonitor->ExpectSuccess();
vk::UpdateDescriptorSets(m_device->device(), 1, &descriptor_write, 0, NULL);
m_errorMonitor->VerifyNotFound();
}
TEST_F(VkLayerTest, ValidateCmdBuildAccelerationStructureNV) {
TEST_DESCRIPTION("Validate acceleration structure building.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
PFN_vkCmdBuildAccelerationStructureNV vkCmdBuildAccelerationStructureNV =
reinterpret_cast<PFN_vkCmdBuildAccelerationStructureNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkCmdBuildAccelerationStructureNV"));
assert(vkCmdBuildAccelerationStructureNV != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
VkGeometryNV geometry;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometry);
VkAccelerationStructureCreateInfoNV bot_level_as_create_info = {};
bot_level_as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
bot_level_as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
bot_level_as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
bot_level_as_create_info.info.instanceCount = 0;
bot_level_as_create_info.info.geometryCount = 1;
bot_level_as_create_info.info.pGeometries = &geometry;
VkAccelerationStructureObj bot_level_as(*m_device, bot_level_as_create_info);
m_errorMonitor->VerifyNotFound();
VkBufferObj bot_level_as_scratch;
bot_level_as.create_scratch_buffer(*m_device, &bot_level_as_scratch);
// Command buffer must be in recording state
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-commandBuffer-recording");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
m_commandBuffer->begin();
// Incompatible type
VkAccelerationStructureInfoNV as_build_info_with_incompatible_type = bot_level_as_create_info.info;
as_build_info_with_incompatible_type.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV;
as_build_info_with_incompatible_type.instanceCount = 1;
as_build_info_with_incompatible_type.geometryCount = 0;
// This is duplicated since it triggers one error for different types and one error for lower instance count - the
// build info is incompatible but still needs to be valid to get past the stateless checks.
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &as_build_info_with_incompatible_type, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// Incompatible flags
VkAccelerationStructureInfoNV as_build_info_with_incompatible_flags = bot_level_as_create_info.info;
as_build_info_with_incompatible_flags.flags = VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_NV;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &as_build_info_with_incompatible_flags, VK_NULL_HANDLE, 0,
VK_FALSE, bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// Incompatible build size
VkGeometryNV geometry_with_more_vertices = geometry;
geometry_with_more_vertices.geometry.triangles.vertexCount += 1;
VkAccelerationStructureInfoNV as_build_info_with_incompatible_geometry = bot_level_as_create_info.info;
as_build_info_with_incompatible_geometry.pGeometries = &geometry_with_more_vertices;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &as_build_info_with_incompatible_geometry, VK_NULL_HANDLE, 0,
VK_FALSE, bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// Scratch buffer too small
VkBufferCreateInfo too_small_scratch_buffer_info = {};
too_small_scratch_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
too_small_scratch_buffer_info.usage = VK_BUFFER_USAGE_RAY_TRACING_BIT_NV;
too_small_scratch_buffer_info.size = 1;
VkBufferObj too_small_scratch_buffer(*m_device, too_small_scratch_buffer_info);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-update-02491");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, too_small_scratch_buffer.handle(), 0);
m_errorMonitor->VerifyFound();
// Scratch buffer with offset too small
VkDeviceSize scratch_buffer_offset = 5;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-update-02491");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), scratch_buffer_offset);
m_errorMonitor->VerifyFound();
// Src must have been built before
VkAccelerationStructureObj bot_level_as_updated(*m_device, bot_level_as_create_info);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-update-02489");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_TRUE,
bot_level_as_updated.handle(), bot_level_as.handle(), bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// Src must have been built before with the VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_NV flag
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyNotFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-update-02489");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_TRUE,
bot_level_as_updated.handle(), bot_level_as.handle(), bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// invalid scratch buff
VkBufferObj bot_level_as_invalid_scratch;
VkBufferCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
// invalid usage
create_info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR;
bot_level_as.create_scratch_buffer(*m_device, &bot_level_as_invalid_scratch, &create_info);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureInfoNV-scratch-02781");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_invalid_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// invalid instance data.
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureInfoNV-instanceData-02782");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info,
bot_level_as_invalid_scratch.handle(), 0, VK_FALSE, bot_level_as.handle(), VK_NULL_HANDLE,
bot_level_as_scratch.handle(), 0);
m_errorMonitor->VerifyFound();
// must be called outside renderpass
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBuildAccelerationStructureNV-renderpass");
vkCmdBuildAccelerationStructureNV(m_commandBuffer->handle(), &bot_level_as_create_info.info, VK_NULL_HANDLE, 0, VK_FALSE,
bot_level_as.handle(), VK_NULL_HANDLE, bot_level_as_scratch.handle(), 0);
m_commandBuffer->EndRenderPass();
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, ValidateGetAccelerationStructureHandleNV) {
TEST_DESCRIPTION("Validate acceleration structure handle querying.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
PFN_vkGetAccelerationStructureHandleNV vkGetAccelerationStructureHandleNV =
reinterpret_cast<PFN_vkGetAccelerationStructureHandleNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkGetAccelerationStructureHandleNV"));
assert(vkGetAccelerationStructureHandleNV != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
VkGeometryNV geometry;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometry);
VkAccelerationStructureCreateInfoNV bot_level_as_create_info = {};
bot_level_as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
bot_level_as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
bot_level_as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
bot_level_as_create_info.info.instanceCount = 0;
bot_level_as_create_info.info.geometryCount = 1;
bot_level_as_create_info.info.pGeometries = &geometry;
// Not enough space for the handle
{
VkAccelerationStructureObj bot_level_as(*m_device, bot_level_as_create_info);
m_errorMonitor->VerifyNotFound();
uint64_t handle = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetAccelerationStructureHandleNV-dataSize-02240");
vkGetAccelerationStructureHandleNV(m_device->handle(), bot_level_as.handle(), sizeof(uint8_t), &handle);
m_errorMonitor->VerifyFound();
}
// No memory bound to acceleration structure
{
VkAccelerationStructureObj bot_level_as(*m_device, bot_level_as_create_info, /*init_memory=*/false);
m_errorMonitor->VerifyNotFound();
uint64_t handle = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "UNASSIGNED-vkGetAccelerationStructureHandleNV-accelerationStructure-XXXX");
vkGetAccelerationStructureHandleNV(m_device->handle(), bot_level_as.handle(), sizeof(uint64_t), &handle);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateCmdCopyAccelerationStructureNV) {
TEST_DESCRIPTION("Validate acceleration structure copying.");
if (!InitFrameworkForRayTracingTest(this, false, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
PFN_vkCmdCopyAccelerationStructureNV vkCmdCopyAccelerationStructureNV = reinterpret_cast<PFN_vkCmdCopyAccelerationStructureNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkCmdCopyAccelerationStructureNV"));
assert(vkCmdCopyAccelerationStructureNV != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
VkGeometryNV geometry;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometry);
VkAccelerationStructureCreateInfoNV as_create_info = {};
as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
as_create_info.info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
as_create_info.info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
as_create_info.info.instanceCount = 0;
as_create_info.info.geometryCount = 1;
as_create_info.info.pGeometries = &geometry;
VkAccelerationStructureObj src_as(*m_device, as_create_info);
VkAccelerationStructureObj dst_as(*m_device, as_create_info);
VkAccelerationStructureObj dst_as_without_mem(*m_device, as_create_info, false);
m_errorMonitor->VerifyNotFound();
// Command buffer must be in recording state
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyAccelerationStructureNV-commandBuffer-recording");
vkCmdCopyAccelerationStructureNV(m_commandBuffer->handle(), dst_as.handle(), src_as.handle(),
VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_NV);
m_errorMonitor->VerifyFound();
m_commandBuffer->begin();
// Src must have been created with allow compaction flag
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyAccelerationStructureNV-src-03411");
vkCmdCopyAccelerationStructureNV(m_commandBuffer->handle(), dst_as.handle(), src_as.handle(),
VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_NV);
m_errorMonitor->VerifyFound();
// Dst must have been bound with memory
m_errorMonitor->SetDesiredFailureMsg(kErrorBit,
"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkAccelerationStructureNV");
vkCmdCopyAccelerationStructureNV(m_commandBuffer->handle(), dst_as_without_mem.handle(), src_as.handle(),
VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_NV);
m_errorMonitor->VerifyFound();
// mode must be VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR or VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_KHR
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyAccelerationStructureNV-mode-03410");
vkCmdCopyAccelerationStructureNV(m_commandBuffer->handle(), dst_as.handle(), src_as.handle(),
VK_COPY_ACCELERATION_STRUCTURE_MODE_DESERIALIZE_KHR);
m_errorMonitor->VerifyFound();
// mode must be a valid VkCopyAccelerationStructureModeKHR value
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyAccelerationStructureNV-mode-parameter");
vkCmdCopyAccelerationStructureNV(m_commandBuffer->handle(), dst_as.handle(), src_as.handle(),
VK_COPY_ACCELERATION_STRUCTURE_MODE_MAX_ENUM_KHR);
m_errorMonitor->VerifyFound();
// This command must only be called outside of a render pass instance
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdCopyAccelerationStructureNV-renderpass");
vkCmdCopyAccelerationStructureNV(m_commandBuffer->handle(), dst_as.handle(), src_as.handle(),
VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_NV);
m_commandBuffer->EndRenderPass();
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, QueryPerformanceCreation) {
TEST_DESCRIPTION("Create performance query without support");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkPhysicalDeviceFeatures2KHR features2 = {};
auto performance_features = lvl_init_struct<VkPhysicalDevicePerformanceQueryFeaturesKHR>();
features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&performance_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!performance_features.performanceCounterQueryPools) {
printf("%s Performance query pools are not supported.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &performance_features));
PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR =
(PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)vk::GetInstanceProcAddr(
instance(), "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR");
ASSERT_TRUE(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR != nullptr);
auto queueFamilyProperties = m_device->phy().queue_properties();
uint32_t queueFamilyIndex = queueFamilyProperties.size();
std::vector<VkPerformanceCounterKHR> counters;
for (uint32_t idx = 0; idx < queueFamilyProperties.size(); idx++) {
uint32_t nCounters;
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, nullptr, nullptr);
if (nCounters == 0) continue;
counters.resize(nCounters);
for (auto &c : counters) {
c.sType = VK_STRUCTURE_TYPE_PERFORMANCE_COUNTER_KHR;
c.pNext = nullptr;
}
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, &counters[0], nullptr);
queueFamilyIndex = idx;
break;
}
if (counters.empty()) {
printf("%s No queue reported any performance counter.\n", kSkipPrefix);
return;
}
VkQueryPoolPerformanceCreateInfoKHR perf_query_pool_ci{};
perf_query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
perf_query_pool_ci.queueFamilyIndex = queueFamilyIndex;
perf_query_pool_ci.counterIndexCount = counters.size();
std::vector<uint32_t> counterIndices;
for (uint32_t c = 0; c < counters.size(); c++) counterIndices.push_back(c);
perf_query_pool_ci.pCounterIndices = &counterIndices[0];
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.queryType = VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
query_pool_ci.queryCount = 1;
// Missing pNext
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkQueryPoolCreateInfo-queryType-03222");
VkQueryPool query_pool;
vk::CreateQueryPool(m_device->device(), &query_pool_ci, nullptr, &query_pool);
m_errorMonitor->VerifyFound();
query_pool_ci.pNext = &perf_query_pool_ci;
// Invalid counter indices
counterIndices.push_back(counters.size());
perf_query_pool_ci.counterIndexCount++;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkQueryPoolPerformanceCreateInfoKHR-pCounterIndices-03321");
vk::CreateQueryPool(m_device->device(), &query_pool_ci, nullptr, &query_pool);
m_errorMonitor->VerifyFound();
perf_query_pool_ci.counterIndexCount--;
counterIndices.pop_back();
// Success
m_errorMonitor->ExpectSuccess(kErrorBit);
vk::CreateQueryPool(m_device->device(), &query_pool_ci, nullptr, &query_pool);
m_errorMonitor->VerifyNotFound();
m_commandBuffer->begin();
// Missing acquire lock
{
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryPool-03223");
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
m_errorMonitor->VerifyFound();
}
m_commandBuffer->end();
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
}
TEST_F(VkLayerTest, QueryPerformanceCounterCommandbufferScope) {
TEST_DESCRIPTION("Insert a performance query begin/end with respect to the command buffer counter scope");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkPhysicalDeviceFeatures2KHR features2 = {};
auto performanceFeatures = lvl_init_struct<VkPhysicalDevicePerformanceQueryFeaturesKHR>();
features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&performanceFeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!performanceFeatures.performanceCounterQueryPools) {
printf("%s Performance query pools are not supported.\n", kSkipPrefix);
return;
}
VkCommandPoolCreateFlags pool_flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &performanceFeatures, pool_flags));
PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR =
(PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)vk::GetInstanceProcAddr(
instance(), "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR");
ASSERT_TRUE(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR != nullptr);
auto queueFamilyProperties = m_device->phy().queue_properties();
uint32_t queueFamilyIndex = queueFamilyProperties.size();
std::vector<VkPerformanceCounterKHR> counters;
std::vector<uint32_t> counterIndices;
// Find a single counter with VK_QUERY_SCOPE_COMMAND_BUFFER_KHR scope.
for (uint32_t idx = 0; idx < queueFamilyProperties.size(); idx++) {
uint32_t nCounters;
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, nullptr, nullptr);
if (nCounters == 0) continue;
counters.resize(nCounters);
for (auto &c : counters) {
c.sType = VK_STRUCTURE_TYPE_PERFORMANCE_COUNTER_KHR;
c.pNext = nullptr;
}
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, &counters[0], nullptr);
queueFamilyIndex = idx;
for (uint32_t counterIdx = 0; counterIdx < counters.size(); counterIdx++) {
if (counters[counterIdx].scope == VK_QUERY_SCOPE_COMMAND_BUFFER_KHR) {
counterIndices.push_back(counterIdx);
break;
}
}
if (counterIndices.empty()) {
counters.clear();
continue;
}
break;
}
if (counterIndices.empty()) {
printf("%s No queue reported any performance counter with command buffer scope.\n", kSkipPrefix);
return;
}
VkQueryPoolPerformanceCreateInfoKHR perf_query_pool_ci{};
perf_query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
perf_query_pool_ci.queueFamilyIndex = queueFamilyIndex;
perf_query_pool_ci.counterIndexCount = counterIndices.size();
perf_query_pool_ci.pCounterIndices = &counterIndices[0];
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.pNext = &perf_query_pool_ci;
query_pool_ci.queryType = VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
query_pool_ci.queryCount = 1;
VkQueryPool query_pool;
vk::CreateQueryPool(device(), &query_pool_ci, nullptr, &query_pool);
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(device(), queueFamilyIndex, 0, &queue);
PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR =
(PFN_vkAcquireProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkAcquireProfilingLockKHR");
ASSERT_TRUE(vkAcquireProfilingLockKHR != nullptr);
PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR =
(PFN_vkReleaseProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkReleaseProfilingLockKHR");
ASSERT_TRUE(vkReleaseProfilingLockKHR != nullptr);
{
VkAcquireProfilingLockInfoKHR lock_info{};
lock_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_PROFILING_LOCK_INFO_KHR;
VkResult result = vkAcquireProfilingLockKHR(device(), &lock_info);
ASSERT_TRUE(result == VK_SUCCESS);
}
// Not the first command.
{
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkBuffer buffer;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
m_commandBuffer->begin();
vk::CmdFillBuffer(m_commandBuffer->handle(), buffer, 0, 4096, 0);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryPool-03224");
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
m_errorMonitor->VerifyFound();
m_commandBuffer->end();
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(queue);
vk::DestroyBuffer(device(), buffer, nullptr);
vk::FreeMemory(device(), mem, NULL);
}
// First command: success.
{
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkBuffer buffer;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
m_commandBuffer->begin();
m_errorMonitor->ExpectSuccess(kErrorBit);
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
m_errorMonitor->VerifyNotFound();
vk::CmdFillBuffer(m_commandBuffer->handle(), buffer, 0, 4096, 0);
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, 0);
m_commandBuffer->end();
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(queue);
vk::DestroyBuffer(device(), buffer, nullptr);
vk::FreeMemory(device(), mem, NULL);
}
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
vkReleaseProfilingLockKHR(device());
}
TEST_F(VkLayerTest, QueryPerformanceCounterRenderPassScope) {
TEST_DESCRIPTION("Insert a performance query begin/end with respect to the render pass counter scope");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkPhysicalDeviceFeatures2KHR features2 = {};
auto performanceFeatures = lvl_init_struct<VkPhysicalDevicePerformanceQueryFeaturesKHR>();
features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&performanceFeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!performanceFeatures.performanceCounterQueryPools) {
printf("%s Performance query pools are not supported.\n", kSkipPrefix);
return;
}
VkCommandPoolCreateFlags pool_flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, nullptr, pool_flags));
PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR =
(PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)vk::GetInstanceProcAddr(
instance(), "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR");
ASSERT_TRUE(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR != nullptr);
auto queueFamilyProperties = m_device->phy().queue_properties();
uint32_t queueFamilyIndex = queueFamilyProperties.size();
std::vector<VkPerformanceCounterKHR> counters;
std::vector<uint32_t> counterIndices;
// Find a single counter with VK_QUERY_SCOPE_RENDER_PASS_KHR scope.
for (uint32_t idx = 0; idx < queueFamilyProperties.size(); idx++) {
uint32_t nCounters;
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, nullptr, nullptr);
if (nCounters == 0) continue;
counters.resize(nCounters);
for (auto &c : counters) {
c.sType = VK_STRUCTURE_TYPE_PERFORMANCE_COUNTER_KHR;
c.pNext = nullptr;
}
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, &counters[0], nullptr);
queueFamilyIndex = idx;
for (uint32_t counterIdx = 0; counterIdx < counters.size(); counterIdx++) {
if (counters[counterIdx].scope == VK_QUERY_SCOPE_RENDER_PASS_KHR) {
counterIndices.push_back(counterIdx);
break;
}
}
if (counterIndices.empty()) {
counters.clear();
continue;
}
break;
}
if (counterIndices.empty()) {
printf("%s No queue reported any performance counter with render pass scope.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkQueryPoolPerformanceCreateInfoKHR perf_query_pool_ci{};
perf_query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
perf_query_pool_ci.queueFamilyIndex = queueFamilyIndex;
perf_query_pool_ci.counterIndexCount = counterIndices.size();
perf_query_pool_ci.pCounterIndices = &counterIndices[0];
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.pNext = &perf_query_pool_ci;
query_pool_ci.queryType = VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
query_pool_ci.queryCount = 1;
VkQueryPool query_pool;
vk::CreateQueryPool(device(), &query_pool_ci, nullptr, &query_pool);
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(device(), queueFamilyIndex, 0, &queue);
PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR =
(PFN_vkAcquireProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkAcquireProfilingLockKHR");
ASSERT_TRUE(vkAcquireProfilingLockKHR != nullptr);
PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR =
(PFN_vkReleaseProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkReleaseProfilingLockKHR");
ASSERT_TRUE(vkReleaseProfilingLockKHR != nullptr);
{
VkAcquireProfilingLockInfoKHR lock_info{};
lock_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_PROFILING_LOCK_INFO_KHR;
VkResult result = vkAcquireProfilingLockKHR(device(), &lock_info);
ASSERT_TRUE(result == VK_SUCCESS);
}
// Inside a render pass.
{
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdBeginQuery-queryPool-03225");
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
m_errorMonitor->VerifyFound();
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(queue);
}
vkReleaseProfilingLockKHR(device());
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
}
TEST_F(VkLayerTest, QueryPerformanceReleaseProfileLockBeforeSubmit) {
TEST_DESCRIPTION("Verify that we get an error if we release the profiling lock during the recording of performance queries");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkPhysicalDeviceFeatures2KHR features2 = {};
auto performanceFeatures = lvl_init_struct<VkPhysicalDevicePerformanceQueryFeaturesKHR>();
features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&performanceFeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!performanceFeatures.performanceCounterQueryPools) {
printf("%s Performance query pools are not supported.\n", kSkipPrefix);
return;
}
VkCommandPoolCreateFlags pool_flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &performanceFeatures, pool_flags));
PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR =
(PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)vk::GetInstanceProcAddr(
instance(), "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR");
ASSERT_TRUE(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR != nullptr);
auto queueFamilyProperties = m_device->phy().queue_properties();
uint32_t queueFamilyIndex = queueFamilyProperties.size();
std::vector<VkPerformanceCounterKHR> counters;
std::vector<uint32_t> counterIndices;
// Find a single counter with VK_QUERY_SCOPE_RENDER_PASS_KHR scope.
for (uint32_t idx = 0; idx < queueFamilyProperties.size(); idx++) {
uint32_t nCounters;
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, nullptr, nullptr);
if (nCounters == 0) continue;
counters.resize(nCounters);
for (auto &c : counters) {
c.sType = VK_STRUCTURE_TYPE_PERFORMANCE_COUNTER_KHR;
c.pNext = nullptr;
}
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, &counters[0], nullptr);
queueFamilyIndex = idx;
for (uint32_t counterIdx = 0; counterIdx < counters.size(); counterIdx++) {
counterIndices.push_back(counterIdx);
break;
}
if (counterIndices.empty()) {
counters.clear();
continue;
}
break;
}
if (counterIndices.empty()) {
printf("%s No queue reported any performance counter with render pass scope.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkQueryPoolPerformanceCreateInfoKHR perf_query_pool_ci{};
perf_query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
perf_query_pool_ci.queueFamilyIndex = queueFamilyIndex;
perf_query_pool_ci.counterIndexCount = counterIndices.size();
perf_query_pool_ci.pCounterIndices = &counterIndices[0];
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.pNext = &perf_query_pool_ci;
query_pool_ci.queryType = VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
query_pool_ci.queryCount = 1;
VkQueryPool query_pool;
vk::CreateQueryPool(device(), &query_pool_ci, nullptr, &query_pool);
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(device(), queueFamilyIndex, 0, &queue);
PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR =
(PFN_vkAcquireProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkAcquireProfilingLockKHR");
ASSERT_TRUE(vkAcquireProfilingLockKHR != nullptr);
PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR =
(PFN_vkReleaseProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkReleaseProfilingLockKHR");
ASSERT_TRUE(vkReleaseProfilingLockKHR != nullptr);
{
VkAcquireProfilingLockInfoKHR lock_info{};
lock_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_PROFILING_LOCK_INFO_KHR;
VkResult result = vkAcquireProfilingLockKHR(device(), &lock_info);
ASSERT_TRUE(result == VK_SUCCESS);
}
{
m_commandBuffer->reset();
m_commandBuffer->begin();
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
m_commandBuffer->end();
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(queue);
}
{
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkBuffer buffer;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
m_commandBuffer->reset();
m_commandBuffer->begin();
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
// Relase while recording.
vkReleaseProfilingLockKHR(device());
{
VkAcquireProfilingLockInfoKHR lock_info{};
lock_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_PROFILING_LOCK_INFO_KHR;
VkResult result = vkAcquireProfilingLockKHR(device(), &lock_info);
ASSERT_TRUE(result == VK_SUCCESS);
}
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, 0);
m_commandBuffer->end();
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkQueueSubmit-pCommandBuffers-03220");
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::QueueWaitIdle(queue);
vk::DestroyBuffer(device(), buffer, nullptr);
vk::FreeMemory(device(), mem, NULL);
}
vkReleaseProfilingLockKHR(device());
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
}
TEST_F(VkLayerTest, QueryPerformanceIncompletePasses) {
TEST_DESCRIPTION("Verify that we get an error if we don't submit a command buffer for each passes before getting the results.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
return;
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkPhysicalDeviceFeatures2KHR features2 = {};
auto hostQueryResetFeatures = lvl_init_struct<VkPhysicalDeviceHostQueryResetFeaturesEXT>();
auto performanceFeatures = lvl_init_struct<VkPhysicalDevicePerformanceQueryFeaturesKHR>(&hostQueryResetFeatures);
features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&performanceFeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!performanceFeatures.performanceCounterQueryPools) {
printf("%s Performance query pools are not supported.\n", kSkipPrefix);
return;
}
if (!hostQueryResetFeatures.hostQueryReset) {
printf("%s Missing host query reset.\n", kSkipPrefix);
return;
}
VkCommandPoolCreateFlags pool_flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &performanceFeatures, pool_flags));
PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR =
(PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)vk::GetInstanceProcAddr(
instance(), "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR");
ASSERT_TRUE(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR != nullptr);
PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR =
(PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR)vk::GetInstanceProcAddr(
instance(), "vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR");
ASSERT_TRUE(vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR != nullptr);
auto queueFamilyProperties = m_device->phy().queue_properties();
uint32_t queueFamilyIndex = queueFamilyProperties.size();
std::vector<VkPerformanceCounterKHR> counters;
std::vector<uint32_t> counterIndices;
uint32_t nPasses = 0;
// Find a single counter with VK_QUERY_SCOPE_RENDER_PASS_KHR scope.
for (uint32_t idx = 0; idx < queueFamilyProperties.size(); idx++) {
uint32_t nCounters;
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, nullptr, nullptr);
if (nCounters == 0) continue;
counters.resize(nCounters);
for (auto &c : counters) {
c.sType = VK_STRUCTURE_TYPE_PERFORMANCE_COUNTER_KHR;
c.pNext = nullptr;
}
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, &counters[0], nullptr);
queueFamilyIndex = idx;
for (uint32_t counterIdx = 0; counterIdx < counters.size(); counterIdx++) counterIndices.push_back(counterIdx);
VkQueryPoolPerformanceCreateInfoKHR create_info{};
create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
create_info.queueFamilyIndex = idx;
create_info.counterIndexCount = counterIndices.size();
create_info.pCounterIndices = &counterIndices[0];
vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(gpu(), &create_info, &nPasses);
if (nPasses < 2) {
counters.clear();
continue;
}
break;
}
if (counterIndices.empty()) {
printf("%s No queue reported a set of counters that needs more than one pass.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkQueryPoolPerformanceCreateInfoKHR perf_query_pool_ci{};
perf_query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
perf_query_pool_ci.queueFamilyIndex = queueFamilyIndex;
perf_query_pool_ci.counterIndexCount = counterIndices.size();
perf_query_pool_ci.pCounterIndices = &counterIndices[0];
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.pNext = &perf_query_pool_ci;
query_pool_ci.queryType = VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
query_pool_ci.queryCount = 1;
VkQueryPool query_pool;
vk::CreateQueryPool(device(), &query_pool_ci, nullptr, &query_pool);
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(device(), queueFamilyIndex, 0, &queue);
PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR =
(PFN_vkAcquireProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkAcquireProfilingLockKHR");
ASSERT_TRUE(vkAcquireProfilingLockKHR != nullptr);
PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR =
(PFN_vkReleaseProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkReleaseProfilingLockKHR");
ASSERT_TRUE(vkReleaseProfilingLockKHR != nullptr);
PFN_vkResetQueryPoolEXT fpvkResetQueryPoolEXT =
(PFN_vkResetQueryPoolEXT)vk::GetInstanceProcAddr(instance(), "vkResetQueryPoolEXT");
{
VkAcquireProfilingLockInfoKHR lock_info{};
lock_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_PROFILING_LOCK_INFO_KHR;
VkResult result = vkAcquireProfilingLockKHR(device(), &lock_info);
ASSERT_TRUE(result == VK_SUCCESS);
}
{
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkBuffer buffer;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
VkCommandBufferBeginInfo command_buffer_begin_info{};
command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
command_buffer_begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
fpvkResetQueryPoolEXT(m_device->device(), query_pool, 0, 1);
m_commandBuffer->begin(&command_buffer_begin_info);
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
vk::CmdFillBuffer(m_commandBuffer->handle(), buffer, 0, 4096, 0);
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, 0);
m_commandBuffer->end();
// Invalid pass index
{
VkPerformanceQuerySubmitInfoKHR perf_submit_info{};
perf_submit_info.sType = VK_STRUCTURE_TYPE_PERFORMANCE_QUERY_SUBMIT_INFO_KHR;
perf_submit_info.counterPassIndex = nPasses;
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &perf_submit_info;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkPerformanceQuerySubmitInfoKHR-counterPassIndex-03221");
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
// Leave the last pass out.
for (uint32_t passIdx = 0; passIdx < (nPasses - 1); passIdx++) {
VkPerformanceQuerySubmitInfoKHR perf_submit_info{};
perf_submit_info.sType = VK_STRUCTURE_TYPE_PERFORMANCE_QUERY_SUBMIT_INFO_KHR;
perf_submit_info.counterPassIndex = passIdx;
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &perf_submit_info;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
}
vk::QueueWaitIdle(queue);
std::vector<VkPerformanceCounterResultKHR> results;
results.resize(counterIndices.size());
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-queryType-03231");
vk::GetQueryPoolResults(device(), query_pool, 0, 1, sizeof(VkPerformanceCounterResultKHR) * results.size(), &results[0],
sizeof(VkPerformanceCounterResultKHR), VK_QUERY_RESULT_WAIT_BIT);
m_errorMonitor->VerifyFound();
{
VkPerformanceQuerySubmitInfoKHR perf_submit_info{};
perf_submit_info.sType = VK_STRUCTURE_TYPE_PERFORMANCE_QUERY_SUBMIT_INFO_KHR;
perf_submit_info.counterPassIndex = nPasses - 1;
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &perf_submit_info;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
}
vk::QueueWaitIdle(queue);
// Invalid stride
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-queryType-03229");
vk::GetQueryPoolResults(device(), query_pool, 0, 1, sizeof(VkPerformanceCounterResultKHR) * results.size(), &results[0],
sizeof(VkPerformanceCounterResultKHR) + 4, VK_QUERY_RESULT_WAIT_BIT);
m_errorMonitor->VerifyFound();
// Invalid flags
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-queryType-03230");
vk::GetQueryPoolResults(device(), query_pool, 0, 1, sizeof(VkPerformanceCounterResultKHR) * results.size(), &results[0],
sizeof(VkPerformanceCounterResultKHR), VK_QUERY_RESULT_WITH_AVAILABILITY_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-queryType-03230");
vk::GetQueryPoolResults(device(), query_pool, 0, 1, sizeof(VkPerformanceCounterResultKHR) * results.size(), &results[0],
sizeof(VkPerformanceCounterResultKHR), VK_QUERY_RESULT_PARTIAL_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetQueryPoolResults-queryType-03230");
vk::GetQueryPoolResults(device(), query_pool, 0, 1, sizeof(VkPerformanceCounterResultKHR) * results.size(), &results[0],
sizeof(VkPerformanceCounterResultKHR), VK_QUERY_RESULT_64_BIT);
m_errorMonitor->VerifyFound();
m_errorMonitor->ExpectSuccess(kErrorBit);
vk::GetQueryPoolResults(device(), query_pool, 0, 1, sizeof(VkPerformanceCounterResultKHR) * results.size(), &results[0],
sizeof(VkPerformanceCounterResultKHR), VK_QUERY_RESULT_WAIT_BIT);
m_errorMonitor->VerifyNotFound();
vk::DestroyBuffer(device(), buffer, nullptr);
vk::FreeMemory(device(), mem, NULL);
}
vkReleaseProfilingLockKHR(device());
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
}
TEST_F(VkLayerTest, QueryPerformanceResetAndBegin) {
TEST_DESCRIPTION("Verify that we get an error if we reset & begin a performance query within the same primary command buffer.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME);
return;
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkPhysicalDeviceFeatures2KHR features2 = {};
auto hostQueryResetFeatures = lvl_init_struct<VkPhysicalDeviceHostQueryResetFeaturesEXT>();
auto performanceFeatures = lvl_init_struct<VkPhysicalDevicePerformanceQueryFeaturesKHR>(&hostQueryResetFeatures);
features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&performanceFeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!performanceFeatures.performanceCounterQueryPools) {
printf("%s Performance query pools are not supported.\n", kSkipPrefix);
return;
}
if (!hostQueryResetFeatures.hostQueryReset) {
printf("%s Missing host query reset.\n", kSkipPrefix);
return;
}
VkCommandPoolCreateFlags pool_flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &performanceFeatures, pool_flags));
PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR =
(PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)vk::GetInstanceProcAddr(
instance(), "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR");
ASSERT_TRUE(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR != nullptr);
PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR =
(PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR)vk::GetInstanceProcAddr(
instance(), "vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR");
ASSERT_TRUE(vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR != nullptr);
auto queueFamilyProperties = m_device->phy().queue_properties();
uint32_t queueFamilyIndex = queueFamilyProperties.size();
std::vector<VkPerformanceCounterKHR> counters;
std::vector<uint32_t> counterIndices;
uint32_t nPasses = 0;
// Find a single counter with VK_QUERY_SCOPE_RENDER_PASS_KHR scope.
for (uint32_t idx = 0; idx < queueFamilyProperties.size(); idx++) {
uint32_t nCounters;
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, nullptr, nullptr);
if (nCounters == 0) continue;
counters.resize(nCounters);
for (auto &c : counters) {
c.sType = VK_STRUCTURE_TYPE_PERFORMANCE_COUNTER_KHR;
c.pNext = nullptr;
}
vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(gpu(), idx, &nCounters, &counters[0], nullptr);
queueFamilyIndex = idx;
for (uint32_t counterIdx = 0; counterIdx < counters.size(); counterIdx++) counterIndices.push_back(counterIdx);
VkQueryPoolPerformanceCreateInfoKHR create_info{};
create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
create_info.queueFamilyIndex = idx;
create_info.counterIndexCount = counterIndices.size();
create_info.pCounterIndices = &counterIndices[0];
vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(gpu(), &create_info, &nPasses);
if (nPasses < 2) {
counters.clear();
continue;
}
break;
}
if (counterIndices.empty()) {
printf("%s No queue reported a set of counters that needs more than one pass.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkQueryPoolPerformanceCreateInfoKHR perf_query_pool_ci{};
perf_query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR;
perf_query_pool_ci.queueFamilyIndex = queueFamilyIndex;
perf_query_pool_ci.counterIndexCount = counterIndices.size();
perf_query_pool_ci.pCounterIndices = &counterIndices[0];
VkQueryPoolCreateInfo query_pool_ci{};
query_pool_ci.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
query_pool_ci.pNext = &perf_query_pool_ci;
query_pool_ci.queryType = VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
query_pool_ci.queryCount = 1;
VkQueryPool query_pool;
vk::CreateQueryPool(device(), &query_pool_ci, nullptr, &query_pool);
VkQueue queue = VK_NULL_HANDLE;
vk::GetDeviceQueue(device(), queueFamilyIndex, 0, &queue);
PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR =
(PFN_vkAcquireProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkAcquireProfilingLockKHR");
ASSERT_TRUE(vkAcquireProfilingLockKHR != nullptr);
PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR =
(PFN_vkReleaseProfilingLockKHR)vk::GetInstanceProcAddr(instance(), "vkReleaseProfilingLockKHR");
ASSERT_TRUE(vkReleaseProfilingLockKHR != nullptr);
{
VkAcquireProfilingLockInfoKHR lock_info{};
lock_info.sType = VK_STRUCTURE_TYPE_ACQUIRE_PROFILING_LOCK_INFO_KHR;
VkResult result = vkAcquireProfilingLockKHR(device(), &lock_info);
ASSERT_TRUE(result == VK_SUCCESS);
}
{
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkBuffer buffer;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
VkCommandBufferBeginInfo command_buffer_begin_info{};
command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
command_buffer_begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, "VUID-vkCmdBeginQuery-None-02863");
m_commandBuffer->reset();
m_commandBuffer->begin(&command_buffer_begin_info);
vk::CmdResetQueryPool(m_commandBuffer->handle(), query_pool, 0, 1);
vk::CmdBeginQuery(m_commandBuffer->handle(), query_pool, 0, 0);
vk::CmdEndQuery(m_commandBuffer->handle(), query_pool, 0);
m_commandBuffer->end();
{
VkPerformanceQuerySubmitInfoKHR perf_submit_info{};
perf_submit_info.sType = VK_STRUCTURE_TYPE_PERFORMANCE_QUERY_SUBMIT_INFO_KHR;
perf_submit_info.counterPassIndex = nPasses - 1;
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &perf_submit_info;
submit_info.waitSemaphoreCount = 0;
submit_info.pWaitSemaphores = NULL;
submit_info.pWaitDstStageMask = NULL;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &m_commandBuffer->handle();
submit_info.signalSemaphoreCount = 0;
submit_info.pSignalSemaphores = NULL;
vk::QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
}
vk::QueueWaitIdle(queue);
m_errorMonitor->VerifyFound();
vk::DestroyBuffer(device(), buffer, nullptr);
vk::FreeMemory(device(), mem, NULL);
}
vkReleaseProfilingLockKHR(device());
vk::DestroyQueryPool(m_device->device(), query_pool, NULL);
}
TEST_F(VkLayerTest, QueueSubmitNoTimelineSemaphoreInfo) {
TEST_DESCRIPTION("Submit a queue with a timeline semaphore but not a VkTimelineSemaphoreSubmitInfoKHR.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo submit_info[2] = {};
submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[0].commandBufferCount = 0;
submit_info[0].pWaitDstStageMask = &stageFlags;
submit_info[0].signalSemaphoreCount = 1;
submit_info[0].pSignalSemaphores = &semaphore;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pWaitSemaphores-03239");
vk::QueueSubmit(m_device->m_queue, 1, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
VkTimelineSemaphoreSubmitInfoKHR timeline_semaphore_submit_info{};
uint64_t signalValue = 1;
timeline_semaphore_submit_info.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR;
timeline_semaphore_submit_info.signalSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pSignalSemaphoreValues = &signalValue;
submit_info[0].pNext = &timeline_semaphore_submit_info;
submit_info[1].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[1].commandBufferCount = 0;
submit_info[1].pWaitDstStageMask = &stageFlags;
submit_info[1].waitSemaphoreCount = 1;
submit_info[1].pWaitSemaphores = &semaphore;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pWaitSemaphores-03239");
vk::QueueSubmit(m_device->m_queue, 2, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
}
TEST_F(VkLayerTest, QueueSubmitTimelineSemaphoreBadValue) {
TEST_DESCRIPTION("Submit a queue with a timeline semaphore using a wrong payload value.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
auto timelineproperties = lvl_init_struct<VkPhysicalDeviceTimelineSemaphorePropertiesKHR>();
auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&timelineproperties);
vkGetPhysicalDeviceProperties2KHR(gpu(), &prop2);
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkTimelineSemaphoreSubmitInfoKHR timeline_semaphore_submit_info = {};
uint64_t signalValue = 1;
uint64_t waitValue = 3;
timeline_semaphore_submit_info.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR;
timeline_semaphore_submit_info.signalSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pSignalSemaphoreValues = &signalValue;
timeline_semaphore_submit_info.waitSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pWaitSemaphoreValues = &waitValue;
VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo submit_info[2] = {};
submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[0].pNext = &timeline_semaphore_submit_info;
submit_info[0].pWaitDstStageMask = &stageFlags;
submit_info[0].signalSemaphoreCount = 1;
submit_info[0].pSignalSemaphores = &semaphore;
submit_info[1].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[1].pNext = &timeline_semaphore_submit_info;
submit_info[1].pWaitDstStageMask = &stageFlags;
submit_info[1].waitSemaphoreCount = 1;
submit_info[1].pWaitSemaphores = &semaphore;
timeline_semaphore_submit_info.signalSemaphoreValueCount = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pNext-03241");
vk::QueueSubmit(m_device->m_queue, 1, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
timeline_semaphore_submit_info.signalSemaphoreValueCount = 1;
timeline_semaphore_submit_info.waitSemaphoreValueCount = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pNext-03240");
vk::QueueSubmit(m_device->m_queue, 2, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
timeline_semaphore_submit_info.waitSemaphoreValueCount = 1;
semaphore_type_create_info.initialValue = 5;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pSignalSemaphores-03242");
vk::QueueSubmit(m_device->m_queue, 1, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
// Check if we can test violations of maxTimelineSemaphoreValueDifference
if (timelineproperties.maxTimelineSemaphoreValueDifference < UINT64_MAX) {
semaphore_type_create_info.initialValue = 0;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
signalValue = timelineproperties.maxTimelineSemaphoreValueDifference + 1;
timeline_semaphore_submit_info.pSignalSemaphoreValues = &signalValue;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pSignalSemaphores-03244");
vk::QueueSubmit(m_device->m_queue, 1, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
if (signalValue < UINT64_MAX) {
waitValue = signalValue + 1;
signalValue = 1;
timeline_semaphore_submit_info.waitSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pWaitSemaphoreValues = &waitValue;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSubmitInfo-pWaitSemaphores-03243");
vk::QueueSubmit(m_device->m_queue, 2, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
}
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
}
}
TEST_F(VkLayerTest, QueueSubmitBinarySemaphoreNotSignaled) {
TEST_DESCRIPTION("Submit a queue with a waiting binary semaphore not previously signaled.");
bool timelineSemaphoresExtensionSupported = true;
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
timelineSemaphoresExtensionSupported = false;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (timelineSemaphoresExtensionSupported &&
DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
timelineSemaphoresExtensionSupported = false;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore[3];
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore[0]));
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore[1]));
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore[2]));
VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo submit_info[3] = {};
submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[0].pWaitDstStageMask = &stageFlags;
submit_info[0].waitSemaphoreCount = 1;
submit_info[0].pWaitSemaphores = &(semaphore[0]);
submit_info[0].signalSemaphoreCount = 1;
submit_info[0].pSignalSemaphores = &(semaphore[1]);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, timelineSemaphoresExtensionSupported
? "VUID-vkQueueSubmit-pWaitSemaphores-03238"
: "VUID-vkQueueSubmit-pWaitSemaphores-00069");
vk::QueueSubmit(m_device->m_queue, 1, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
submit_info[1].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[1].pWaitDstStageMask = &stageFlags;
submit_info[1].waitSemaphoreCount = 1;
submit_info[1].pWaitSemaphores = &(semaphore[1]);
submit_info[1].signalSemaphoreCount = 1;
submit_info[1].pSignalSemaphores = &(semaphore[2]);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, timelineSemaphoresExtensionSupported
? "VUID-vkQueueSubmit-pWaitSemaphores-03238"
: "VUID-vkQueueSubmit-pWaitSemaphores-00069");
vk::QueueSubmit(m_device->m_queue, 2, submit_info, VK_NULL_HANDLE);
m_errorMonitor->VerifyFound();
submit_info[2].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[2].signalSemaphoreCount = 1;
submit_info[2].pSignalSemaphores = &(semaphore[0]);
ASSERT_VK_SUCCESS(vk::QueueSubmit(m_device->m_queue, 1, &(submit_info[2]), VK_NULL_HANDLE));
ASSERT_VK_SUCCESS(vk::QueueSubmit(m_device->m_queue, 2, submit_info, VK_NULL_HANDLE));
ASSERT_VK_SUCCESS(vk::QueueWaitIdle(m_device->m_queue));
vk::DestroySemaphore(m_device->device(), semaphore[0], nullptr);
vk::DestroySemaphore(m_device->device(), semaphore[1], nullptr);
vk::DestroySemaphore(m_device->device(), semaphore[2], nullptr);
}
TEST_F(VkLayerTest, QueueSubmitTimelineSemaphoreOutOfOrder) {
TEST_DESCRIPTION("Submit out-of-order timeline semaphores.");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
// We need two queues for this
uint32_t queue_count;
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_count, NULL);
VkQueueFamilyProperties *queue_props = new VkQueueFamilyProperties[queue_count];
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_count, queue_props);
uint32_t family_index[2] = {0};
uint32_t queue_index[2] = {0};
if (queue_count > 1) {
family_index[1]++;
} else {
// If there's only one family index, check if it supports more than 1 queue
if (queue_props[0].queueCount > 1) {
queue_index[1]++;
} else {
printf("%s Multiple queues are required to run this test. .\n", kSkipPrefix);
return;
}
}
float priorities[] = {1.0f, 1.0f};
VkDeviceQueueCreateInfo queue_info[2] = {};
queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info[0].queueFamilyIndex = family_index[0];
queue_info[0].queueCount = queue_count > 1 ? 1 : 2;
queue_info[0].pQueuePriorities = &(priorities[0]);
queue_info[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info[1].queueFamilyIndex = family_index[1];
queue_info[1].queueCount = queue_count > 1 ? 1 : 2;
queue_info[1].pQueuePriorities = &(priorities[0]);
VkDeviceCreateInfo dev_info{};
dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dev_info.queueCreateInfoCount = queue_count > 1 ? 2 : 1;
dev_info.pQueueCreateInfos = &(queue_info[0]);
dev_info.enabledLayerCount = 0;
dev_info.enabledExtensionCount = m_device_extension_names.size();
dev_info.ppEnabledExtensionNames = m_device_extension_names.data();
auto timeline_semaphore_features = lvl_init_struct<VkPhysicalDeviceTimelineSemaphoreFeatures>();
timeline_semaphore_features.timelineSemaphore = true;
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&timeline_semaphore_features);
dev_info.pNext = &features2;
VkDevice dev;
ASSERT_VK_SUCCESS(vk::CreateDevice(gpu(), &dev_info, nullptr, &dev));
VkQueue queue[2];
vk::GetDeviceQueue(dev, family_index[0], queue_index[0], &(queue[0]));
vk::GetDeviceQueue(dev, family_index[1], queue_index[1], &(queue[1]));
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
semaphore_type_create_info.initialValue = 5;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(dev, &semaphore_create_info, nullptr, &semaphore));
uint64_t semaphoreValues[] = {10, 100, 0, 10};
VkTimelineSemaphoreSubmitInfoKHR timeline_semaphore_submit_info{};
timeline_semaphore_submit_info.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR;
timeline_semaphore_submit_info.waitSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pWaitSemaphoreValues = &(semaphoreValues[0]);
timeline_semaphore_submit_info.signalSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pSignalSemaphoreValues = &(semaphoreValues[1]);
VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &timeline_semaphore_submit_info;
submit_info.pWaitDstStageMask = &stageFlags;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = &semaphore;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &semaphore;
ASSERT_VK_SUCCESS(vk::QueueSubmit(queue[0], 1, &submit_info, VK_NULL_HANDLE));
timeline_semaphore_submit_info.pWaitSemaphoreValues = &(semaphoreValues[2]);
timeline_semaphore_submit_info.pSignalSemaphoreValues = &(semaphoreValues[3]);
ASSERT_VK_SUCCESS(vk::QueueSubmit(queue[1], 1, &submit_info, VK_NULL_HANDLE));
vk::DeviceWaitIdle(dev);
vk::DestroySemaphore(dev, semaphore, nullptr);
vk::DestroyDevice(dev, nullptr);
}
TEST_F(VkLayerTest, InvalidExternalSemaphore) {
TEST_DESCRIPTION("Import and export invalid external semaphores, no queue sumbits involved.");
#ifdef _WIN32
printf("%s Test doesn't currently support Win32 semaphore, skipping test\n", kSkipPrefix);
return;
#else
const auto extension_name = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
// Check for external semaphore instance extensions
if (InstanceExtensionSupported(VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME);
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s External semaphore extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
// Check for external semaphore device extensions
if (DeviceExtensionSupported(gpu(), nullptr, extension_name)) {
m_device_extension_names.push_back(extension_name);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s External semaphore extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
// Create a semaphore fpr importing
VkSemaphoreCreateInfo semaphore_create_info = {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
semaphore_create_info.pNext = nullptr;
semaphore_create_info.flags = 0;
VkSemaphore import_semaphore;
VkResult err = vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &import_semaphore);
ASSERT_VK_SUCCESS(err);
int fd = 0;
VkImportSemaphoreFdInfoKHR import_semaphore_fd_info = {VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR};
import_semaphore_fd_info.pNext = nullptr;
import_semaphore_fd_info.semaphore = import_semaphore;
import_semaphore_fd_info.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR;
import_semaphore_fd_info.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT;
import_semaphore_fd_info.fd = fd;
auto vkImportSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)vk::GetDeviceProcAddr(m_device->device(), "vkImportSemaphoreFdKHR");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImportSemaphoreFdInfoKHR-handleType-01143");
vkImportSemaphoreFdKHR(device(), &import_semaphore_fd_info);
m_errorMonitor->VerifyFound();
// Cleanup
vk::DestroySemaphore(device(), import_semaphore, nullptr);
#endif
}
TEST_F(VkLayerTest, InvalidWaitSemaphoresType) {
TEST_DESCRIPTION("Wait for a non Timeline Semaphore");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore[2];
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &(semaphore[0])));
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_BINARY;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &(semaphore[1])));
VkSemaphoreWaitInfo semaphore_wait_info{};
semaphore_wait_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
semaphore_wait_info.semaphoreCount = 2;
semaphore_wait_info.pSemaphores = &semaphore[0];
const uint64_t wait_values[] = {10, 40};
semaphore_wait_info.pValues = &wait_values[0];
auto vkWaitSemaphoresKHR = (PFN_vkWaitSemaphoresKHR)vk::GetDeviceProcAddr(m_device->device(), "vkWaitSemaphoresKHR");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSemaphoreWaitInfo-pSemaphores-03256");
vkWaitSemaphoresKHR(m_device->device(), &semaphore_wait_info, 10000);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore[0], nullptr);
vk::DestroySemaphore(m_device->device(), semaphore[1], nullptr);
}
TEST_F(VkLayerTest, InvalidSignalSemaphoreType) {
TEST_DESCRIPTION("Signal a non Timeline Semaphore");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
auto timelinefeatures = lvl_init_struct<VkPhysicalDeviceTimelineSemaphoreFeaturesKHR>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&timelinefeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!timelinefeatures.timelineSemaphore) {
printf("%s Timeline semaphores are not supported.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
VkSemaphoreSignalInfo semaphore_signal_info{};
semaphore_signal_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO;
semaphore_signal_info.semaphore = semaphore;
semaphore_signal_info.value = 10;
auto vkSignalSemaphoreKHR = (PFN_vkSignalSemaphoreKHR)vk::GetDeviceProcAddr(m_device->device(), "vkSignalSemaphoreKHR");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSemaphoreSignalInfo-semaphore-03257");
vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
}
TEST_F(VkLayerTest, InvalidSignalSemaphoreValue) {
TEST_DESCRIPTION("Signal a Timeline Semaphore with invalid values");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
if (!CheckTimelineSemaphoreSupportAndInitState(this)) {
printf("%s Timeline semaphore not supported, skipping test\n", kSkipPrefix);
return;
}
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
auto timelineproperties = lvl_init_struct<VkPhysicalDeviceTimelineSemaphorePropertiesKHR>();
auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&timelineproperties);
vkGetPhysicalDeviceProperties2KHR(gpu(), &prop2);
VkSemaphoreTypeCreateInfoKHR semaphore_type_create_info{};
semaphore_type_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR;
semaphore_type_create_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR;
semaphore_type_create_info.initialValue = 5;
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphore_create_info.pNext = &semaphore_type_create_info;
VkSemaphore semaphore[2];
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore[0]));
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore[1]));
VkSemaphoreSignalInfo semaphore_signal_info{};
semaphore_signal_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO;
semaphore_signal_info.semaphore = semaphore[0];
semaphore_signal_info.value = 3;
auto vkSignalSemaphoreKHR = (PFN_vkSignalSemaphoreKHR)vk::GetDeviceProcAddr(m_device->device(), "vkSignalSemaphoreKHR");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSemaphoreSignalInfo-value-03258");
vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info);
m_errorMonitor->VerifyFound();
semaphore_signal_info.value = 10;
ASSERT_VK_SUCCESS(vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info));
VkTimelineSemaphoreSubmitInfoKHR timeline_semaphore_submit_info{};
uint64_t waitValue = 10;
uint64_t signalValue = 20;
timeline_semaphore_submit_info.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR;
timeline_semaphore_submit_info.waitSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pWaitSemaphoreValues = &waitValue;
timeline_semaphore_submit_info.signalSemaphoreValueCount = 1;
timeline_semaphore_submit_info.pSignalSemaphoreValues = &signalValue;
VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = &timeline_semaphore_submit_info;
submit_info.pWaitDstStageMask = &stageFlags;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = &(semaphore[1]);
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &(semaphore[0]);
ASSERT_VK_SUCCESS(vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE));
semaphore_signal_info.value = 25;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSemaphoreSignalInfo-value-03259");
vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info);
m_errorMonitor->VerifyFound();
semaphore_signal_info.value = 15;
ASSERT_VK_SUCCESS(vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info));
semaphore_signal_info.semaphore = semaphore[1];
ASSERT_VK_SUCCESS(vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info));
// Check if we can test violations of maxTimmelineSemaphoreValueDifference
if (timelineproperties.maxTimelineSemaphoreValueDifference < UINT64_MAX) {
VkSemaphore sem;
semaphore_type_create_info.initialValue = 0;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &sem));
semaphore_signal_info.semaphore = sem;
semaphore_signal_info.value = timelineproperties.maxTimelineSemaphoreValueDifference + 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkSemaphoreSignalInfo-value-03260");
vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info);
m_errorMonitor->VerifyFound();
semaphore_signal_info.value--;
ASSERT_VK_SUCCESS(vkSignalSemaphoreKHR(m_device->device(), &semaphore_signal_info));
vk::DestroySemaphore(m_device->device(), sem, nullptr);
}
ASSERT_VK_SUCCESS(vk::QueueWaitIdle(m_device->m_queue));
vk::DestroySemaphore(m_device->device(), semaphore[0], nullptr);
vk::DestroySemaphore(m_device->device(), semaphore[1], nullptr);
}
TEST_F(VkLayerTest, InvalidSemaphoreCounterType) {
TEST_DESCRIPTION("Get payload from a non Timeline Semaphore");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
return;
}
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
auto timelinefeatures = lvl_init_struct<VkPhysicalDeviceTimelineSemaphoreFeaturesKHR>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&timelinefeatures);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!timelinefeatures.timelineSemaphore) {
printf("%s Timeline semaphores are not supported.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
VkSemaphoreCreateInfo semaphore_create_info{};
semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
ASSERT_VK_SUCCESS(vk::CreateSemaphore(m_device->device(), &semaphore_create_info, nullptr, &semaphore));
auto vkGetSemaphoreCounterValueKHR =
(PFN_vkGetSemaphoreCounterValueKHR)vk::GetDeviceProcAddr(m_device->device(), "vkGetSemaphoreCounterValueKHR");
uint64_t value = 0xdeadbeef;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetSemaphoreCounterValue-semaphore-03255");
vkGetSemaphoreCounterValueKHR(m_device->device(), semaphore, &value);
m_errorMonitor->VerifyFound();
vk::DestroySemaphore(m_device->device(), semaphore, nullptr);
}
TEST_F(VkLayerTest, ImageDrmFormatModifer) {
TEST_DESCRIPTION("General testing of VK_EXT_image_drm_format_modifier");
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (IsPlatform(kMockICD)) {
printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix);
return;
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME);
return;
}
PFN_vkGetImageDrmFormatModifierPropertiesEXT vkGetImageDrmFormatModifierPropertiesEXT =
(PFN_vkGetImageDrmFormatModifierPropertiesEXT)vk::GetInstanceProcAddr(instance(),
"vkGetImageDrmFormatModifierPropertiesEXT");
ASSERT_TRUE(vkGetImageDrmFormatModifierPropertiesEXT != nullptr);
ASSERT_NO_FATAL_FAILURE(InitState());
const uint64_t dummy_modifiers[2] = {0, 1};
VkImageCreateInfo image_info = {};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.pNext = nullptr;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.arrayLayers = 1;
image_info.extent = {64, 64, 1};
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.mipLevels = 1;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
VkImageFormatProperties2 image_format_prop = {};
image_format_prop.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
VkPhysicalDeviceImageFormatInfo2 image_format_info = {};
image_format_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
image_format_info.format = image_info.format;
image_format_info.tiling = image_info.tiling;
image_format_info.type = image_info.imageType;
image_format_info.usage = image_info.usage;
VkPhysicalDeviceImageDrmFormatModifierInfoEXT drm_format_mod_info = {};
drm_format_mod_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT;
drm_format_mod_info.pNext = nullptr;
drm_format_mod_info.drmFormatModifier = dummy_modifiers[0];
drm_format_mod_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
drm_format_mod_info.queueFamilyIndexCount = 0;
image_format_info.pNext = (void *)&drm_format_mod_info;
vk::GetPhysicalDeviceImageFormatProperties2(m_device->phy().handle(), &image_format_info, &image_format_prop);
VkSubresourceLayout dummyPlaneLayout = {0, 0, 0, 0, 0};
VkImageDrmFormatModifierListCreateInfoEXT drm_format_mod_list = {};
drm_format_mod_list.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT;
drm_format_mod_list.pNext = nullptr;
drm_format_mod_list.drmFormatModifierCount = 2;
drm_format_mod_list.pDrmFormatModifiers = dummy_modifiers;
VkImageDrmFormatModifierExplicitCreateInfoEXT drm_format_mod_explicit = {};
drm_format_mod_explicit.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT;
drm_format_mod_explicit.pNext = nullptr;
drm_format_mod_explicit.drmFormatModifierPlaneCount = 1;
drm_format_mod_explicit.pPlaneLayouts = &dummyPlaneLayout;
VkImage image = VK_NULL_HANDLE;
// No pNext
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-tiling-02261");
vk::CreateImage(device(), &image_info, nullptr, &image);
m_errorMonitor->VerifyFound();
// Postive check if only 1
image_info.pNext = (void *)&drm_format_mod_list;
m_errorMonitor->ExpectSuccess();
vk::CreateImage(device(), &image_info, nullptr, &image);
vk::DestroyImage(device(), image, nullptr);
m_errorMonitor->VerifyNotFound();
image_info.pNext = (void *)&drm_format_mod_explicit;
m_errorMonitor->ExpectSuccess();
vk::CreateImage(device(), &image_info, nullptr, &image);
vk::DestroyImage(device(), image, nullptr);
m_errorMonitor->VerifyNotFound();
// Having both in pNext
drm_format_mod_explicit.pNext = (void *)&drm_format_mod_list;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-tiling-02261");
vk::CreateImage(device(), &image_info, nullptr, &image);
m_errorMonitor->VerifyFound();
// Only 1 pNext but wrong tiling
image_info.pNext = (void *)&drm_format_mod_list;
image_info.tiling = VK_IMAGE_TILING_LINEAR;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkImageCreateInfo-pNext-02262");
vk::CreateImage(device(), &image_info, nullptr, &image);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, ValidateNVDeviceDiagnosticCheckpoints) {
TEST_DESCRIPTION("General testing of VK_NV_device_diagnostic_checkpoints");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Extension %s is not supported.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
if (DeviceExtensionSupported(gpu(), nullptr, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME);
} else {
printf("%s Extension %s not supported by device; skipped.\n", kSkipPrefix,
VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
auto vkGetQueueCheckpointDataNV =
(PFN_vkGetQueueCheckpointDataNV)vk::GetDeviceProcAddr(m_device->device(), "vkGetQueueCheckpointDataNV");
auto vkCmdSetCheckpointNV = (PFN_vkCmdSetCheckpointNV)vk::GetDeviceProcAddr(m_device->device(), "vkCmdSetCheckpointNV");
ASSERT_TRUE(vkGetQueueCheckpointDataNV != nullptr);
ASSERT_TRUE(vkCmdSetCheckpointNV != nullptr);
uint32_t data = 100;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdSetCheckpointNV-commandBuffer-recording");
vkCmdSetCheckpointNV(m_commandBuffer->handle(), &data);
m_errorMonitor->VerifyFound();
}
TEST_F(VkLayerTest, InvalidGetDeviceQueue) {
TEST_DESCRIPTION("General testing of vkGetDeviceQueue and general Device creation cases");
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Did not find VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME; skipped.\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
VkDevice test_device;
VkQueue test_queue;
VkResult result;
// Use the first Physical device and queue family
// Makes test more portable as every driver has at least 1 queue with a queueCount of 1
uint32_t queue_family_count = 1;
uint32_t queue_family_index = 0;
VkQueueFamilyProperties queue_properties;
vk::GetPhysicalDeviceQueueFamilyProperties(gpu(), &queue_family_count, &queue_properties);
float queue_priority = 1.0;
VkDeviceQueueCreateInfo queue_create_info = {};
queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_create_info.flags = VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT;
queue_create_info.pNext = nullptr;
queue_create_info.queueFamilyIndex = queue_family_index;
queue_create_info.queueCount = 1;
queue_create_info.pQueuePriorities = &queue_priority;
VkPhysicalDeviceProtectedMemoryFeatures protect_features = {};
protect_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES;
protect_features.pNext = nullptr;
protect_features.protectedMemory = VK_FALSE; // Starting with it off
VkDeviceCreateInfo device_create_info = {};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = &protect_features;
device_create_info.flags = 0;
device_create_info.pQueueCreateInfos = &queue_create_info;
device_create_info.queueCreateInfoCount = 1;
device_create_info.pEnabledFeatures = nullptr;
device_create_info.enabledLayerCount = 0;
device_create_info.enabledExtensionCount = 0;
// Protect feature not set
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkDeviceQueueCreateInfo-flags-02861");
vk::CreateDevice(gpu(), &device_create_info, nullptr, &test_device);
m_errorMonitor->VerifyFound();
VkPhysicalDeviceFeatures2 features2;
features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
features2.pNext = &protect_features;
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (protect_features.protectedMemory == VK_TRUE) {
result = vk::CreateDevice(gpu(), &device_create_info, nullptr, &test_device);
if (result != VK_SUCCESS) {
printf("%s CreateDevice returned back %s, skipping rest of tests\n", kSkipPrefix, string_VkResult(result));
return;
}
// TODO: Re-enable test when Vulkan-Loader issue #384 is resolved and upstream
// Try using GetDeviceQueue with a queue that has as flag
// m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetDeviceQueue-flags-01841");
// vk::GetDeviceQueue(test_device, queue_family_index, 0, &test_queue);
// m_errorMonitor->VerifyFound();
vk::DestroyDevice(test_device, nullptr);
}
// Create device without protected queue
protect_features.protectedMemory = VK_FALSE;
queue_create_info.flags = 0;
result = vk::CreateDevice(gpu(), &device_create_info, nullptr, &test_device);
if (result != VK_SUCCESS) {
printf("%s CreateDevice returned back %s, skipping rest of tests\n", kSkipPrefix, string_VkResult(result));
return;
}
// TODO: Re-enable test when Vulkan-Loader issue #384 is resolved and upstream
// Set queueIndex 1 over size of queueCount
// m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetDeviceQueue-queueIndex-00385");
// vk::GetDeviceQueue(test_device, queue_family_index, queue_properties.queueCount, &test_queue);
// m_errorMonitor->VerifyFound();
// Use an unknown queue family index
// m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkGetDeviceQueue-queueFamilyIndex-00384");
// vk::GetDeviceQueue(test_device, queue_family_index + 1, 0, &test_queue);
// m_errorMonitor->VerifyFound();
// Sanity check can still get the queue
m_errorMonitor->ExpectSuccess();
vk::GetDeviceQueue(test_device, queue_family_index, 0, &test_queue);
m_errorMonitor->VerifyNotFound();
vk::DestroyDevice(test_device, nullptr);
}
TEST_F(VkLayerTest, ValidateCmdTraceRaysKHR) {
TEST_DESCRIPTION("Validate vkCmdTraceRaysKHR.");
if (!InitFrameworkForRayTracingTest(this, true, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
VkBuffer buffer;
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
auto ray_tracing_properties = lvl_init_struct<VkPhysicalDeviceRayTracingPropertiesKHR>();
auto properties2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&ray_tracing_properties);
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR = (PFN_vkCmdTraceRaysKHR)vk::GetInstanceProcAddr(instance(), "vkCmdTraceRaysKHR");
ASSERT_TRUE(vkCmdTraceRaysKHR != nullptr);
VkStridedBufferRegionKHR stridebufregion = {};
stridebufregion.buffer = buffer;
stridebufregion.offset = 0;
stridebufregion.stride = ray_tracing_properties.shaderGroupHandleSize;
stridebufregion.size = buf_info.size;
// invalid offset
{
VkStridedBufferRegionKHR invalid_offset = stridebufregion;
invalid_offset.offset = ray_tracing_properties.shaderGroupBaseAlignment + 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-offset-04038");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &stridebufregion, &invalid_offset, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-offset-04032");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &invalid_offset, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-offset-04026");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &invalid_offset, &stridebufregion, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-pRayGenShaderBindingTable-04021");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &invalid_offset, &stridebufregion, &stridebufregion, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
}
// Invalid stride multiplier
{
VkStridedBufferRegionKHR invalid_stride = stridebufregion;
invalid_stride.stride = 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-stride-04040");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &stridebufregion, &invalid_stride, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-stride-04034");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &invalid_stride, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-stride-04028");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &invalid_stride, &stridebufregion, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
}
// Invalid stride, greater than maxShaderGroupStride
{
VkStridedBufferRegionKHR invalid_stride = stridebufregion;
uint32_t align = ray_tracing_properties.shaderGroupHandleSize;
invalid_stride.stride =
ray_tracing_properties.maxShaderGroupStride + (align - (ray_tracing_properties.maxShaderGroupStride % align));
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-stride-04041");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &stridebufregion, &invalid_stride, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-stride-04035");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &invalid_stride, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysKHR-stride-04029");
vkCmdTraceRaysKHR(m_commandBuffer->handle(), &stridebufregion, &invalid_stride, &stridebufregion, &stridebufregion, 100,
100, 1);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateCmdTraceRaysIndirectKHR) {
TEST_DESCRIPTION("Validate vkCmdTraceRaysIndirectKHR.");
if (!InitFrameworkForRayTracingTest(this, true, m_instance_extension_names, m_device_extension_names, m_errorMonitor, false,
false, true)) {
return;
}
auto ray_tracing_features = lvl_init_struct<VkPhysicalDeviceRayTracingFeaturesKHR>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&ray_tracing_features);
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (ray_tracing_features.rayTracingIndirectTraceRays == VK_FALSE) {
printf("%s rayTracingIndirectTraceRays not supported, skipping tests\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &ray_tracing_features));
VkBuffer buffer;
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
buf_info.size = 4096;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkResult err = vk::CreateBuffer(device(), &buf_info, NULL, &buffer);
ASSERT_VK_SUCCESS(err);
VkMemoryRequirements mem_reqs;
vk::GetBufferMemoryRequirements(device(), buffer, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = 4096;
VkDeviceMemory mem;
err = vk::AllocateMemory(device(), &alloc_info, NULL, &mem);
ASSERT_VK_SUCCESS(err);
vk::BindBufferMemory(device(), buffer, mem, 0);
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
auto ray_tracing_properties = lvl_init_struct<VkPhysicalDeviceRayTracingPropertiesKHR>();
auto properties2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&ray_tracing_properties);
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
PFN_vkCmdTraceRaysIndirectKHR vkCmdTraceRaysIndirectKHR =
(PFN_vkCmdTraceRaysIndirectKHR)vk::GetInstanceProcAddr(instance(), "vkCmdTraceRaysIndirectKHR");
ASSERT_TRUE(vkCmdTraceRaysIndirectKHR != nullptr);
VkStridedBufferRegionKHR stridebufregion = {};
stridebufregion.buffer = buffer;
stridebufregion.offset = 0;
stridebufregion.stride = ray_tracing_properties.shaderGroupHandleSize;
stridebufregion.size = buf_info.size;
// invalid offset
{
VkStridedBufferRegionKHR invalid_offset = stridebufregion;
invalid_offset.offset = ray_tracing_properties.shaderGroupBaseAlignment + 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-offset-04038");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &stridebufregion, &invalid_offset,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-offset-04032");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &invalid_offset, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-offset-04026");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &invalid_offset, &stridebufregion, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-pRayGenShaderBindingTable-04021");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &invalid_offset, &stridebufregion, &stridebufregion, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
}
// Invalid stride multiplier
{
VkStridedBufferRegionKHR invalid_stride = stridebufregion;
invalid_stride.stride = 1;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-stride-04040");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &stridebufregion, &invalid_stride,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-stride-04034");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &invalid_stride, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-stride-04028");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &invalid_stride, &stridebufregion, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
}
// Invalid stride, greater than maxShaderGroupStride
{
VkStridedBufferRegionKHR invalid_stride = stridebufregion;
uint32_t align = ray_tracing_properties.shaderGroupHandleSize;
invalid_stride.stride =
ray_tracing_properties.maxShaderGroupStride + (align - (ray_tracing_properties.maxShaderGroupStride % align));
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-stride-04041");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &stridebufregion, &invalid_stride,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-stride-04035");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &stridebufregion, &invalid_stride, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysIndirectKHR-stride-04029");
vkCmdTraceRaysIndirectKHR(m_commandBuffer->handle(), &stridebufregion, &invalid_stride, &stridebufregion, &stridebufregion,
buffer, 0);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateVkAccelerationStructureVersionKHR) {
TEST_DESCRIPTION("Validate VkAccelerationStructureVersionKHR.");
if (!InitFrameworkForRayTracingTest(this, true, m_instance_extension_names, m_device_extension_names, m_errorMonitor, false,
false, true)) {
return;
}
auto ray_tracing_features = lvl_init_struct<VkPhysicalDeviceRayTracingFeaturesKHR>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&ray_tracing_features);
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (ray_tracing_features.rayTracing == VK_FALSE) {
printf("%s rayTracing not supported, skipping tests\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &ray_tracing_features));
PFN_vkGetDeviceAccelerationStructureCompatibilityKHR vkGetDeviceAccelerationStructureCompatibilityKHR =
(PFN_vkGetDeviceAccelerationStructureCompatibilityKHR)vk::GetInstanceProcAddr(
instance(), "vkGetDeviceAccelerationStructureCompatibilityKHR");
ASSERT_TRUE(vkGetDeviceAccelerationStructureCompatibilityKHR != nullptr);
VkAccelerationStructureVersionKHR valid_version = {};
uint8_t mode[] = {VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR, VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_KHR};
valid_version.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_VERSION_KHR;
valid_version.versionData = mode;
{
VkAccelerationStructureVersionKHR invalid_version = valid_version;
invalid_version.sType = VK_STRUCTURE_TYPE_MAX_ENUM;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureVersionKHR-sType-sType");
vkGetDeviceAccelerationStructureCompatibilityKHR(m_device->handle(), &invalid_version);
m_errorMonitor->VerifyFound();
}
{
VkAccelerationStructureVersionKHR invalid_version = valid_version;
invalid_version.versionData = NULL;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureVersionKHR-versionData-parameter");
vkGetDeviceAccelerationStructureCompatibilityKHR(m_device->handle(), &invalid_version);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateCmdBuildAccelerationStructureKHR) {
TEST_DESCRIPTION("Validate acceleration structure building.");
if (!InitFrameworkForRayTracingTest(this, true, m_instance_extension_names, m_device_extension_names, m_errorMonitor)) {
return;
}
PFN_vkCmdBuildAccelerationStructureKHR vkCmdBuildAccelerationStructureKHR =
(PFN_vkCmdBuildAccelerationStructureKHR)vk::GetDeviceProcAddr(device(), "vkCmdBuildAccelerationStructureKHR");
PFN_vkGetBufferDeviceAddressKHR vkGetBufferDeviceAddressKHR =
(PFN_vkGetBufferDeviceAddressKHR)vk::GetDeviceProcAddr(device(), "vkGetBufferDeviceAddressKHR");
assert(vkCmdBuildAccelerationStructureKHR != nullptr);
VkBufferObj vbo;
VkBufferObj ibo;
VkGeometryNV geometryNV;
GetSimpleGeometryForAccelerationStructureTests(*m_device, &vbo, &ibo, &geometryNV);
VkAccelerationStructureCreateGeometryTypeInfoKHR geometryInfo = {};
geometryInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_GEOMETRY_TYPE_INFO_KHR;
geometryInfo.geometryType = geometryNV.geometryType;
geometryInfo.maxPrimitiveCount = 1024;
geometryInfo.indexType = geometryNV.geometry.triangles.indexType;
geometryInfo.maxVertexCount = 1024;
geometryInfo.vertexFormat = geometryNV.geometry.triangles.vertexFormat;
geometryInfo.allowsTransforms = VK_TRUE;
VkAccelerationStructureCreateInfoKHR bot_level_as_create_info = {};
bot_level_as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR;
bot_level_as_create_info.pNext = NULL;
bot_level_as_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
bot_level_as_create_info.maxGeometryCount = 1;
bot_level_as_create_info.pGeometryInfos = &geometryInfo;
VkAccelerationStructureObj bot_level_as(*m_device, bot_level_as_create_info);
VkBufferDeviceAddressInfo vertexAddressInfo = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, NULL,
geometryNV.geometry.triangles.vertexData};
VkDeviceAddress vertexAddress = vkGetBufferDeviceAddressKHR(m_device->handle(), &vertexAddressInfo);
VkBufferDeviceAddressInfo indexAddressInfo = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, NULL,
geometryNV.geometry.triangles.indexData};
VkDeviceAddress indexAddress = vkGetBufferDeviceAddressKHR(m_device->handle(), &indexAddressInfo);
VkAccelerationStructureGeometryKHR valid_geometry_triangles = {VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR};
valid_geometry_triangles.geometryType = geometryNV.geometryType;
valid_geometry_triangles.geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR;
valid_geometry_triangles.geometry.triangles.pNext = NULL;
valid_geometry_triangles.geometry.triangles.vertexFormat = geometryNV.geometry.triangles.vertexFormat;
valid_geometry_triangles.geometry.triangles.vertexData.deviceAddress = vertexAddress;
valid_geometry_triangles.geometry.triangles.vertexStride = 8;
valid_geometry_triangles.geometry.triangles.indexType = VK_INDEX_TYPE_UINT32;
valid_geometry_triangles.geometry.triangles.indexData.deviceAddress = indexAddress;
valid_geometry_triangles.geometry.triangles.transformData.deviceAddress = 0;
valid_geometry_triangles.flags = 0;
VkAccelerationStructureGeometryKHR *pGeometry_triangles = &valid_geometry_triangles;
VkAccelerationStructureBuildGeometryInfoKHR valid_asInfo_triangles = {
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR};
valid_asInfo_triangles.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
valid_asInfo_triangles.flags = 0;
valid_asInfo_triangles.update = VK_FALSE;
valid_asInfo_triangles.srcAccelerationStructure = VK_NULL_HANDLE;
valid_asInfo_triangles.dstAccelerationStructure = bot_level_as.handle();
valid_asInfo_triangles.geometryArrayOfPointers = VK_FALSE;
valid_asInfo_triangles.geometryCount = 1;
valid_asInfo_triangles.ppGeometries = &pGeometry_triangles;
valid_asInfo_triangles.scratchData.deviceAddress = 0;
VkAccelerationStructureBuildOffsetInfoKHR buildOffsetInfo = {
1,
0,
0,
0,
};
const VkAccelerationStructureBuildOffsetInfoKHR *pBuildOffsetInfo = &buildOffsetInfo;
m_commandBuffer->begin();
// build valid src acc for update VK_TRUE case with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR set
VkAccelerationStructureBuildGeometryInfoKHR valid_src_asInfo_triangles = valid_asInfo_triangles;
valid_src_asInfo_triangles.flags = VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR;
valid_src_asInfo_triangles.srcAccelerationStructure = bot_level_as.handle();
valid_src_asInfo_triangles.dstAccelerationStructure = bot_level_as.handle();
vkCmdBuildAccelerationStructureKHR(m_commandBuffer->handle(), 1, &valid_src_asInfo_triangles, &pBuildOffsetInfo);
// positive test
{
VkAccelerationStructureBuildGeometryInfoKHR asInfo_validupdate = valid_asInfo_triangles;
asInfo_validupdate.update = VK_TRUE;
asInfo_validupdate.srcAccelerationStructure = bot_level_as.handle();
m_errorMonitor->ExpectSuccess();
vkCmdBuildAccelerationStructureKHR(m_commandBuffer->handle(), 1, &asInfo_validupdate, &pBuildOffsetInfo);
m_errorMonitor->VerifyNotFound();
}
// If update is VK_TRUE, srcAccelerationStructure must not be VK_NULL_HANDLE
{
VkAccelerationStructureBuildGeometryInfoKHR asInfo_invalidupdate = valid_asInfo_triangles;
asInfo_invalidupdate.update = VK_TRUE;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureBuildGeometryInfoKHR-update-03537");
vkCmdBuildAccelerationStructureKHR(m_commandBuffer->handle(), 1, &asInfo_invalidupdate, &pBuildOffsetInfo);
m_errorMonitor->VerifyFound();
}
{
VkAccelerationStructureBuildGeometryInfoKHR invalid_src_asInfo_triangles = valid_src_asInfo_triangles;
invalid_src_asInfo_triangles.flags = 0;
invalid_src_asInfo_triangles.srcAccelerationStructure = bot_level_as.handle();
invalid_src_asInfo_triangles.dstAccelerationStructure = bot_level_as.handle();
// build src As without flag VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR set
vkCmdBuildAccelerationStructureKHR(m_commandBuffer->handle(), 1, &invalid_src_asInfo_triangles, &pBuildOffsetInfo);
VkAccelerationStructureBuildGeometryInfoKHR asInfo_invalidupdate = valid_asInfo_triangles;
asInfo_invalidupdate.update = VK_TRUE;
asInfo_invalidupdate.srcAccelerationStructure = bot_level_as.handle();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkAccelerationStructureBuildGeometryInfoKHR-update-03538");
vkCmdBuildAccelerationStructureKHR(m_commandBuffer->handle(), 1, &asInfo_invalidupdate, &pBuildOffsetInfo);
m_errorMonitor->VerifyFound();
}
}
TEST_F(VkLayerTest, ValidateImportMemoryHandleType) {
TEST_DESCRIPTION("Validate import memory handleType for buffers and images");
#ifdef _WIN32
const auto ext_mem_extension_name = VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME;
const auto handle_type = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR;
#else
const auto ext_mem_extension_name = VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME;
const auto handle_type = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
#endif
const auto wrong_handle_type = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
// Check for external memory instance extensions
std::vector<const char *> reqd_instance_extensions = {
{VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME}};
for (auto extension_name : reqd_instance_extensions) {
if (InstanceExtensionSupported(extension_name)) {
m_instance_extension_names.push_back(extension_name);
} else {
printf("%s Required instance extension %s not supported, skipping test\n", kSkipPrefix, extension_name);
return;
}
}
ASSERT_NO_FATAL_FAILURE(InitFramework(m_errorMonitor));
auto vkGetPhysicalDeviceExternalBufferPropertiesKHR =
(PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR)vk::GetInstanceProcAddr(
instance(), "vkGetPhysicalDeviceExternalBufferPropertiesKHR");
// Check for import/export capability
// export used to feed memory to test import
VkPhysicalDeviceExternalBufferInfoKHR ebi = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO_KHR, nullptr, 0,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, handle_type};
VkExternalBufferPropertiesKHR ebp = {VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES_KHR, nullptr, {0, 0, 0}};
ASSERT_TRUE(vkGetPhysicalDeviceExternalBufferPropertiesKHR != nullptr);
vkGetPhysicalDeviceExternalBufferPropertiesKHR(gpu(), &ebi, &ebp);
if (!(ebp.externalMemoryProperties.compatibleHandleTypes & handle_type) ||
!(ebp.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_KHR) ||
!(ebp.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_KHR)) {
printf("%s External buffer does not support importing and exporting, skipping test\n", kSkipPrefix);
return;
}
// Always use dedicated allocation
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
} else {
printf("%s Dedicated allocation extension not supported, skipping test\n", kSkipPrefix);
return;
}
// Check for external memory device extensions
if (DeviceExtensionSupported(gpu(), nullptr, ext_mem_extension_name)) {
m_device_extension_names.push_back(ext_mem_extension_name);
m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
} else {
printf("%s External memory extension not supported, skipping test\n", kSkipPrefix);
return;
}
// Check for bind memory 2
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
} else {
printf("%s bind memory 2 extension not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
PFN_vkBindBufferMemory2KHR vkBindBufferMemory2Function =
(PFN_vkBindBufferMemory2KHR)vk::GetDeviceProcAddr(m_device->handle(), "vkBindBufferMemory2KHR");
PFN_vkBindImageMemory2KHR vkBindImageMemory2Function =
(PFN_vkBindImageMemory2KHR)vk::GetDeviceProcAddr(m_device->handle(), "vkBindImageMemory2KHR");
m_errorMonitor->ExpectSuccess(kErrorBit | kWarningBit);
VkMemoryPropertyFlags mem_flags = 0;
const VkDeviceSize buffer_size = 1024;
// Create export and import buffers
VkExternalMemoryBufferCreateInfoKHR external_buffer_info = {VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, nullptr,
handle_type};
auto buffer_info = VkBufferObj::create_info(buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
buffer_info.pNext = &external_buffer_info;
VkBufferObj buffer_export;
buffer_export.init_no_mem(*m_device, buffer_info);
external_buffer_info.handleTypes = wrong_handle_type;
VkBufferObj buffer_import;
buffer_import.init_no_mem(*m_device, buffer_info);
// Allocation info
auto alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, buffer_export.memory_requirements(), mem_flags);
// Add export allocation info to pNext chain
VkMemoryDedicatedAllocateInfoKHR dedicated_info = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR, nullptr,
VK_NULL_HANDLE, buffer_export.handle()};
VkExportMemoryAllocateInfoKHR export_info = {VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR, &dedicated_info, handle_type};
alloc_info.pNext = &export_info;
// Allocate memory to be exported
vk_testing::DeviceMemory memory_buffer_export;
memory_buffer_export.init(*m_device, alloc_info);
// Bind exported memory
buffer_export.bind_memory(memory_buffer_export, 0);
VkExternalMemoryImageCreateInfoKHR external_image_info = {VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, nullptr,
handle_type};
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.pNext = &external_image_info;
image_info.extent = {64, 64, 1};
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.arrayLayers = 1;
image_info.mipLevels = 1;
VkImageObj image_export(m_device);
image_export.init_no_mem(*m_device, image_info);
external_image_info.handleTypes = wrong_handle_type;
VkImageObj image_import(m_device);
image_import.init_no_mem(*m_device, image_info);
// Allocation info
dedicated_info = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR, nullptr, image_export.handle(), VK_NULL_HANDLE};
alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, image_export.memory_requirements(), mem_flags);
alloc_info.pNext = &export_info;
// Allocate memory to be exported
vk_testing::DeviceMemory memory_image_export;
memory_image_export.init(*m_device, alloc_info);
// Bind exported memory
image_export.bind_memory(memory_image_export, 0);
#ifdef _WIN32
// Export memory to handle
auto vkGetMemoryWin32HandleKHR =
(PFN_vkGetMemoryWin32HandleKHR)vk::GetInstanceProcAddr(instance(), "vkGetMemoryWin32HandleKHR");
ASSERT_TRUE(vkGetMemoryWin32HandleKHR != nullptr);
VkMemoryGetWin32HandleInfoKHR mghi_buffer = {VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR, nullptr,
memory_buffer_export.handle(), handle_type};
VkMemoryGetWin32HandleInfoKHR mghi_image = {VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR, nullptr,
memory_image_export.handle(), handle_type};
HANDLE handle_buffer;
HANDLE handle_image;
ASSERT_VK_SUCCESS(vkGetMemoryWin32HandleKHR(m_device->device(), &mghi_buffer, &handle_buffer));
ASSERT_VK_SUCCESS(vkGetMemoryWin32HandleKHR(m_device->device(), &mghi_image, &handle_image));
VkImportMemoryWin32HandleInfoKHR import_info_buffer = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR, nullptr,
handle_type, handle_buffer};
VkImportMemoryWin32HandleInfoKHR import_info_image = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR, nullptr,
handle_type, handle_image};
#else
// Export memory to fd
auto vkGetMemoryFdKHR = (PFN_vkGetMemoryFdKHR)vk::GetInstanceProcAddr(instance(), "vkGetMemoryFdKHR");
ASSERT_TRUE(vkGetMemoryFdKHR != nullptr);
VkMemoryGetFdInfoKHR mgfi_buffer = {VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, nullptr, memory_buffer_export.handle(),
handle_type};
VkMemoryGetFdInfoKHR mgfi_image = {VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, nullptr, memory_image_export.handle(),
handle_type};
int fd_buffer;
int fd_image;
ASSERT_VK_SUCCESS(vkGetMemoryFdKHR(m_device->device(), &mgfi_buffer, &fd_buffer));
ASSERT_VK_SUCCESS(vkGetMemoryFdKHR(m_device->device(), &mgfi_image, &fd_image));
VkImportMemoryFdInfoKHR import_info_buffer = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, nullptr, handle_type, fd_buffer};
VkImportMemoryFdInfoKHR import_info_image = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, nullptr, handle_type, fd_image};
#endif
// Import memory
alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, buffer_import.memory_requirements(), mem_flags);
alloc_info.pNext = &import_info_buffer;
vk_testing::DeviceMemory memory_buffer_import;
memory_buffer_import.init(*m_device, alloc_info);
alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, image_import.memory_requirements(), mem_flags);
alloc_info.pNext = &import_info_image;
vk_testing::DeviceMemory memory_image_import;
memory_image_import.init(*m_device, alloc_info);
m_errorMonitor->VerifyNotFound();
// Bind imported memory with different handleType
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkBindBufferMemory-memory-02727");
vk::BindBufferMemory(device(), buffer_import.handle(), memory_buffer_import.handle(), 0);
m_errorMonitor->VerifyFound();
VkBindBufferMemoryInfo bind_buffer_info = {};
bind_buffer_info.sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO;
bind_buffer_info.pNext = nullptr;
bind_buffer_info.buffer = buffer_import.handle();
bind_buffer_info.memory = memory_buffer_import.handle();
bind_buffer_info.memoryOffset = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindBufferMemoryInfo-memory-02792");
vkBindBufferMemory2Function(device(), 1, &bind_buffer_info);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkBindImageMemory-memory-02729");
m_errorMonitor->SetUnexpectedError("VUID-VkBindImageMemoryInfo-memory-01614");
m_errorMonitor->SetUnexpectedError("VUID-VkBindImageMemoryInfo-memory-01612");
vk::BindImageMemory(device(), image_import.handle(), memory_image_import.handle(), 0);
m_errorMonitor->VerifyFound();
VkBindImageMemoryInfo bind_image_info = {};
bind_image_info.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
bind_image_info.pNext = nullptr;
bind_image_info.image = image_import.handle();
bind_image_info.memory = memory_buffer_import.handle();
bind_image_info.memoryOffset = 0;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-VkBindImageMemoryInfo-memory-02794");
m_errorMonitor->SetUnexpectedError("VUID-VkBindImageMemoryInfo-memory-01614");
m_errorMonitor->SetUnexpectedError("VUID-VkBindImageMemoryInfo-memory-01612");
vkBindImageMemory2Function(device(), 1, &bind_image_info);
m_errorMonitor->VerifyFound();
}
| 1 | 13,843 | I this used anyplace? | KhronosGroup-Vulkan-ValidationLayers | cpp |
@@ -102,7 +102,7 @@ public class TestHiveMetastore {
.transportFactory(new TTransportFactory())
.protocolFactory(new TBinaryProtocol.Factory())
.minWorkerThreads(3)
- .maxWorkerThreads(5);
+ .maxWorkerThreads(8);
return new TThreadPoolServer(args);
} | 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.hive;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.IHMSHandler;
import org.apache.hadoop.hive.metastore.RetryingHMSHandler;
import org.apache.hadoop.hive.metastore.TSetIpAddressProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportFactory;
import static java.nio.file.Files.createTempDirectory;
import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;
import static java.nio.file.attribute.PosixFilePermissions.fromString;
public class TestHiveMetastore {
private File hiveLocalDir;
private HiveConf hiveConf;
private ExecutorService executorService;
private TServer server;
public void start() {
try {
hiveLocalDir = createTempDirectory("hive", asFileAttribute(fromString("rwxrwxrwx"))).toFile();
File derbyLogFile = new File(hiveLocalDir, "derby.log");
System.setProperty("derby.stream.error.file", derbyLogFile.getAbsolutePath());
setupMetastoreDB("jdbc:derby:" + getDerbyPath() + ";create=true");
TServerSocket socket = new TServerSocket(0);
int port = socket.getServerSocket().getLocalPort();
hiveConf = newHiveConf(port);
server = newThriftServer(socket, hiveConf);
executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> server.serve());
} catch (Exception e) {
throw new RuntimeException("Cannot start TestHiveMetastore", e);
}
}
public void stop() {
if (server != null) {
server.stop();
}
if (executorService != null) {
executorService.shutdown();
}
if (hiveLocalDir != null) {
hiveLocalDir.delete();
}
}
public HiveConf hiveConf() {
return hiveConf;
}
public String getDatabasePath(String dbName) {
File dbDir = new File(hiveLocalDir, dbName + ".db");
return dbDir.getPath();
}
private TServer newThriftServer(TServerSocket socket, HiveConf conf) throws Exception {
HiveConf serverConf = new HiveConf(conf);
serverConf.set(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname, "jdbc:derby:" + getDerbyPath() + ";create=true");
HiveMetaStore.HMSHandler baseHandler = new HiveMetaStore.HMSHandler("new db based metaserver", serverConf);
IHMSHandler handler = RetryingHMSHandler.getProxy(serverConf, baseHandler, false);
TThreadPoolServer.Args args = new TThreadPoolServer.Args(socket)
.processor(new TSetIpAddressProcessor<>(handler))
.transportFactory(new TTransportFactory())
.protocolFactory(new TBinaryProtocol.Factory())
.minWorkerThreads(3)
.maxWorkerThreads(5);
return new TThreadPoolServer(args);
}
private HiveConf newHiveConf(int port) {
HiveConf newHiveConf = new HiveConf(new Configuration(), TestHiveMetastore.class);
newHiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname, "thrift://localhost:" + port);
newHiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, "file:" + hiveLocalDir.getAbsolutePath());
return newHiveConf;
}
private void setupMetastoreDB(String dbURL) throws SQLException, IOException {
Connection connection = DriverManager.getConnection(dbURL);
ScriptRunner scriptRunner = new ScriptRunner(connection, true, true);
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("hive-schema-3.1.0.derby.sql");
try (Reader reader = new InputStreamReader(inputStream)) {
scriptRunner.runScript(reader);
}
}
private String getDerbyPath() {
File metastoreDB = new File(hiveLocalDir, "metastore_db");
return metastoreDB.getPath();
}
}
| 1 | 15,182 | Why was this change required? | apache-iceberg | java |
@@ -39,6 +39,7 @@ public class AuthorizationException extends ProcessEngineException {
protected final String userId;
protected final List<MissingAuthorization> missingAuthorizations;
+ protected final boolean missingAdminRole;
// these properties have been replaced by the list of missingAuthorizations
// and are only left because this is a public API package and users might | 1 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.camunda.bpm.engine.authorization.MissingAuthorization;
/**
* <p>Exception thrown by the process engine in case a user tries to
* interact with a resource in an unauthorized way.</p>
*
* <p>The exception contains a list of Missing authorizations. The List is a
* disjunction i.e. a user should have any of the authorization for the engine
* to continue the execution beyond the point where it failed.</p>
*
* @author Daniel Meyer
*
*/
public class AuthorizationException extends ProcessEngineException {
private static final long serialVersionUID = 1L;
protected final String userId;
protected final List<MissingAuthorization> missingAuthorizations;
// these properties have been replaced by the list of missingAuthorizations
// and are only left because this is a public API package and users might
// have subclasses relying on these fields
@Deprecated
protected String resourceType;
@Deprecated
protected String permissionName;
@Deprecated
protected String resourceId;
public AuthorizationException(String message) {
super(message);
this.userId = null;
missingAuthorizations = new ArrayList<MissingAuthorization>();
}
public AuthorizationException(String userId, String permissionName, String resourceType, String resourceId) {
this(userId, new MissingAuthorization(permissionName, resourceType, resourceId));
}
public AuthorizationException(String userId, MissingAuthorization exceptionInfo) {
super(
"The user with id '"+userId+
"' does not have "+generateMissingAuthorizationMessage(exceptionInfo)+".");
this.userId = userId;
missingAuthorizations = new ArrayList<MissingAuthorization>();
missingAuthorizations.add(exceptionInfo);
this.resourceType = exceptionInfo.getResourceType();
this.permissionName = exceptionInfo.getViolatedPermissionName();
this.resourceId = exceptionInfo.getResourceId();
}
public AuthorizationException(String userId, List<MissingAuthorization> info) {
super(generateExceptionMessage(userId, info));
this.userId = userId;
this.missingAuthorizations = info;
}
/**
* @return the type of the resource if there
* is only one {@link MissingAuthorization}, {@code null} otherwise
*
* @deprecated Use {@link #getMissingAuthorizations()} to get the type of the resource
* of the {@link MissingAuthorization}(s). This method may be removed in future versions.
*/
@Deprecated
public String getResourceType() {
String resourceType = null;
if (missingAuthorizations.size() == 1) {
resourceType = missingAuthorizations.get(0).getResourceType();
}
return resourceType;
}
/**
* @return the type of the violated permission name if there
* is only one {@link MissingAuthorization}, {@code null} otherwise
*
* @deprecated Use {@link #getMissingAuthorizations()} to get the violated permission name
* of the {@link MissingAuthorization}(s). This method may be removed in future versions.
*/
@Deprecated
public String getViolatedPermissionName() {
if (missingAuthorizations.size() == 1) {
return missingAuthorizations.get(0).getViolatedPermissionName();
}
return null;
}
/**
* @return id of the user in which context the request was made and who misses authorizations
* to perform it successfully
*/
public String getUserId() {
return userId;
}
/**
* @return the id of the resource if there
* is only one {@link MissingAuthorization}, {@code null} otherwise
*
* @deprecated Use {@link #getMissingAuthorizations()} to get the id of the resource
* of the {@link MissingAuthorization}(s). This method may be removed in future versions.
*/
@Deprecated
public String getResourceId() {
if (missingAuthorizations.size() == 1) {
return missingAuthorizations.get(0).getResourceId();
}
return null;
}
/**
* @return Disjunctive list of {@link MissingAuthorization} from
* which a user needs to have at least one for the authorization to pass
*/
public List<MissingAuthorization> getMissingAuthorizations() {
return Collections.unmodifiableList(missingAuthorizations);
}
/**
* Generate exception message from the missing authorizations.
*
* @param userId to use
* @param missingAuthorizations to use
* @return The prepared exception message
*/
private static String generateExceptionMessage(String userId, List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("The user with id '");
sBuilder.append(userId);
sBuilder.append("' does not have one of the following permissions: ");
boolean first = true;
for(MissingAuthorization missingAuthorization: missingAuthorizations) {
if (!first) {
sBuilder.append(" or ");
} else {
first = false;
}
sBuilder.append(generateMissingAuthorizationMessage(missingAuthorization));
}
return sBuilder.toString();
}
/**
* Generated exception message for the missing authorization.
*
* @param exceptionInfo to use
*/
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) {
StringBuilder builder = new StringBuilder();
String permissionName = exceptionInfo.getViolatedPermissionName();
String resourceType = exceptionInfo.getResourceType();
String resourceId = exceptionInfo.getResourceId();
builder.append("'");
builder.append(permissionName);
builder.append("' permission on resource '");
builder.append((resourceId != null ? (resourceId+"' of type '") : "" ));
builder.append(resourceType);
builder.append("'");
return builder.toString();
}
}
| 1 | 12,607 | I like that we have this attribute here. However, I think the way we use it right now might be confusing in the future. For example, when only camunda admin is checked, this exception will be instantiated with a message and `missingAdminRole` is `false`. I think that is counter-intuitive. I would expect this exception to have `missingAdminRole` set to `true`. With this explicit information, the exception message could now be generated inside this exception class with the text block that is currently used in the authorization manager. We could maybe generally reuse that text block then also for the case where a user is no admin and also has none of the required permissions. I haven't tried it myself but I think it would be great if we could streamline those things a bit more if we're working on it now. Let me know what you think. | camunda-camunda-bpm-platform | java |
@@ -14,6 +14,9 @@ import com.google.flatbuffers.*;
public final class Monster extends Table {
public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); }
public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public static Monster getSizePrefixedRootAsMonster(ByteBuffer _psbb) { return getSizePrefixedRootAsMonster(_psbb, new Monster()); }
+ public static Monster getSizePrefixedRootAsMonster(ByteBuffer _psbb, Monster obj) { ByteBuffer _bb = _psbb.slice(); _bb.position(4); return getRootAsMonster(_bb, obj); }
+ public static int getSizePrefix(ByteBuffer _bb) { _bb.order(ByteOrder.LITTLE_ENDIAN); return _bb.getInt(_bb.position()); }
public static boolean MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); }
public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; }
public Monster __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } | 1 | // automatically generated by the FlatBuffers compiler, do not modify
package MyGame.Example;
import java.nio.*;
import java.lang.*;
import java.util.*;
import com.google.flatbuffers.*;
@SuppressWarnings("unused")
/**
* an example documentation comment: monster object
*/
public final class Monster extends Table {
public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); }
public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); }
public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; }
public Monster __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public Vec3 pos() { return pos(new Vec3()); }
public Vec3 pos(Vec3 obj) { int o = __offset(4); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; }
public short mana() { int o = __offset(6); return o != 0 ? bb.getShort(o + bb_pos) : 150; }
public boolean mutateMana(short mana) { int o = __offset(6); if (o != 0) { bb.putShort(o + bb_pos, mana); return true; } else { return false; } }
public short hp() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) : 100; }
public boolean mutateHp(short hp) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, hp); return true; } else { return false; } }
public String name() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(10, 1); }
public int inventory(int j) { int o = __offset(14); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; }
public int inventoryLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; }
public ByteBuffer inventoryAsByteBuffer() { return __vector_as_bytebuffer(14, 1); }
public boolean mutateInventory(int j, int inventory) { int o = __offset(14); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)inventory); return true; } else { return false; } }
public byte color() { int o = __offset(16); return o != 0 ? bb.get(o + bb_pos) : 8; }
public boolean mutateColor(byte color) { int o = __offset(16); if (o != 0) { bb.put(o + bb_pos, color); return true; } else { return false; } }
public byte testType() { int o = __offset(18); return o != 0 ? bb.get(o + bb_pos) : 0; }
public boolean mutateTestType(byte test_type) { int o = __offset(18); if (o != 0) { bb.put(o + bb_pos, test_type); return true; } else { return false; } }
public Table test(Table obj) { int o = __offset(20); return o != 0 ? __union(obj, o) : null; }
public Test test4(int j) { return test4(new Test(), j); }
public Test test4(Test obj, int j) { int o = __offset(22); return o != 0 ? obj.__assign(__vector(o) + j * 4, bb) : null; }
public int test4Length() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; }
public String testarrayofstring(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int testarrayofstringLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; }
/**
* an example documentation comment: this will end up in the generated code
* multiline too
*/
public Monster testarrayoftables(int j) { return testarrayoftables(new Monster(), j); }
public Monster testarrayoftables(Monster obj, int j) { int o = __offset(26); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int testarrayoftablesLength() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; }
public Monster testarrayoftablesByKey(String key) { int o = __offset(26); return o != 0 ? Monster.__lookup_by_key(__vector(o), key, bb) : null; }
public Monster enemy() { return enemy(new Monster()); }
public Monster enemy(Monster obj) { int o = __offset(28); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public int testnestedflatbuffer(int j) { int o = __offset(30); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; }
public int testnestedflatbufferLength() { int o = __offset(30); return o != 0 ? __vector_len(o) : 0; }
public ByteBuffer testnestedflatbufferAsByteBuffer() { return __vector_as_bytebuffer(30, 1); }
public Monster testnestedflatbufferAsMonster() { return testnestedflatbufferAsMonster(new Monster()); }
public Monster testnestedflatbufferAsMonster(Monster obj) { int o = __offset(30); return o != 0 ? obj.__assign(__indirect(__vector(o)), bb) : null; }
public boolean mutateTestnestedflatbuffer(int j, int testnestedflatbuffer) { int o = __offset(30); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)testnestedflatbuffer); return true; } else { return false; } }
public Stat testempty() { return testempty(new Stat()); }
public Stat testempty(Stat obj) { int o = __offset(32); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public boolean testbool() { int o = __offset(34); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public boolean mutateTestbool(boolean testbool) { int o = __offset(34); if (o != 0) { bb.put(o + bb_pos, (byte)(testbool ? 1 : 0)); return true; } else { return false; } }
public int testhashs32Fnv1() { int o = __offset(36); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public boolean mutateTesthashs32Fnv1(int testhashs32_fnv1) { int o = __offset(36); if (o != 0) { bb.putInt(o + bb_pos, testhashs32_fnv1); return true; } else { return false; } }
public long testhashu32Fnv1() { int o = __offset(38); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; }
public boolean mutateTesthashu32Fnv1(long testhashu32_fnv1) { int o = __offset(38); if (o != 0) { bb.putInt(o + bb_pos, (int)testhashu32_fnv1); return true; } else { return false; } }
public long testhashs64Fnv1() { int o = __offset(40); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateTesthashs64Fnv1(long testhashs64_fnv1) { int o = __offset(40); if (o != 0) { bb.putLong(o + bb_pos, testhashs64_fnv1); return true; } else { return false; } }
public long testhashu64Fnv1() { int o = __offset(42); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateTesthashu64Fnv1(long testhashu64_fnv1) { int o = __offset(42); if (o != 0) { bb.putLong(o + bb_pos, testhashu64_fnv1); return true; } else { return false; } }
public int testhashs32Fnv1a() { int o = __offset(44); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public boolean mutateTesthashs32Fnv1a(int testhashs32_fnv1a) { int o = __offset(44); if (o != 0) { bb.putInt(o + bb_pos, testhashs32_fnv1a); return true; } else { return false; } }
public long testhashu32Fnv1a() { int o = __offset(46); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; }
public boolean mutateTesthashu32Fnv1a(long testhashu32_fnv1a) { int o = __offset(46); if (o != 0) { bb.putInt(o + bb_pos, (int)testhashu32_fnv1a); return true; } else { return false; } }
public long testhashs64Fnv1a() { int o = __offset(48); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateTesthashs64Fnv1a(long testhashs64_fnv1a) { int o = __offset(48); if (o != 0) { bb.putLong(o + bb_pos, testhashs64_fnv1a); return true; } else { return false; } }
public long testhashu64Fnv1a() { int o = __offset(50); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateTesthashu64Fnv1a(long testhashu64_fnv1a) { int o = __offset(50); if (o != 0) { bb.putLong(o + bb_pos, testhashu64_fnv1a); return true; } else { return false; } }
public boolean testarrayofbools(int j) { int o = __offset(52); return o != 0 ? 0!=bb.get(__vector(o) + j * 1) : false; }
public int testarrayofboolsLength() { int o = __offset(52); return o != 0 ? __vector_len(o) : 0; }
public ByteBuffer testarrayofboolsAsByteBuffer() { return __vector_as_bytebuffer(52, 1); }
public boolean mutateTestarrayofbools(int j, boolean testarrayofbools) { int o = __offset(52); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)(testarrayofbools ? 1 : 0)); return true; } else { return false; } }
public float testf() { int o = __offset(54); return o != 0 ? bb.getFloat(o + bb_pos) : 3.14159f; }
public boolean mutateTestf(float testf) { int o = __offset(54); if (o != 0) { bb.putFloat(o + bb_pos, testf); return true; } else { return false; } }
public float testf2() { int o = __offset(56); return o != 0 ? bb.getFloat(o + bb_pos) : 3.0f; }
public boolean mutateTestf2(float testf2) { int o = __offset(56); if (o != 0) { bb.putFloat(o + bb_pos, testf2); return true; } else { return false; } }
public float testf3() { int o = __offset(58); return o != 0 ? bb.getFloat(o + bb_pos) : 0.0f; }
public boolean mutateTestf3(float testf3) { int o = __offset(58); if (o != 0) { bb.putFloat(o + bb_pos, testf3); return true; } else { return false; } }
public String testarrayofstring2(int j) { int o = __offset(60); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int testarrayofstring2Length() { int o = __offset(60); return o != 0 ? __vector_len(o) : 0; }
public Ability testarrayofsortedstruct(int j) { return testarrayofsortedstruct(new Ability(), j); }
public Ability testarrayofsortedstruct(Ability obj, int j) { int o = __offset(62); return o != 0 ? obj.__assign(__vector(o) + j * 8, bb) : null; }
public int testarrayofsortedstructLength() { int o = __offset(62); return o != 0 ? __vector_len(o) : 0; }
public int flex(int j) { int o = __offset(64); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; }
public int flexLength() { int o = __offset(64); return o != 0 ? __vector_len(o) : 0; }
public ByteBuffer flexAsByteBuffer() { return __vector_as_bytebuffer(64, 1); }
public boolean mutateFlex(int j, int flex) { int o = __offset(64); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)flex); return true; } else { return false; } }
public Test test5(int j) { return test5(new Test(), j); }
public Test test5(Test obj, int j) { int o = __offset(66); return o != 0 ? obj.__assign(__vector(o) + j * 4, bb) : null; }
public int test5Length() { int o = __offset(66); return o != 0 ? __vector_len(o) : 0; }
public long vectorOfLongs(int j) { int o = __offset(68); return o != 0 ? bb.getLong(__vector(o) + j * 8) : 0; }
public int vectorOfLongsLength() { int o = __offset(68); return o != 0 ? __vector_len(o) : 0; }
public ByteBuffer vectorOfLongsAsByteBuffer() { return __vector_as_bytebuffer(68, 8); }
public boolean mutateVectorOfLongs(int j, long vector_of_longs) { int o = __offset(68); if (o != 0) { bb.putLong(__vector(o) + j * 8, vector_of_longs); return true; } else { return false; } }
public double vectorOfDoubles(int j) { int o = __offset(70); return o != 0 ? bb.getDouble(__vector(o) + j * 8) : 0; }
public int vectorOfDoublesLength() { int o = __offset(70); return o != 0 ? __vector_len(o) : 0; }
public ByteBuffer vectorOfDoublesAsByteBuffer() { return __vector_as_bytebuffer(70, 8); }
public boolean mutateVectorOfDoubles(int j, double vector_of_doubles) { int o = __offset(70); if (o != 0) { bb.putDouble(__vector(o) + j * 8, vector_of_doubles); return true; } else { return false; } }
public MyGame.InParentNamespace parentNamespaceTest() { return parentNamespaceTest(new MyGame.InParentNamespace()); }
public MyGame.InParentNamespace parentNamespaceTest(MyGame.InParentNamespace obj) { int o = __offset(72); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public static void startMonster(FlatBufferBuilder builder) { builder.startObject(35); }
public static void addPos(FlatBufferBuilder builder, int posOffset) { builder.addStruct(0, posOffset, 0); }
public static void addMana(FlatBufferBuilder builder, short mana) { builder.addShort(1, mana, 150); }
public static void addHp(FlatBufferBuilder builder, short hp) { builder.addShort(2, hp, 100); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(3, nameOffset, 0); }
public static void addInventory(FlatBufferBuilder builder, int inventoryOffset) { builder.addOffset(5, inventoryOffset, 0); }
public static int createInventoryVector(FlatBufferBuilder builder, byte[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addByte(data[i]); return builder.endVector(); }
public static void startInventoryVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); }
public static void addColor(FlatBufferBuilder builder, byte color) { builder.addByte(6, color, 8); }
public static void addTestType(FlatBufferBuilder builder, byte testType) { builder.addByte(7, testType, 0); }
public static void addTest(FlatBufferBuilder builder, int testOffset) { builder.addOffset(8, testOffset, 0); }
public static void addTest4(FlatBufferBuilder builder, int test4Offset) { builder.addOffset(9, test4Offset, 0); }
public static void startTest4Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 2); }
public static void addTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.addOffset(10, testarrayofstringOffset, 0); }
public static int createTestarrayofstringVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.addOffset(11, testarrayoftablesOffset, 0); }
public static int createTestarrayoftablesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addEnemy(FlatBufferBuilder builder, int enemyOffset) { builder.addOffset(12, enemyOffset, 0); }
public static void addTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.addOffset(13, testnestedflatbufferOffset, 0); }
public static int createTestnestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addByte(data[i]); return builder.endVector(); }
public static void startTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); }
public static void addTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.addOffset(14, testemptyOffset, 0); }
public static void addTestbool(FlatBufferBuilder builder, boolean testbool) { builder.addBoolean(15, testbool, false); }
public static void addTesthashs32Fnv1(FlatBufferBuilder builder, int testhashs32Fnv1) { builder.addInt(16, testhashs32Fnv1, 0); }
public static void addTesthashu32Fnv1(FlatBufferBuilder builder, long testhashu32Fnv1) { builder.addInt(17, (int)testhashu32Fnv1, (int)0L); }
public static void addTesthashs64Fnv1(FlatBufferBuilder builder, long testhashs64Fnv1) { builder.addLong(18, testhashs64Fnv1, 0L); }
public static void addTesthashu64Fnv1(FlatBufferBuilder builder, long testhashu64Fnv1) { builder.addLong(19, testhashu64Fnv1, 0L); }
public static void addTesthashs32Fnv1a(FlatBufferBuilder builder, int testhashs32Fnv1a) { builder.addInt(20, testhashs32Fnv1a, 0); }
public static void addTesthashu32Fnv1a(FlatBufferBuilder builder, long testhashu32Fnv1a) { builder.addInt(21, (int)testhashu32Fnv1a, (int)0L); }
public static void addTesthashs64Fnv1a(FlatBufferBuilder builder, long testhashs64Fnv1a) { builder.addLong(22, testhashs64Fnv1a, 0L); }
public static void addTesthashu64Fnv1a(FlatBufferBuilder builder, long testhashu64Fnv1a) { builder.addLong(23, testhashu64Fnv1a, 0L); }
public static void addTestarrayofbools(FlatBufferBuilder builder, int testarrayofboolsOffset) { builder.addOffset(24, testarrayofboolsOffset, 0); }
public static int createTestarrayofboolsVector(FlatBufferBuilder builder, boolean[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addBoolean(data[i]); return builder.endVector(); }
public static void startTestarrayofboolsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); }
public static void addTestf(FlatBufferBuilder builder, float testf) { builder.addFloat(25, testf, 3.14159f); }
public static void addTestf2(FlatBufferBuilder builder, float testf2) { builder.addFloat(26, testf2, 3.0f); }
public static void addTestf3(FlatBufferBuilder builder, float testf3) { builder.addFloat(27, testf3, 0.0f); }
public static void addTestarrayofstring2(FlatBufferBuilder builder, int testarrayofstring2Offset) { builder.addOffset(28, testarrayofstring2Offset, 0); }
public static int createTestarrayofstring2Vector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startTestarrayofstring2Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addTestarrayofsortedstruct(FlatBufferBuilder builder, int testarrayofsortedstructOffset) { builder.addOffset(29, testarrayofsortedstructOffset, 0); }
public static void startTestarrayofsortedstructVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 4); }
public static void addFlex(FlatBufferBuilder builder, int flexOffset) { builder.addOffset(30, flexOffset, 0); }
public static int createFlexVector(FlatBufferBuilder builder, byte[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addByte(data[i]); return builder.endVector(); }
public static void startFlexVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); }
public static void addTest5(FlatBufferBuilder builder, int test5Offset) { builder.addOffset(31, test5Offset, 0); }
public static void startTest5Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 2); }
public static void addVectorOfLongs(FlatBufferBuilder builder, int vectorOfLongsOffset) { builder.addOffset(32, vectorOfLongsOffset, 0); }
public static int createVectorOfLongsVector(FlatBufferBuilder builder, long[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addLong(data[i]); return builder.endVector(); }
public static void startVectorOfLongsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); }
public static void addVectorOfDoubles(FlatBufferBuilder builder, int vectorOfDoublesOffset) { builder.addOffset(33, vectorOfDoublesOffset, 0); }
public static int createVectorOfDoublesVector(FlatBufferBuilder builder, double[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addDouble(data[i]); return builder.endVector(); }
public static void startVectorOfDoublesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); }
public static void addParentNamespaceTest(FlatBufferBuilder builder, int parentNamespaceTestOffset) { builder.addOffset(34, parentNamespaceTestOffset, 0); }
public static int endMonster(FlatBufferBuilder builder) {
int o = builder.endObject();
builder.required(o, 10); // name
return o;
}
public static void finishMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "MONS"); }
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(10, o1, _bb), __offset(10, o2, _bb), _bb); }
public static Monster __lookup_by_key(int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(Table.UTF8_CHARSET.get());
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(10, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return new Monster().__assign(tableOffset, bb);
}
}
return null;
}
}
| 1 | 12,451 | Not sure why we're creating a new `ByteBuffer` here, ideally this refers to the existing one? | google-flatbuffers | java |
@@ -45,10 +45,11 @@ import getNoDataComponent from '../../../../components/legacy-notifications/noda
import getDataErrorComponent from '../../../../components/legacy-notifications/data-error';
import HelpLink from '../../../../components/HelpLink';
import { getCurrentDateRangeDayCount } from '../../../../util/date-range';
-import { STORE_NAME } from '../../datastore/constants';
+import { STORE_NAME, DATE_RANGE_OFFSET } from '../../datastore/constants';
import { CORE_USER } from '../../../../googlesitekit/datastore/user/constants';
import { CORE_SITE } from '../../../../googlesitekit/datastore/site/constants';
import { untrailingslashit } from '../../../../util';
+import { generateDateRangeArgs } from '../../util/report-date-range-args';
const { useSelect } = Data;
| 1 | /**
* GoogleSitekitSearchConsoleDashboardWidget component.
*
* Site Kit by Google, Copyright 2021 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
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { Fragment, useState } from '@wordpress/element';
import { __, _n, _x, sprintf } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import SearchConsoleIcon from '../../../../../svg/search-console.svg';
import Header from '../../../../components/Header';
import SearchConsoleDashboardWidgetSiteStats from './SearchConsoleDashboardWidgetSiteStats';
import LegacySearchConsoleDashboardWidgetKeywordTable from './LegacySearchConsoleDashboardWidgetKeywordTable';
import SearchConsoleDashboardWidgetOverview from './SearchConsoleDashboardWidgetOverview';
import DateRangeSelector from '../../../../components/DateRangeSelector';
import PageHeader from '../../../../components/PageHeader';
import Layout from '../../../../components/layout/Layout';
import Alert from '../../../../components/Alert';
import ProgressBar from '../../../../components/ProgressBar';
import getNoDataComponent from '../../../../components/legacy-notifications/nodata';
import getDataErrorComponent from '../../../../components/legacy-notifications/data-error';
import HelpLink from '../../../../components/HelpLink';
import { getCurrentDateRangeDayCount } from '../../../../util/date-range';
import { STORE_NAME } from '../../datastore/constants';
import { CORE_USER } from '../../../../googlesitekit/datastore/user/constants';
import { CORE_SITE } from '../../../../googlesitekit/datastore/site/constants';
import { untrailingslashit } from '../../../../util';
const { useSelect } = Data;
const GoogleSitekitSearchConsoleDashboardWidget = () => {
const [ selectedStats, setSelectedStats ] = useState( [ 0, 1 ] );
const [ receivingData, setReceivingData ] = useState( true );
const [ error, setError ] = useState( false );
const [ errorObj, setErrorObject ] = useState();
const [ loading, setLoading ] = useState( true );
const dateRange = useSelect( ( select ) => select( CORE_USER ).getDateRange() );
const propertyID = useSelect( ( select ) => select( STORE_NAME ).getPropertyID() );
const isDomainProperty = useSelect( ( select ) => select( STORE_NAME ).isDomainProperty() );
const referenceSiteURL = useSelect( ( select ) => {
return untrailingslashit( select( CORE_SITE ).getReferenceSiteURL() );
} );
const searchConsoleDeepArgs = {
resource_id: propertyID,
num_of_days: getCurrentDateRangeDayCount(),
};
if ( isDomainProperty && referenceSiteURL ) {
searchConsoleDeepArgs.page = `*${ referenceSiteURL }`;
}
const searchConsoleDeepLink = useSelect( ( select ) => select( STORE_NAME ).getServiceURL(
{
path: '/performance/search-analytics',
query: searchConsoleDeepArgs,
} ) );
/**
* Handles data errors from the contained AdSense component(s).
*
* Currently handled in the SearchConsoleDashboardWidgetOverview component.
*
* If this component's API data calls returns an error, the error message is passed to this callback, resulting in the display of an error Notification.
*
* If the component detects no data - in this case all 0s - the callback is called without an error message,
* resulting in the display of a CTA.
*
* @since 1.0.0
*
* @param {string} receivedError A potential error string.
* @param {Object} receivedErrorObj Full error object.
*/
const handleDataError = ( receivedError, receivedErrorObj ) => {
setReceivingData( false );
setError( receivedError );
setErrorObject( receivedErrorObj );
setLoading( false );
};
/**
* Sets loading to `false` and "receiving data" to `true` until data starts to resolve.
*/
const handleDataSuccess = () => {
setReceivingData( true );
setLoading( false );
};
const handleStatSelection = ( stat ) => {
let newStats = selectedStats.slice();
if ( selectedStats.includes( stat ) ) {
newStats = selectedStats.filter( ( selected ) => stat !== selected );
} else {
newStats.push( stat );
}
if ( 0 === newStats.length ) {
return;
}
setSelectedStats( newStats );
};
const buildSeries = () => {
const colorMap = {
0: '#4285f4',
1: '#27bcd4',
2: '#1b9688',
3: '#673ab7',
};
return selectedStats.map( function( stat, i ) {
return { color: colorMap[ stat ], targetAxisIndex: i };
} );
};
const buildVAxes = () => {
const vAxesMap = {
0: __( 'Clicks', 'google-site-kit' ),
1: __( 'Impressions', 'google-site-kit' ),
2: __( 'Average CTR', 'google-site-kit' ),
3: __( 'Average Position', 'google-site-kit' ),
};
return selectedStats.map( function( stat ) {
const otherSettings = {};
// The third index refers to the "Average Position" stat.
// We need to reverse the y-axis for this stat, see:
// https://github.com/google/site-kit-wp/issues/874
if ( stat === 3 ) {
otherSettings.direction = -1;
}
return { title: vAxesMap[ stat ], ...otherSettings };
} );
};
const series = buildSeries();
const vAxes = buildVAxes();
// Hide AdSense data display when we don't have data.
const wrapperClass = ! loading && receivingData ? '' : 'googlesitekit-nodata';
const currentDayCount = getCurrentDateRangeDayCount( dateRange );
return (
<Fragment>
<Header>
<DateRangeSelector />
</Header>
<Alert module="search-console" />
<div className="googlesitekit-module-page googlesitekit-module-page--search-console">
<div className="mdc-layout-grid">
<div className="mdc-layout-grid__inner">
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-12
">
<PageHeader
title={ _x( 'Search Console', 'Service name', 'google-site-kit' ) }
icon={
<SearchConsoleIcon
className="googlesitekit-page-header__icon"
height="21"
width="23"
/>
}
status="connected"
statusText={ sprintf(
/* translators: %s: module name. */
__( '%s is connected', 'google-site-kit' ),
_x( 'Search Console', 'Service name', 'google-site-kit' )
) }
/>
{ loading && <ProgressBar /> }
</div>
{ /* Data issue: on error display a notification. On missing data: display a CTA. */ }
{ ! receivingData && (
error ? getDataErrorComponent( 'search-console', error, true, true, true, errorObj ) : getNoDataComponent( _x( 'Search Console', 'Service name', 'google-site-kit' ), true, true, true )
) }
<div className={ classnames(
'mdc-layout-grid__cell',
'mdc-layout-grid__cell--span-12',
wrapperClass
) }>
<Layout
header
title={ sprintf(
/* translators: %s: number of days */
_n( 'Overview for the last %s day', 'Overview for the last %s days', currentDayCount, 'google-site-kit', ),
currentDayCount,
) }
headerCTALabel={ sprintf(
/* translators: %s: module name. */
__( 'See full stats in %s', 'google-site-kit' ),
_x( 'Search Console', 'Service name', 'google-site-kit' )
) }
headerCTALink={ searchConsoleDeepLink }
>
<SearchConsoleDashboardWidgetOverview
selectedStats={ selectedStats }
handleStatSelection={ handleStatSelection }
handleDataError={ handleDataError }
handleDataSuccess={ handleDataSuccess }
/>
<SearchConsoleDashboardWidgetSiteStats selectedStats={ selectedStats } series={ series } vAxes={ vAxes } />
</Layout>
</div>
<div className={ classnames(
'mdc-layout-grid__cell',
'mdc-layout-grid__cell--span-12',
wrapperClass
) }>
<Layout
/* translators: %s: number of days */
title={ sprintf(
/* translators: %s: number of days */
_n( 'Top search queries over the last %s day', 'Top search queries over last %s days', currentDayCount, 'google-site-kit', ),
currentDayCount,
) }
header
footer
headerCTALabel={ sprintf(
/* translators: %s: module name. */
__( 'See full stats in %s', 'google-site-kit' ),
_x( 'Search Console', 'Service name', 'google-site-kit' )
) }
headerCTALink={ searchConsoleDeepLink }
footerCTALabel={ _x( 'Search Console', 'Service name', 'google-site-kit' ) }
footerCTALink={ searchConsoleDeepLink }
>
<LegacySearchConsoleDashboardWidgetKeywordTable />
</Layout>
</div>
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-12
mdc-layout-grid__cell--align-right
">
<HelpLink />
</div>
</div>
</div>
</div>
</Fragment>
);
};
export default GoogleSitekitSearchConsoleDashboardWidget;
| 1 | 35,493 | Same here re: `STORE_NAME` to `MODULES_SEARCH_CONSOLE`. | google-site-kit-wp | js |
@@ -21,11 +21,14 @@ async function proceedToSetUpAnalytics() {
await Promise.all( [
expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up analytics/i } ),
page.waitForSelector( '.googlesitekit-setup-module--analytics' ),
- page.waitForResponse( ( res ) => res.url().match( 'analytics/data' ) ),
+ page.waitForResponse( ( res ) => res.url().match( 'analytics/data/accounts-properties-profiles' ) ),
] );
}
-const EXISTING_PROPERTY_ID = 'UA-00000001-1';
+const existingTag = {
+ accountID: '999',
+ propertyID: 'UA-999-9',
+};
describe( 'setting up the Analytics module with no existing account and with an existing tag', () => {
beforeAll( async () => { | 1 | /**
* WordPress dependencies
*/
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';
/**
* Internal dependencies
*/
import {
deactivateUtilityPlugins,
resetSiteKit,
setAnalyticsExistingPropertyID,
setAuthToken,
setClientConfig,
setSearchConsoleProperty,
setSiteVerification,
useRequestInterception,
} from '../../../utils';
async function proceedToSetUpAnalytics() {
await Promise.all( [
expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up analytics/i } ),
page.waitForSelector( '.googlesitekit-setup-module--analytics' ),
page.waitForResponse( ( res ) => res.url().match( 'analytics/data' ) ),
] );
}
const EXISTING_PROPERTY_ID = 'UA-00000001-1';
describe( 'setting up the Analytics module with no existing account and with an existing tag', () => {
beforeAll( async () => {
await page.setRequestInterception( true );
useRequestInterception( ( request ) => {
if ( request.url().match( 'modules/analytics/data/tag-permission' ) ) {
request.respond( {
status: 403,
body: JSON.stringify( {
code: 'google_analytics_existing_tag_permission',
message: 'google_analytics_existing_tag_permission',
} ),
} );
} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
request.respond( {
status: 200,
} );
} else {
request.continue();
}
} );
} );
beforeEach( async () => {
await activatePlugin( 'e2e-tests-auth-plugin' );
await activatePlugin( 'e2e-tests-analytics-existing-tag' );
await activatePlugin( 'e2e-tests-module-setup-analytics-api-mock-no-account' );
await setClientConfig();
await setAuthToken();
await setSiteVerification();
await setSearchConsoleProperty();
await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
await page.waitForSelector( '.mdc-tab-bar' );
await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
await page.waitForSelector( '.googlesitekit-settings-connect-module--analytics' );
} );
afterEach( async () => {
await deactivateUtilityPlugins();
await resetSiteKit();
} );
it( 'does not allow Analytics to be set up with an existing tag that does not match a property of the user', async () => {
await setAnalyticsExistingPropertyID( EXISTING_PROPERTY_ID );
await proceedToSetUpAnalytics();
// The specific message comes from the datapoint which we've mocked to return the error code instead.
await expect( page ).toMatchElement( '.googlesitekit-setup-module--analytics p', { text: /google_analytics_existing_tag_permission/i } );
// Buttons to proceed are not displayed; the user is blocked from completing setup.
await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics button', { text: /create an account/i } );
await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics button', { text: /re-fetch my account/i } );
} );
} );
| 1 | 27,094 | I could've sworn I got a `403` myself when I got that response locally. Is `200` what the API would send back for a `permission: false` tag? | google-site-kit-wp | js |
@@ -11,13 +11,13 @@ import (
"strings"
)
-type identityManager struct {
- keystoreManager keystoreInterface
+type IdentityManager struct {
+ KeystoreManager keystoreInterface
}
-func NewIdentityManager(keydir string) *identityManager {
- return &identityManager{
- keystoreManager: keystore.NewKeyStore(keydir, keystore.StandardScryptN, keystore.StandardScryptP),
+func NewIdentityManager(keydir string) *IdentityManager {
+ return &IdentityManager{
+ KeystoreManager: keystore.NewKeyStore(keydir, keystore.StandardScryptN, keystore.StandardScryptP),
}
}
| 1 | // Maps Ethereum account to dto.Identity.
// Currently creates a new eth account with password on CreateNewIdentity().
package identity
import (
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/mysterium/node/service_discovery/dto"
"strings"
)
type identityManager struct {
keystoreManager keystoreInterface
}
func NewIdentityManager(keydir string) *identityManager {
return &identityManager{
keystoreManager: keystore.NewKeyStore(keydir, keystore.StandardScryptN, keystore.StandardScryptP),
}
}
func accountToIdentity(account accounts.Account) *dto.Identity {
identity := dto.Identity(account.Address.Hex())
return &identity
}
func identityToAccount(identityString string) accounts.Account {
return accounts.Account{
Address: common.HexToAddress(identityString),
}
}
func (idm *identityManager) CreateNewIdentity(passphrase string) (*dto.Identity, error) {
account, err := idm.keystoreManager.NewAccount(passphrase)
if err != nil {
return nil, err
}
return accountToIdentity(account), nil
}
func (idm *identityManager) GetIdentities() []dto.Identity {
accountList := idm.keystoreManager.Accounts()
var ids = make([]dto.Identity, len(accountList))
for i, account := range accountList {
ids[i] = *accountToIdentity(account)
}
return ids
}
func (idm *identityManager) GetIdentity(identityString string) *dto.Identity {
identityString = strings.ToLower(identityString)
for _, id := range idm.GetIdentities() {
if strings.ToLower(string(id)) == identityString {
return &id
}
}
return nil
}
func (idm *identityManager) HasIdentity(identityString string) bool {
return idm.GetIdentity(identityString) != nil
}
| 1 | 9,668 | This attribute was intentionally private. - lets force usage of factory `NewIdentityManager()` - lets ramake to `NewIdentityManager(keydir string)` -> `NewIdentityManager(keystore keystoreManager)` | mysteriumnetwork-node | go |
@@ -34,6 +34,10 @@ import (
const transportName = "redis"
+const maxConnectRetries = 100
+
+var connectRetryDelay = 10 * time.Millisecond
+
// Inbound is a redis inbound that reads from the given queueKey. This will
// wait for an item in the queue or until the timout is reached before trying
// to read again. | 1 | // Copyright (c) 2016 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 redis
import (
"context"
"time"
"go.uber.org/yarpc/api/transport"
"go.uber.org/yarpc/internal/errors"
"go.uber.org/yarpc/internal/sync"
"go.uber.org/yarpc/serialize"
"github.com/opentracing/opentracing-go"
)
const transportName = "redis"
// Inbound is a redis inbound that reads from the given queueKey. This will
// wait for an item in the queue or until the timout is reached before trying
// to read again.
type Inbound struct {
router transport.Router
tracer opentracing.Tracer
client Client
timeout time.Duration
queueKey string
processingKey string
stop chan struct{}
once sync.LifecycleOnce
}
// NewInbound creates a redis Inbound that satisfies transport.Inbound.
//
// queueKey - key for the queue in redis
// processingKey - key for the list we'll store items we've popped from the queue
// timeout - how long the inbound will block on reading from redis
func NewInbound(client Client, queueKey, processingKey string, timeout time.Duration) *Inbound {
return &Inbound{
tracer: opentracing.GlobalTracer(),
client: client,
timeout: timeout,
queueKey: queueKey,
processingKey: processingKey,
stop: make(chan struct{}),
}
}
// Transports returns nil for now
func (i *Inbound) Transports() []transport.Transport {
// TODO
return nil
}
// WithTracer configures a tracer on this inbound.
func (i *Inbound) WithTracer(tracer opentracing.Tracer) *Inbound {
i.tracer = tracer
return i
}
// WithRouter configures a router to handle incoming requests,
// as a chained method for convenience.
func (i *Inbound) WithRouter(router transport.Router) *Inbound {
i.router = router
return i
}
// SetRouter configures a router to handle incoming requests.
// This satisfies the transport.Inbound interface, and would be called
// by a dispatcher when it starts.
func (i *Inbound) SetRouter(router transport.Router) {
i.router = router
}
// Start starts the inbound, reading from the queueKey
func (i *Inbound) Start() error {
return i.once.Start(i.start)
}
func (i *Inbound) start() error {
if i.router == nil {
return errors.ErrNoRouter
}
err := i.client.Start()
if err != nil {
return err
}
go i.startLoop()
return nil
}
func (i *Inbound) startLoop() {
for {
select {
case <-i.stop:
return
default:
// TODO: logging
i.handle()
}
}
}
// Stop ends the connection to redis
func (i *Inbound) Stop() error {
return i.once.Stop(i.stopClient)
}
func (i *Inbound) stopClient() error {
close(i.stop)
return i.client.Stop()
}
// IsRunning returns whether the inbound is still processing requests.
func (i *Inbound) IsRunning() bool {
return i.once.IsRunning()
}
func (i *Inbound) handle() error {
// TODO: logging
item, err := i.client.BRPopLPush(i.queueKey, i.processingKey, i.timeout)
if err != nil {
return err
}
defer i.client.LRem(i.queueKey, item)
start := time.Now()
spanContext, req, err := serialize.FromBytes(i.tracer, item)
if err != nil {
return err
}
extractOpenTracingSpan := transport.ExtractOpenTracingSpan{
ParentSpanContext: spanContext,
Tracer: i.tracer,
TransportName: transportName,
StartTime: start,
}
ctx, span := extractOpenTracingSpan.Do(context.Background(), req)
defer span.Finish()
if err := transport.ValidateRequest(req); err != nil {
return transport.UpdateSpanWithErr(span, err)
}
spec, err := i.router.Choose(ctx, req)
if err != nil {
return transport.UpdateSpanWithErr(span, err)
}
if spec.Type() != transport.Oneway {
err = errors.UnsupportedTypeError{Transport: transportName, Type: string(spec.Type())}
return transport.UpdateSpanWithErr(span, err)
}
return transport.DispatchOnewayHandler(ctx, spec.Oneway(), req)
}
| 1 | 11,998 | Is this too frequent? | yarpc-yarpc-go | go |
@@ -21,6 +21,7 @@ class UploadModel
{
private const FILE_EXTENSIONS = [
'csv',
+ 'zip',
];
/** | 1 | <?php
/**
* Copyright © Bold Brand Commerce Sp. z o.o. All rights reserved.
* See LICENSE.txt for license details.
*/
declare(strict_types = 1);
namespace Ergonode\Importer\Application\Model\Form;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @Vich\Uploadable()
*/
class UploadModel
{
private const FILE_EXTENSIONS = [
'csv',
];
/**
* @Assert\File(maxSize="500M")
*
* @Vich\UploadableField(mapping="attachment", fileNameProperty="fileName", size="fileSize")
*
* @var UploadedFile
*/
public ?UploadedFile $upload = null;
/**
* @Assert\Callback
*
* @param ExecutionContextInterface $context
*/
public function validate(ExecutionContextInterface $context): void
{
$isFileExtensionValid = \in_array($this->upload->getClientOriginalExtension(), self::FILE_EXTENSIONS, true);
if ($this->upload && !$isFileExtensionValid) {
$context
->buildViolation(sprintf('%s not allowed file type', $this->upload->getClientOriginalExtension()))
->setTranslationDomain('file')
->atPath('upload')
->addViolation();
}
}
}
| 1 | 8,926 | will this not make it possible to use a zip file, e.g. on other importers who do not have to support it ? | ergonode-backend | php |
@@ -34,6 +34,7 @@ from .http import UpstreamConnectLayer
from .http1 import Http1Layer
from .http2 import Http2Layer
from .rawtcp import RawTCPLayer
+from .socks_client import SocksClientLayer
__all__ = [
"Layer", "ServerConnectionMixin", "Kill", | 1 | """
In mitmproxy, protocols are implemented as a set of layers, which are composed on top each other.
The first layer is usually the proxy mode, e.g. transparent proxy or normal HTTP proxy. Next,
various protocol layers are stacked on top of each other - imagine WebSockets on top of an HTTP
Upgrade request. An actual mitmproxy connection may look as follows (outermost layer first):
Transparent HTTP proxy, no TLS:
- TransparentProxy
- Http1Layer
- HttpLayer
Regular proxy, CONNECT request with WebSockets over SSL:
- ReverseProxy
- Http1Layer
- HttpLayer
- TLSLayer
- WebsocketLayer (or TCPLayer)
Every layer acts as a read-only context for its inner layers (see :py:class:`Layer`). To communicate
with an outer layer, a layer can use functions provided in the context. The next layer is always
determined by a call to :py:meth:`.next_layer() <mitmproxy.proxy.RootContext.next_layer>`,
which is provided by the root context.
Another subtle design goal of this architecture is that upstream connections should be established
as late as possible; this makes server replay without any outgoing connections possible.
"""
from __future__ import (absolute_import, print_function, division)
from .base import Layer, ServerConnectionMixin, Kill
from .tls import TlsLayer
from .tls import is_tls_record_magic
from .tls import TlsClientHello
from .http import UpstreamConnectLayer
from .http1 import Http1Layer
from .http2 import Http2Layer
from .rawtcp import RawTCPLayer
__all__ = [
"Layer", "ServerConnectionMixin", "Kill",
"TlsLayer", "is_tls_record_magic", "TlsClientHello",
"UpstreamConnectLayer",
"Http1Layer",
"Http2Layer",
"RawTCPLayer",
]
| 1 | 11,270 | Needs to be mentioned in `__all__` below. | mitmproxy-mitmproxy | py |
@@ -349,6 +349,13 @@ signalfd_thread_exit(dcontext_t *dcontext, thread_sig_info_t *info)
TABLE_RWLOCK(sigfd_table, write, unlock);
}
+bool
+is_repeat_handle_pre_extended_syscall_sigmasks(dcontext_t *dcontext)
+{
+ thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
+ return info->pre_syscall_app_sigprocmask_valid;
+}
+
bool
handle_pre_extended_syscall_sigmasks(dcontext_t *dcontext, kernel_sigset_t *sigmask,
size_t sizemask) | 1 | /* **********************************************************
* Copyright (c) 2011-2018 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 */
/*
* signal_linux.c - Linux-specific signal code
*/
#include "signal_private.h" /* pulls in globals.h for us, in right order */
#ifndef LINUX
# error Linux-only
#endif
#include "arch.h"
#include "../hashtable.h"
#include "include/syscall.h"
#include <errno.h>
#undef errno
/* important reference files:
* /usr/include/asm/signal.h
* /usr/include/asm/siginfo.h
* /usr/include/asm/ucontext.h
* /usr/include/asm/sigcontext.h
* /usr/include/sys/ucontext.h (see notes below...asm one is more useful)
* /usr/include/bits/sigaction.h
* /usr/src/linux/kernel/signal.c
* /usr/src/linux/arch/i386/kernel/signal.c
* /usr/src/linux/include/asm-i386/signal.h
* /usr/src/linux/include/asm-i386/sigcontext.h
* /usr/src/linux/include/asm-i386/ucontext.h
* /usr/src/linux/include/linux/signal.h
* /usr/src/linux/include/linux/sched.h (sas_ss_flags, on_sig_stack)
* ditto with x86_64, plus:
* /usr/src/linux/arch/x86_64/ia32/ia32_signal.c
*/
int default_action[] = {
/* nothing 0 */ DEFAULT_IGNORE,
/* SIGHUP 1 */ DEFAULT_TERMINATE,
/* SIGINT 2 */ DEFAULT_TERMINATE,
/* SIGQUIT 3 */ DEFAULT_TERMINATE_CORE,
/* SIGILL 4 */ DEFAULT_TERMINATE_CORE,
/* SIGTRAP 5 */ DEFAULT_TERMINATE_CORE,
/* SIGABRT/SIGIOT 6 */ DEFAULT_TERMINATE_CORE,
/* SIGBUS 7 */ DEFAULT_TERMINATE, /* should be CORE */
/* SIGFPE 8 */ DEFAULT_TERMINATE_CORE,
/* SIGKILL 9 */ DEFAULT_TERMINATE,
/* SIGUSR1 10 */ DEFAULT_TERMINATE,
/* SIGSEGV 11 */ DEFAULT_TERMINATE_CORE,
/* SIGUSR2 12 */ DEFAULT_TERMINATE,
/* SIGPIPE 13 */ DEFAULT_TERMINATE,
/* SIGALRM 14 */ DEFAULT_TERMINATE,
/* SIGTERM 15 */ DEFAULT_TERMINATE,
/* SIGSTKFLT 16 */ DEFAULT_TERMINATE,
/* SIGCHLD 17 */ DEFAULT_IGNORE,
/* SIGCONT 18 */ DEFAULT_CONTINUE,
/* SIGSTOP 19 */ DEFAULT_STOP,
/* SIGTSTP 20 */ DEFAULT_STOP,
/* SIGTTIN 21 */ DEFAULT_STOP,
/* SIGTTOU 22 */ DEFAULT_STOP,
/* SIGURG 23 */ DEFAULT_IGNORE,
/* SIGXCPU 24 */ DEFAULT_TERMINATE,
/* SIGXFSZ 25 */ DEFAULT_TERMINATE,
/* SIGVTALRM 26 */ DEFAULT_TERMINATE,
/* SIGPROF 27 */ DEFAULT_TERMINATE,
/* SIGWINCH 28 */ DEFAULT_IGNORE,
/* SIGIO/SIGPOLL/SIGLOST 29 */ DEFAULT_TERMINATE,
/* SIGPWR 30 */ DEFAULT_TERMINATE,
/* SIGSYS/SIGUNUSED 31 */ DEFAULT_TERMINATE,
/* ASSUMPTION: all real-time have default of terminate...XXX: ok? */
/* 32 */ DEFAULT_TERMINATE,
/* 33 */ DEFAULT_TERMINATE,
/* 34 */ DEFAULT_TERMINATE,
/* 35 */ DEFAULT_TERMINATE,
/* 36 */ DEFAULT_TERMINATE,
/* 37 */ DEFAULT_TERMINATE,
/* 38 */ DEFAULT_TERMINATE,
/* 39 */ DEFAULT_TERMINATE,
/* 40 */ DEFAULT_TERMINATE,
/* 41 */ DEFAULT_TERMINATE,
/* 42 */ DEFAULT_TERMINATE,
/* 43 */ DEFAULT_TERMINATE,
/* 44 */ DEFAULT_TERMINATE,
/* 45 */ DEFAULT_TERMINATE,
/* 46 */ DEFAULT_TERMINATE,
/* 47 */ DEFAULT_TERMINATE,
/* 48 */ DEFAULT_TERMINATE,
/* 49 */ DEFAULT_TERMINATE,
/* 50 */ DEFAULT_TERMINATE,
/* 51 */ DEFAULT_TERMINATE,
/* 52 */ DEFAULT_TERMINATE,
/* 53 */ DEFAULT_TERMINATE,
/* 54 */ DEFAULT_TERMINATE,
/* 55 */ DEFAULT_TERMINATE,
/* 56 */ DEFAULT_TERMINATE,
/* 57 */ DEFAULT_TERMINATE,
/* 58 */ DEFAULT_TERMINATE,
/* 59 */ DEFAULT_TERMINATE,
/* 60 */ DEFAULT_TERMINATE,
/* 61 */ DEFAULT_TERMINATE,
/* 62 */ DEFAULT_TERMINATE,
/* 63 */ DEFAULT_TERMINATE,
/* 64 */ DEFAULT_TERMINATE,
};
bool can_always_delay[] = {
/* nothing 0 */ true,
/* SIGHUP 1 */ true,
/* SIGINT 2 */ true,
/* SIGQUIT 3 */ true,
/* SIGILL 4 */ false,
/* SIGTRAP 5 */ false,
/* SIGABRT/SIGIOT 6 */ false,
/* SIGBUS 7 */ false,
/* SIGFPE 8 */ false,
/* SIGKILL 9 */ true,
/* SIGUSR1 10 */ true,
/* SIGSEGV 11 */ false,
/* SIGUSR2 12 */ true,
/* SIGPIPE 13 */ false,
/* SIGALRM 14 */ true,
/* SIGTERM 15 */ true,
/* SIGSTKFLT 16 */ false,
/* SIGCHLD 17 */ true,
/* SIGCONT 18 */ true,
/* SIGSTOP 19 */ true,
/* SIGTSTP 20 */ true,
/* SIGTTIN 21 */ true,
/* SIGTTOU 22 */ true,
/* SIGURG 23 */ true,
/* SIGXCPU 24 */ false,
/* SIGXFSZ 25 */ true,
/* SIGVTALRM 26 */ true,
/* SIGPROF 27 */ true,
/* SIGWINCH 28 */ true,
/* SIGIO/SIGPOLL/SIGLOST 29 */ true,
/* SIGPWR 30 */ true,
/* SIGSYS/SIGUNUSED 31 */ false,
/* ASSUMPTION: all real-time can be delayed */
/* 32 */ true,
/* 33 */ true,
/* 34 */ true,
/* 35 */ true,
/* 36 */ true,
/* 37 */ true,
/* 38 */ true,
/* 39 */ true,
/* 40 */ true,
/* 41 */ true,
/* 42 */ true,
/* 43 */ true,
/* 44 */ true,
/* 45 */ true,
/* 46 */ true,
/* 47 */ true,
/* 48 */ true,
/* 49 */ true,
/* 50 */ true,
/* 51 */ true,
/* 52 */ true,
/* 53 */ true,
/* 54 */ true,
/* 55 */ true,
/* 56 */ true,
/* 57 */ true,
/* 58 */ true,
/* 59 */ true,
/* 60 */ true,
/* 61 */ true,
/* 62 */ true,
/* 63 */ true,
/* 64 */ true,
};
bool
sysnum_is_not_restartable(int sysnum)
{
/* Check the list of non-restartable syscalls.
* Since we only check the number, we're inaccurate!
* We err on the side of thinking more things are non-restartable
* than actually are, as this is only really used for inserting
* nops to ensure post-syscall points are safe spots, and too many
* nops is better than too few.
* We're missing:
* + SYS_read from an inotify file descriptor.
* We're overly aggressive on:
* + Socket interfaces: supposed to restart if no timeout has been set.
*/
return (
#ifdef SYS_pause
sysnum == SYS_pause ||
#endif
sysnum == SYS_rt_sigsuspend || sysnum == SYS_rt_sigtimedwait ||
IF_X86_64(sysnum == SYS_epoll_wait_old ||)
#ifdef SYS_epoll_wait
sysnum == SYS_epoll_wait ||
#endif
sysnum == SYS_epoll_pwait ||
#ifdef SYS_poll
sysnum == SYS_poll ||
#endif
sysnum == SYS_ppoll || IF_X86(sysnum == SYS_select ||) sysnum == SYS_pselect6 ||
#ifdef X64
sysnum == SYS_msgrcv || sysnum == SYS_msgsnd || sysnum == SYS_semop ||
sysnum == SYS_semtimedop ||
/* XXX: these should be restarted if there's no timeout */
sysnum == SYS_accept || sysnum == SYS_accept4 || sysnum == SYS_recvfrom ||
sysnum == SYS_recvmsg || sysnum == SYS_recvmmsg || sysnum == SYS_connect ||
sysnum == SYS_sendto || sysnum == SYS_sendmmsg || sysnum == SYS_sendfile ||
#elif !defined(ARM)
/* XXX: some should be restarted if there's no timeout */
sysnum == SYS_ipc ||
#endif
sysnum == SYS_clock_nanosleep || sysnum == SYS_nanosleep ||
sysnum == SYS_io_getevents);
}
/***************************************************************************
* SIGNALFD
*/
/* Strategy: a real signalfd is a read-only file, so we can't write to one to
* emulate signal delivery. We also can't block signals we care about (and
* for clients we don't want to block anything). Thus we must emulate
* signalfd via a pipe. The kernel's pipe buffer should easily hold
* even a big queue of RT signals. Xref i#1138.
*
* Although signals are per-thread, fds are global, and one thread
* could use a signalfd to see signals on another thread.
*
* Thus we have:
* + global data struct "sigfd_pipe_t" stores pipe write fd and refcount
* + global hashtable mapping read fd to sigfd_pipe_t
* + thread has array of pointers to sigfd_pipe_t, one per signum
* + on SYS_close, we decrement refcount
* + on SYS_dup*, we add a new hashtable entry
*
* This pipe implementation has a hole: it cannot properly handle two
* signalfds with different but overlapping signal masks (i#1189: see below).
*/
static generic_table_t *sigfd_table;
struct _sigfd_pipe_t {
file_t write_fd;
file_t read_fd;
uint refcount;
dcontext_t *dcontext;
};
static void
sigfd_pipe_free(dcontext_t *dcontext, void *ptr)
{
sigfd_pipe_t *pipe = (sigfd_pipe_t *)ptr;
ASSERT(pipe->refcount > 0);
pipe->refcount--;
if (pipe->refcount == 0) {
if (pipe->dcontext != NULL) {
/* Update the owning thread's info.
* We write a NULL which is atomic.
* The thread on exit grabs the table lock for synch and clears dcontext.
*/
thread_sig_info_t *info = (thread_sig_info_t *)pipe->dcontext->signal_field;
int sig;
for (sig = 1; sig <= MAX_SIGNUM; sig++) {
if (info->signalfd[sig] == pipe)
info->signalfd[sig] = NULL;
}
}
os_close_protected(pipe->write_fd);
os_close_protected(pipe->read_fd);
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, pipe, sigfd_pipe_t, ACCT_OTHER, PROTECTED);
}
}
void
signalfd_init(void)
{
#define SIGNALFD_HTABLE_INIT_SIZE 6
sigfd_table =
generic_hash_create(GLOBAL_DCONTEXT, SIGNALFD_HTABLE_INIT_SIZE,
80 /* load factor: not perf-critical */,
HASHTABLE_ENTRY_SHARED | HASHTABLE_SHARED |
HASHTABLE_PERSISTENT | HASHTABLE_RELAX_CLUSTER_CHECKS,
sigfd_pipe_free _IF_DEBUG("signalfd table"));
/* XXX: we need our lock rank to be higher than fd_table's so we
* can call os_close_protected() when freeing. We should
* parametrize the generic table rank. For now we just change it afterward
* (we'll have issues if we ever call _resurrect):
*/
ASSIGN_INIT_READWRITE_LOCK_FREE(sigfd_table->rwlock, sigfdtable_lock);
}
void
signalfd_exit(void)
{
generic_hash_destroy(GLOBAL_DCONTEXT, sigfd_table);
}
void
signalfd_thread_exit(dcontext_t *dcontext, thread_sig_info_t *info)
{
/* We don't free the pipe until the app closes its fd's but we need to
* update the dcontext in the global data
*/
int sig;
TABLE_RWLOCK(sigfd_table, write, lock);
for (sig = 1; sig <= MAX_SIGNUM; sig++) {
if (info->signalfd[sig] != NULL)
info->signalfd[sig]->dcontext = NULL;
}
TABLE_RWLOCK(sigfd_table, write, unlock);
}
bool
handle_pre_extended_syscall_sigmasks(dcontext_t *dcontext, kernel_sigset_t *sigmask,
size_t sizemask)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
/* XXX i#2311, #3240: We may currently deliver incorrect signals, because the
* native sigprocmask the system call may get interrupted by may not be the same
* as the native app expects. In addition to this, the p* variants of above syscalls
* are not properly emulated w.r.t. their atomicity setting the sigprocmask and
* executing the syscall.
*/
if (sizemask != sizeof(kernel_sigset_t))
return false;
info->pre_syscall_app_sigprocmask = info->app_sigblocked;
signal_set_mask(dcontext, sigmask);
return true;
}
void
handle_post_extended_syscall_sigmasks(dcontext_t *dcontext, bool success)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
signal_set_mask(dcontext, &info->pre_syscall_app_sigprocmask);
}
ptr_int_t
handle_pre_signalfd(dcontext_t *dcontext, int fd, kernel_sigset_t *mask, size_t sizemask,
int flags)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int sig;
kernel_sigset_t local_set;
kernel_sigset_t *set;
ptr_int_t retval = -1;
sigfd_pipe_t *pipe = NULL;
LOG(THREAD, LOG_ASYNCH, 2, "%s: fd=%d, flags=0x%x\n", __FUNCTION__, fd, flags);
if (sizemask == sizeof(sigset_t)) {
copy_sigset_to_kernel_sigset((sigset_t *)mask, &local_set);
set = &local_set;
} else {
ASSERT(sizemask == sizeof(kernel_sigset_t));
set = mask;
}
if (fd != -1) {
TABLE_RWLOCK(sigfd_table, read, lock);
pipe = (sigfd_pipe_t *)generic_hash_lookup(GLOBAL_DCONTEXT, sigfd_table, fd);
TABLE_RWLOCK(sigfd_table, read, unlock);
if (pipe == NULL)
return -EINVAL;
} else {
/* FIXME i#1189: currently we do not properly handle two signalfds with
* different but overlapping signal masks, as we do not monitor the
* read/poll syscalls and thus cannot provide a set of pipes that
* matches the two signal sets. For now we err on the side of sending
* too many signals and simply conflate such sets into a single pipe.
*/
for (sig = 1; sig <= MAX_SIGNUM; sig++) {
if (sig == SIGKILL || sig == SIGSTOP)
continue;
if (kernel_sigismember(set, sig) && info->signalfd[sig] != NULL) {
pipe = info->signalfd[sig];
retval = dup_syscall(pipe->read_fd);
break;
}
}
}
if (pipe == NULL) {
int fds[2];
/* SYS_signalfd is even newer than SYS_pipe2, so pipe2 must be avail.
* We pass the flags through b/c the same ones (SFD_NONBLOCK ==
* O_NONBLOCK, SFD_CLOEXEC == O_CLOEXEC) are accepted by pipe.
*/
ptr_int_t res = dynamorio_syscall(SYS_pipe2, 2, fds, flags);
if (res < 0)
return res;
pipe = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, sigfd_pipe_t, ACCT_OTHER, PROTECTED);
pipe->dcontext = dcontext;
pipe->refcount = 1;
/* Keep our write fd in the private fd space */
pipe->write_fd = fd_priv_dup(fds[1]);
os_close(fds[1]);
if (TEST(SFD_CLOEXEC, flags))
fd_mark_close_on_exec(pipe->write_fd);
fd_table_add(pipe->write_fd, 0 /*keep across fork*/);
/* We need an un-closable copy of the read fd in case we need to dup it */
pipe->read_fd = fd_priv_dup(fds[0]);
if (TEST(SFD_CLOEXEC, flags))
fd_mark_close_on_exec(pipe->read_fd);
fd_table_add(pipe->read_fd, 0 /*keep across fork*/);
TABLE_RWLOCK(sigfd_table, write, lock);
generic_hash_add(GLOBAL_DCONTEXT, sigfd_table, fds[0], (void *)pipe);
TABLE_RWLOCK(sigfd_table, write, unlock);
LOG(THREAD, LOG_ASYNCH, 2, "created signalfd pipe app r=%d DR r=%d w=%d\n",
fds[0], pipe->read_fd, pipe->write_fd);
retval = fds[0];
}
for (sig = 1; sig <= MAX_SIGNUM; sig++) {
if (sig == SIGKILL || sig == SIGSTOP)
continue;
if (kernel_sigismember(set, sig)) {
if (info->signalfd[sig] == NULL)
info->signalfd[sig] = pipe;
else
ASSERT(info->signalfd[sig] == pipe);
LOG(THREAD, LOG_ASYNCH, 2, "adding signalfd pipe %d for signal %d\n",
pipe->write_fd, sig);
} else if (info->signalfd[sig] != NULL) {
info->signalfd[sig] = NULL;
LOG(THREAD, LOG_ASYNCH, 2, "removing signalfd pipe=%d for signal %d\n",
pipe->write_fd, sig);
}
}
return retval;
}
bool
notify_signalfd(dcontext_t *dcontext, thread_sig_info_t *info, int sig,
sigframe_rt_t *frame)
{
sigfd_pipe_t *pipe = info->signalfd[sig];
if (pipe != NULL) {
int res;
struct signalfd_siginfo towrite = {
0,
};
/* XXX: we should limit to a single non-RT signal until it's read (by
* polling pipe->read_fd to see whether it has data), except we delay
* signals and thus do want to accumulate multiple non-RT to some extent.
* For now we go ahead and treat RT and non-RT the same.
*/
towrite.ssi_signo = sig;
towrite.ssi_errno = frame->info.si_errno;
towrite.ssi_code = frame->info.si_code;
towrite.ssi_pid = frame->info.si_pid;
towrite.ssi_uid = frame->info.si_uid;
towrite.ssi_fd = frame->info.si_fd;
towrite.ssi_band = frame->info.si_band;
towrite.ssi_tid = frame->info.si_timerid;
towrite.ssi_overrun = frame->info.si_overrun;
towrite.ssi_status = frame->info.si_status;
towrite.ssi_utime = frame->info.si_utime;
towrite.ssi_stime = frame->info.si_stime;
#ifdef __ARCH_SI_TRAPNO /* XXX: should update include/siginfo.h */
towrite.ssi_trapno = frame->info.si_trapno;
#endif
towrite.ssi_addr = (ptr_int_t)frame->info.si_addr;
/* XXX: if the pipe is full, don't write to it as it could block. We
* can poll to determine. This is quite unlikely (kernel buffer is 64K
* since 2.6.11) so for now we do not do so.
*/
res = write_syscall(pipe->write_fd, &towrite, sizeof(towrite));
LOG(THREAD, LOG_ASYNCH, 2, "writing to signalfd fd=%d for signal %d => %d\n",
pipe->write_fd, sig, res);
return true; /* signal consumed */
}
return false;
}
void
signal_handle_dup(dcontext_t *dcontext, file_t src, file_t dst)
{
sigfd_pipe_t *pipe;
TABLE_RWLOCK(sigfd_table, read, lock);
pipe = (sigfd_pipe_t *)generic_hash_lookup(GLOBAL_DCONTEXT, sigfd_table, src);
TABLE_RWLOCK(sigfd_table, read, unlock);
if (pipe == NULL)
return;
TABLE_RWLOCK(sigfd_table, write, lock);
pipe = (sigfd_pipe_t *)generic_hash_lookup(GLOBAL_DCONTEXT, sigfd_table, src);
if (pipe != NULL) {
pipe->refcount++;
generic_hash_add(GLOBAL_DCONTEXT, sigfd_table, dst, (void *)pipe);
}
TABLE_RWLOCK(sigfd_table, write, unlock);
}
void
signal_handle_close(dcontext_t *dcontext, file_t fd)
{
sigfd_pipe_t *pipe;
TABLE_RWLOCK(sigfd_table, read, lock);
pipe = (sigfd_pipe_t *)generic_hash_lookup(GLOBAL_DCONTEXT, sigfd_table, fd);
TABLE_RWLOCK(sigfd_table, read, unlock);
if (pipe == NULL)
return;
TABLE_RWLOCK(sigfd_table, write, lock);
pipe = (sigfd_pipe_t *)generic_hash_lookup(GLOBAL_DCONTEXT, sigfd_table, fd);
if (pipe != NULL) {
/* this will call sigfd_pipe_free() */
generic_hash_remove(GLOBAL_DCONTEXT, sigfd_table, fd);
}
TABLE_RWLOCK(sigfd_table, write, unlock);
}
| 1 | 15,327 | What if the app's signal handler, executed at pre-syscall for epoll_pwait, executes its own epoll_pwait? For that matter: what happens natively if that happens? I would not expect the kernel to keep a stack -- does that clobber the kernel's stored pre-syscall mask? | DynamoRIO-dynamorio | c |
@@ -139,8 +139,10 @@ public interface DataFile {
DataFile copy();
/**
- * @return a list of offsets for file blocks if applicable, null otherwise. When available, this
- * information is used for planning scan tasks whose boundaries are determined by these offsets.
+ * @return List of offsets for blocks of a file, if applicable, null otherwise.
+ * When available, this information is used for planning scan tasks whose boundaries
+ * are determined by these offsets.It is important that the returned list is sorted
+ * in ascending order.
*/
List<Long> splitOffsets();
} | 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.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import org.apache.iceberg.types.Types.BinaryType;
import org.apache.iceberg.types.Types.IntegerType;
import org.apache.iceberg.types.Types.ListType;
import org.apache.iceberg.types.Types.LongType;
import org.apache.iceberg.types.Types.MapType;
import org.apache.iceberg.types.Types.StringType;
import org.apache.iceberg.types.Types.StructType;
import static org.apache.iceberg.types.Types.NestedField.optional;
import static org.apache.iceberg.types.Types.NestedField.required;
/**
* Interface for files listed in a table manifest.
*/
public interface DataFile {
static StructType getType(StructType partitionType) {
// IDs start at 100 to leave room for changes to ManifestEntry
return StructType.of(
required(100, "file_path", StringType.get()),
required(101, "file_format", StringType.get()),
required(102, "partition", partitionType),
required(103, "record_count", LongType.get()),
required(104, "file_size_in_bytes", LongType.get()),
required(105, "block_size_in_bytes", LongType.get()),
optional(106, "file_ordinal", IntegerType.get()),
optional(107, "sort_columns", ListType.ofRequired(112, IntegerType.get())),
optional(108, "column_sizes", MapType.ofRequired(117, 118,
IntegerType.get(), LongType.get())),
optional(109, "value_counts", MapType.ofRequired(119, 120,
IntegerType.get(), LongType.get())),
optional(110, "null_value_counts", MapType.ofRequired(121, 122,
IntegerType.get(), LongType.get())),
optional(125, "lower_bounds", MapType.ofRequired(126, 127,
IntegerType.get(), BinaryType.get())),
optional(128, "upper_bounds", MapType.ofRequired(129, 130,
IntegerType.get(), BinaryType.get())),
optional(131, "key_metadata", BinaryType.get()),
optional(132, "split_offsets", ListType.ofRequired(133, LongType.get()))
// NEXT ID TO ASSIGN: 134
);
}
/**
* @return fully qualified path to the file, suitable for constructing a Hadoop Path
*/
CharSequence path();
/**
* @return format of the data file
*/
FileFormat format();
/**
* @return partition data for this file as a {@link StructLike}
*/
StructLike partition();
/**
* @return the number of top-level records in the data file
*/
long recordCount();
/**
* @return the data file size in bytes
*/
long fileSizeInBytes();
/**
* @return file ordinal if written in a global ordering, or null
*/
Integer fileOrdinal();
/**
* @return list of columns the file records are sorted by, or null
*/
List<Integer> sortColumns();
/**
* @return if collected, map from column ID to the size of the column in bytes, null otherwise
*/
Map<Integer, Long> columnSizes();
/**
* @return if collected, map from column ID to the count of its non-null values, null otherwise
*/
Map<Integer, Long> valueCounts();
/**
* @return if collected, map from column ID to its null value count, null otherwise
*/
Map<Integer, Long> nullValueCounts();
/**
* @return if collected, map from column ID to value lower bounds, null otherwise
*/
Map<Integer, ByteBuffer> lowerBounds();
/**
* @return if collected, map from column ID to value upper bounds, null otherwise
*/
Map<Integer, ByteBuffer> upperBounds();
/**
* @return metadata about how this file is encrypted, or null if the file is stored in plain
* text.
*/
ByteBuffer keyMetadata();
/**
* Copies this {@link DataFile data file}. Manifest readers can reuse data file instances; use
* this method to copy data when collecting files from tasks.
*
* @return a copy of this data file
*/
DataFile copy();
/**
* @return a list of offsets for file blocks if applicable, null otherwise. When available, this
* information is used for planning scan tasks whose boundaries are determined by these offsets.
*/
List<Long> splitOffsets();
}
| 1 | 13,463 | Nit: missing a space. I think we should phrase the new content a little differently. "It is important" isn't very clear. I think it should be "offsets will be returned in sorted order." | apache-iceberg | java |
@@ -10,8 +10,10 @@ import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
+ "encoding/json"
"fmt"
"io"
+ "io/ioutil"
"net/http"
"net/url"
"path" | 1 | // Package azureblob provides an interface to the Microsoft Azure blob object storage system
// +build !plan9,!solaris,!js,go1.13
package azureblob
import (
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"sync"
"time"
"github.com/Azure/azure-pipeline-go/pipeline"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/pkg/errors"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/walk"
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/readers"
"golang.org/x/sync/errgroup"
)
const (
minSleep = 10 * time.Millisecond
maxSleep = 10 * time.Second
decayConstant = 1 // bigger for slower decay, exponential
maxListChunkSize = 5000 // number of items to read at once
modTimeKey = "mtime"
timeFormatIn = time.RFC3339
timeFormatOut = "2006-01-02T15:04:05.000000000Z07:00"
maxTotalParts = 50000 // in multipart upload
storageDefaultBaseURL = "blob.core.windows.net"
// maxUncommittedSize = 9 << 30 // can't upload bigger than this
defaultChunkSize = 4 * fs.MebiByte
maxChunkSize = 100 * fs.MebiByte
defaultUploadCutoff = 256 * fs.MebiByte
maxUploadCutoff = 256 * fs.MebiByte
defaultAccessTier = azblob.AccessTierNone
maxTryTimeout = time.Hour * 24 * 365 //max time of an azure web request response window (whether or not data is flowing)
// Default storage account, key and blob endpoint for emulator support,
// though it is a base64 key checked in here, it is publicly available secret.
emulatorAccount = "devstoreaccount1"
emulatorAccountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
emulatorBlobEndpoint = "http://127.0.0.1:10000/devstoreaccount1"
memoryPoolFlushTime = fs.Duration(time.Minute) // flush the cached buffers after this long
memoryPoolUseMmap = false
)
// Register with Fs
func init() {
fs.Register(&fs.RegInfo{
Name: "azureblob",
Description: "Microsoft Azure Blob Storage",
NewFs: NewFs,
Options: []fs.Option{{
Name: "account",
Help: "Storage Account Name (leave blank to use SAS URL or Emulator)",
}, {
Name: "key",
Help: "Storage Account Key (leave blank to use SAS URL or Emulator)",
}, {
Name: "sas_url",
Help: "SAS URL for container level access only\n(leave blank if using account/key or Emulator)",
}, {
Name: "use_emulator",
Help: "Uses local storage emulator if provided as 'true' (leave blank if using real azure storage endpoint)",
Default: false,
}, {
Name: "endpoint",
Help: "Endpoint for the service\nLeave blank normally.",
Advanced: true,
}, {
Name: "upload_cutoff",
Help: "Cutoff for switching to chunked upload (<= 256MB).",
Default: defaultUploadCutoff,
Advanced: true,
}, {
Name: "chunk_size",
Help: `Upload chunk size (<= 100MB).
Note that this is stored in memory and there may be up to
"--transfers" chunks stored at once in memory.`,
Default: defaultChunkSize,
Advanced: true,
}, {
Name: "list_chunk",
Help: `Size of blob list.
This sets the number of blobs requested in each listing chunk. Default
is the maximum, 5000. "List blobs" requests are permitted 2 minutes
per megabyte to complete. If an operation is taking longer than 2
minutes per megabyte on average, it will time out (
[source](https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-blob-service-operations#exceptions-to-default-timeout-interval)
). This can be used to limit the number of blobs items to return, to
avoid the time out.`,
Default: maxListChunkSize,
Advanced: true,
}, {
Name: "access_tier",
Help: `Access tier of blob: hot, cool or archive.
Archived blobs can be restored by setting access tier to hot or
cool. Leave blank if you intend to use default access tier, which is
set at account level
If there is no "access tier" specified, rclone doesn't apply any tier.
rclone performs "Set Tier" operation on blobs while uploading, if objects
are not modified, specifying "access tier" to new one will have no effect.
If blobs are in "archive tier" at remote, trying to perform data transfer
operations from remote will not be allowed. User should first restore by
tiering blob to "Hot" or "Cool".`,
Advanced: true,
}, {
Name: "disable_checksum",
Help: `Don't store MD5 checksum with object metadata.
Normally rclone will calculate the MD5 checksum of the input before
uploading it so it can add it to metadata on the object. This is great
for data integrity checking but can cause long delays for large files
to start uploading.`,
Default: false,
Advanced: true,
}, {
Name: "memory_pool_flush_time",
Default: memoryPoolFlushTime,
Advanced: true,
Help: `How often internal memory buffer pools will be flushed.
Uploads which requires additional buffers (f.e multipart) will use memory pool for allocations.
This option controls how often unused buffers will be removed from the pool.`,
}, {
Name: "memory_pool_use_mmap",
Default: memoryPoolUseMmap,
Advanced: true,
Help: `Whether to use mmap buffers in internal memory pool.`,
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
Advanced: true,
Default: (encoder.EncodeInvalidUtf8 |
encoder.EncodeSlash |
encoder.EncodeCtl |
encoder.EncodeDel |
encoder.EncodeBackSlash |
encoder.EncodeRightPeriod),
}},
})
}
// Options defines the configuration for this backend
type Options struct {
Account string `config:"account"`
Key string `config:"key"`
Endpoint string `config:"endpoint"`
SASURL string `config:"sas_url"`
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
ListChunkSize uint `config:"list_chunk"`
AccessTier string `config:"access_tier"`
UseEmulator bool `config:"use_emulator"`
DisableCheckSum bool `config:"disable_checksum"`
MemoryPoolFlushTime fs.Duration `config:"memory_pool_flush_time"`
MemoryPoolUseMmap bool `config:"memory_pool_use_mmap"`
Enc encoder.MultiEncoder `config:"encoding"`
}
// Fs represents a remote azure server
type Fs struct {
name string // name of this remote
root string // the path we are working on if any
opt Options // parsed config options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
client *http.Client // http client we are using
svcURL *azblob.ServiceURL // reference to serviceURL
cntURLcacheMu sync.Mutex // mutex to protect cntURLcache
cntURLcache map[string]*azblob.ContainerURL // reference to containerURL per container
rootContainer string // container part of root (if any)
rootDirectory string // directory part of root (if any)
isLimited bool // if limited to one container
cache *bucket.Cache // cache for container creation status
pacer *fs.Pacer // To pace and retry the API calls
uploadToken *pacer.TokenDispenser // control concurrency
pool *pool.Pool // memory pool
}
// Object describes an azure object
type Object struct {
fs *Fs // what this object is part of
remote string // The remote path
modTime time.Time // The modified time of the object if known
md5 string // MD5 hash if known
size int64 // Size of the object
mimeType string // Content-Type of the object
accessTier azblob.AccessTierType // Blob Access Tier
meta map[string]string // blob metadata
}
// ------------------------------------------------------------
// Name of the remote (as passed into NewFs)
func (f *Fs) Name() string {
return f.name
}
// Root of the remote (as passed into NewFs)
func (f *Fs) Root() string {
return f.root
}
// String converts this Fs to a string
func (f *Fs) String() string {
if f.rootContainer == "" {
return "Azure root"
}
if f.rootDirectory == "" {
return fmt.Sprintf("Azure container %s", f.rootContainer)
}
return fmt.Sprintf("Azure container %s path %s", f.rootContainer, f.rootDirectory)
}
// Features returns the optional features of this Fs
func (f *Fs) Features() *fs.Features {
return f.features
}
// parsePath parses a remote 'url'
func parsePath(path string) (root string) {
root = strings.Trim(path, "/")
return
}
// split returns container and containerPath from the rootRelativePath
// relative to f.root
func (f *Fs) split(rootRelativePath string) (containerName, containerPath string) {
containerName, containerPath = bucket.Split(path.Join(f.root, rootRelativePath))
return f.opt.Enc.FromStandardName(containerName), f.opt.Enc.FromStandardPath(containerPath)
}
// split returns container and containerPath from the object
func (o *Object) split() (container, containerPath string) {
return o.fs.split(o.remote)
}
// validateAccessTier checks if azureblob supports user supplied tier
func validateAccessTier(tier string) bool {
switch tier {
case string(azblob.AccessTierHot),
string(azblob.AccessTierCool),
string(azblob.AccessTierArchive):
// valid cases
return true
default:
return false
}
}
// retryErrorCodes is a slice of error codes that we will retry
var retryErrorCodes = []int{
401, // Unauthorized (e.g. "Token has expired")
408, // Request Timeout
429, // Rate exceeded.
500, // Get occasional 500 Internal Server Error
503, // Service Unavailable
504, // Gateway Time-out
}
// shouldRetry returns a boolean as to whether this resp and err
// deserve to be retried. It returns the err as a convenience
func (f *Fs) shouldRetry(err error) (bool, error) {
// FIXME interpret special errors - more to do here
if storageErr, ok := err.(azblob.StorageError); ok {
switch storageErr.ServiceCode() {
case "InvalidBlobOrBlock":
// These errors happen sometimes in multipart uploads
// because of block concurrency issues
return true, err
}
statusCode := storageErr.Response().StatusCode
for _, e := range retryErrorCodes {
if statusCode == e {
return true, err
}
}
}
return fserrors.ShouldRetry(err), err
}
func checkUploadChunkSize(cs fs.SizeSuffix) error {
const minChunkSize = fs.Byte
if cs < minChunkSize {
return errors.Errorf("%s is less than %s", cs, minChunkSize)
}
if cs > maxChunkSize {
return errors.Errorf("%s is greater than %s", cs, maxChunkSize)
}
return nil
}
func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
err = checkUploadChunkSize(cs)
if err == nil {
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
}
return
}
func checkUploadCutoff(cs fs.SizeSuffix) error {
if cs > maxUploadCutoff {
return errors.Errorf("%v must be less than or equal to %v", cs, maxUploadCutoff)
}
return nil
}
func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
err = checkUploadCutoff(cs)
if err == nil {
old, f.opt.UploadCutoff = f.opt.UploadCutoff, cs
}
return
}
// httpClientFactory creates a Factory object that sends HTTP requests
// to an rclone's http.Client.
//
// copied from azblob.newDefaultHTTPClientFactory
func httpClientFactory(client *http.Client) pipeline.Factory {
return pipeline.FactoryFunc(func(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.PolicyFunc {
return func(ctx context.Context, request pipeline.Request) (pipeline.Response, error) {
r, err := client.Do(request.WithContext(ctx))
if err != nil {
err = pipeline.NewError(err, "HTTP request failed")
}
return pipeline.NewHTTPResponse(r), err
}
})
}
// newPipeline creates a Pipeline using the specified credentials and options.
//
// this code was copied from azblob.NewPipeline
func (f *Fs) newPipeline(c azblob.Credential, o azblob.PipelineOptions) pipeline.Pipeline {
// Don't log stuff to syslog/Windows Event log
pipeline.SetForceLogEnabled(false)
// Closest to API goes first; closest to the wire goes last
factories := []pipeline.Factory{
azblob.NewTelemetryPolicyFactory(o.Telemetry),
azblob.NewUniqueRequestIDPolicyFactory(),
azblob.NewRetryPolicyFactory(o.Retry),
c,
pipeline.MethodFactoryMarker(), // indicates at what stage in the pipeline the method factory is invoked
azblob.NewRequestLogPolicyFactory(o.RequestLog),
}
return pipeline.NewPipeline(factories, pipeline.Options{HTTPSender: httpClientFactory(f.client), Log: o.Log})
}
// setRoot changes the root of the Fs
func (f *Fs) setRoot(root string) {
f.root = parsePath(root)
f.rootContainer, f.rootDirectory = bucket.Split(f.root)
}
// NewFs constructs an Fs from the path, container:path
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
// Parse config into Options struct
opt := new(Options)
err := configstruct.Set(m, opt)
if err != nil {
return nil, err
}
err = checkUploadCutoff(opt.UploadCutoff)
if err != nil {
return nil, errors.Wrap(err, "azure: upload cutoff")
}
err = checkUploadChunkSize(opt.ChunkSize)
if err != nil {
return nil, errors.Wrap(err, "azure: chunk size")
}
if opt.ListChunkSize > maxListChunkSize {
return nil, errors.Errorf("azure: blob list size can't be greater than %v - was %v", maxListChunkSize, opt.ListChunkSize)
}
if opt.Endpoint == "" {
opt.Endpoint = storageDefaultBaseURL
}
if opt.AccessTier == "" {
opt.AccessTier = string(defaultAccessTier)
} else if !validateAccessTier(opt.AccessTier) {
return nil, errors.Errorf("Azure Blob: Supported access tiers are %s, %s and %s",
string(azblob.AccessTierHot), string(azblob.AccessTierCool), string(azblob.AccessTierArchive))
}
ci := fs.GetConfig(ctx)
f := &Fs{
name: name,
opt: *opt,
ci: ci,
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
uploadToken: pacer.NewTokenDispenser(ci.Transfers),
client: fshttp.NewClient(ctx),
cache: bucket.NewCache(),
cntURLcache: make(map[string]*azblob.ContainerURL, 1),
pool: pool.New(
time.Duration(opt.MemoryPoolFlushTime),
int(opt.ChunkSize),
ci.Transfers,
opt.MemoryPoolUseMmap,
),
}
f.setRoot(root)
f.features = (&fs.Features{
ReadMimeType: true,
WriteMimeType: true,
BucketBased: true,
BucketBasedRootOK: true,
SetTier: true,
GetTier: true,
}).Fill(ctx, f)
var (
u *url.URL
serviceURL azblob.ServiceURL
)
switch {
case opt.UseEmulator:
credential, err := azblob.NewSharedKeyCredential(emulatorAccount, emulatorAccountKey)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse credentials")
}
u, err = url.Parse(emulatorBlobEndpoint)
if err != nil {
return nil, errors.Wrap(err, "failed to make azure storage url from account and endpoint")
}
pipeline := f.newPipeline(credential, azblob.PipelineOptions{Retry: azblob.RetryOptions{TryTimeout: maxTryTimeout}})
serviceURL = azblob.NewServiceURL(*u, pipeline)
case opt.Account != "" && opt.Key != "":
credential, err := azblob.NewSharedKeyCredential(opt.Account, opt.Key)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse credentials")
}
u, err = url.Parse(fmt.Sprintf("https://%s.%s", opt.Account, opt.Endpoint))
if err != nil {
return nil, errors.Wrap(err, "failed to make azure storage url from account and endpoint")
}
pipeline := f.newPipeline(credential, azblob.PipelineOptions{Retry: azblob.RetryOptions{TryTimeout: maxTryTimeout}})
serviceURL = azblob.NewServiceURL(*u, pipeline)
case opt.SASURL != "":
u, err = url.Parse(opt.SASURL)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse SAS URL")
}
// use anonymous credentials in case of sas url
pipeline := f.newPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{Retry: azblob.RetryOptions{TryTimeout: maxTryTimeout}})
// Check if we have container level SAS or account level sas
parts := azblob.NewBlobURLParts(*u)
if parts.ContainerName != "" {
if f.rootContainer != "" && parts.ContainerName != f.rootContainer {
return nil, errors.New("Container name in SAS URL and container provided in command do not match")
}
containerURL := azblob.NewContainerURL(*u, pipeline)
f.cntURLcache[parts.ContainerName] = &containerURL
f.isLimited = true
} else {
serviceURL = azblob.NewServiceURL(*u, pipeline)
}
default:
return nil, errors.New("Need account+key or connectionString or sasURL")
}
f.svcURL = &serviceURL
if f.rootContainer != "" && f.rootDirectory != "" {
// Check to see if the (container,directory) is actually an existing file
oldRoot := f.root
newRoot, leaf := path.Split(oldRoot)
f.setRoot(newRoot)
_, err := f.NewObject(ctx, leaf)
if err != nil {
if err == fs.ErrorObjectNotFound || err == fs.ErrorNotAFile {
// File doesn't exist or is a directory so return old f
f.setRoot(oldRoot)
return f, nil
}
return nil, err
}
// return an error with an fs which points to the parent
return f, fs.ErrorIsFile
}
return f, nil
}
// return the container URL for the container passed in
func (f *Fs) cntURL(container string) (containerURL *azblob.ContainerURL) {
f.cntURLcacheMu.Lock()
defer f.cntURLcacheMu.Unlock()
var ok bool
if containerURL, ok = f.cntURLcache[container]; !ok {
cntURL := f.svcURL.NewContainerURL(container)
containerURL = &cntURL
f.cntURLcache[container] = containerURL
}
return containerURL
}
// Return an Object from a path
//
// If it can't be found it returns the error fs.ErrorObjectNotFound.
func (f *Fs) newObjectWithInfo(remote string, info *azblob.BlobItemInternal) (fs.Object, error) {
o := &Object{
fs: f,
remote: remote,
}
if info != nil {
err := o.decodeMetaDataFromBlob(info)
if err != nil {
return nil, err
}
} else {
err := o.readMetaData() // reads info and headers, returning an error
if err != nil {
return nil, err
}
}
return o, nil
}
// NewObject finds the Object at remote. If it can't be found
// it returns the error fs.ErrorObjectNotFound.
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
return f.newObjectWithInfo(remote, nil)
}
// getBlobReference creates an empty blob reference with no metadata
func (f *Fs) getBlobReference(container, containerPath string) azblob.BlobURL {
return f.cntURL(container).NewBlobURL(containerPath)
}
// updateMetadataWithModTime adds the modTime passed in to o.meta.
func (o *Object) updateMetadataWithModTime(modTime time.Time) {
// Make sure o.meta is not nil
if o.meta == nil {
o.meta = make(map[string]string, 1)
}
// Set modTimeKey in it
o.meta[modTimeKey] = modTime.Format(timeFormatOut)
}
// Returns whether file is a directory marker or not
func isDirectoryMarker(size int64, metadata azblob.Metadata, remote string) bool {
// Directory markers are 0 length
if size == 0 {
// Note that metadata with hdi_isfolder = true seems to be a
// defacto standard for marking blobs as directories.
endsWithSlash := strings.HasSuffix(remote, "/")
if endsWithSlash || remote == "" || metadata["hdi_isfolder"] == "true" {
return true
}
}
return false
}
// listFn is called from list to handle an object
type listFn func(remote string, object *azblob.BlobItemInternal, isDirectory bool) error
// list lists the objects into the function supplied from
// the container and root supplied
//
// dir is the starting directory, "" for root
//
// The remote has prefix removed from it and if addContainer is set then
// it adds the container to the start.
func (f *Fs) list(ctx context.Context, container, directory, prefix string, addContainer bool, recurse bool, maxResults uint, fn listFn) error {
if f.cache.IsDeleted(container) {
return fs.ErrorDirNotFound
}
if prefix != "" {
prefix += "/"
}
if directory != "" {
directory += "/"
}
delimiter := ""
if !recurse {
delimiter = "/"
}
options := azblob.ListBlobsSegmentOptions{
Details: azblob.BlobListingDetails{
Copy: false,
Metadata: true,
Snapshots: false,
UncommittedBlobs: false,
Deleted: false,
},
Prefix: directory,
MaxResults: int32(maxResults),
}
for marker := (azblob.Marker{}); marker.NotDone(); {
var response *azblob.ListBlobsHierarchySegmentResponse
err := f.pacer.Call(func() (bool, error) {
var err error
response, err = f.cntURL(container).ListBlobsHierarchySegment(ctx, marker, delimiter, options)
return f.shouldRetry(err)
})
if err != nil {
// Check http error code along with service code, current SDK doesn't populate service code correctly sometimes
if storageErr, ok := err.(azblob.StorageError); ok && (storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound || storageErr.Response().StatusCode == http.StatusNotFound) {
return fs.ErrorDirNotFound
}
return err
}
// Advance marker to next
marker = response.NextMarker
for i := range response.Segment.BlobItems {
file := &response.Segment.BlobItems[i]
// Finish if file name no longer has prefix
// if prefix != "" && !strings.HasPrefix(file.Name, prefix) {
// return nil
// }
remote := f.opt.Enc.ToStandardPath(file.Name)
if !strings.HasPrefix(remote, prefix) {
fs.Debugf(f, "Odd name received %q", remote)
continue
}
remote = remote[len(prefix):]
if isDirectoryMarker(*file.Properties.ContentLength, file.Metadata, remote) {
continue // skip directory marker
}
if addContainer {
remote = path.Join(container, remote)
}
// Send object
err = fn(remote, file, false)
if err != nil {
return err
}
}
// Send the subdirectories
for _, remote := range response.Segment.BlobPrefixes {
remote := strings.TrimRight(remote.Name, "/")
remote = f.opt.Enc.ToStandardPath(remote)
if !strings.HasPrefix(remote, prefix) {
fs.Debugf(f, "Odd directory name received %q", remote)
continue
}
remote = remote[len(prefix):]
if addContainer {
remote = path.Join(container, remote)
}
// Send object
err = fn(remote, nil, true)
if err != nil {
return err
}
}
}
return nil
}
// Convert a list item into a DirEntry
func (f *Fs) itemToDirEntry(remote string, object *azblob.BlobItemInternal, isDirectory bool) (fs.DirEntry, error) {
if isDirectory {
d := fs.NewDir(remote, time.Time{})
return d, nil
}
o, err := f.newObjectWithInfo(remote, object)
if err != nil {
return nil, err
}
return o, nil
}
// listDir lists a single directory
func (f *Fs) listDir(ctx context.Context, container, directory, prefix string, addContainer bool) (entries fs.DirEntries, err error) {
err = f.list(ctx, container, directory, prefix, addContainer, false, f.opt.ListChunkSize, func(remote string, object *azblob.BlobItemInternal, isDirectory bool) error {
entry, err := f.itemToDirEntry(remote, object, isDirectory)
if err != nil {
return err
}
if entry != nil {
entries = append(entries, entry)
}
return nil
})
if err != nil {
return nil, err
}
// container must be present if listing succeeded
f.cache.MarkOK(container)
return entries, nil
}
// listContainers returns all the containers to out
func (f *Fs) listContainers(ctx context.Context) (entries fs.DirEntries, err error) {
if f.isLimited {
f.cntURLcacheMu.Lock()
for container := range f.cntURLcache {
d := fs.NewDir(container, time.Time{})
entries = append(entries, d)
}
f.cntURLcacheMu.Unlock()
return entries, nil
}
err = f.listContainersToFn(func(container *azblob.ContainerItem) error {
d := fs.NewDir(f.opt.Enc.ToStandardName(container.Name), container.Properties.LastModified)
f.cache.MarkOK(container.Name)
entries = append(entries, d)
return nil
})
if err != nil {
return nil, err
}
return entries, nil
}
// List the objects and directories in dir into entries. The
// entries can be returned in any order but should be for a
// complete directory.
//
// dir should be "" to list the root, and should not have
// trailing slashes.
//
// This should return ErrDirNotFound if the directory isn't
// found.
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
container, directory := f.split(dir)
if container == "" {
if directory != "" {
return nil, fs.ErrorListBucketRequired
}
return f.listContainers(ctx)
}
return f.listDir(ctx, container, directory, f.rootDirectory, f.rootContainer == "")
}
// ListR lists the objects and directories of the Fs starting
// from dir recursively into out.
//
// dir should be "" to start from the root, and should not
// have trailing slashes.
//
// This should return ErrDirNotFound if the directory isn't
// found.
//
// It should call callback for each tranche of entries read.
// These need not be returned in any particular order. If
// callback returns an error then the listing will stop
// immediately.
//
// Don't implement this unless you have a more efficient way
// of listing recursively that doing a directory traversal.
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) {
container, directory := f.split(dir)
list := walk.NewListRHelper(callback)
listR := func(container, directory, prefix string, addContainer bool) error {
return f.list(ctx, container, directory, prefix, addContainer, true, f.opt.ListChunkSize, func(remote string, object *azblob.BlobItemInternal, isDirectory bool) error {
entry, err := f.itemToDirEntry(remote, object, isDirectory)
if err != nil {
return err
}
return list.Add(entry)
})
}
if container == "" {
entries, err := f.listContainers(ctx)
if err != nil {
return err
}
for _, entry := range entries {
err = list.Add(entry)
if err != nil {
return err
}
container := entry.Remote()
err = listR(container, "", f.rootDirectory, true)
if err != nil {
return err
}
// container must be present if listing succeeded
f.cache.MarkOK(container)
}
} else {
err = listR(container, directory, f.rootDirectory, f.rootContainer == "")
if err != nil {
return err
}
// container must be present if listing succeeded
f.cache.MarkOK(container)
}
return list.Flush()
}
// listContainerFn is called from listContainersToFn to handle a container
type listContainerFn func(*azblob.ContainerItem) error
// listContainersToFn lists the containers to the function supplied
func (f *Fs) listContainersToFn(fn listContainerFn) error {
params := azblob.ListContainersSegmentOptions{
MaxResults: int32(f.opt.ListChunkSize),
}
ctx := context.Background()
for marker := (azblob.Marker{}); marker.NotDone(); {
var response *azblob.ListContainersSegmentResponse
err := f.pacer.Call(func() (bool, error) {
var err error
response, err = f.svcURL.ListContainersSegment(ctx, marker, params)
return f.shouldRetry(err)
})
if err != nil {
return err
}
for i := range response.ContainerItems {
err = fn(&response.ContainerItems[i])
if err != nil {
return err
}
}
marker = response.NextMarker
}
return nil
}
// Put the object into the container
//
// Copy the reader in to the new object which is returned
//
// The new object may have been created if an error is returned
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
// Temporary Object under construction
fs := &Object{
fs: f,
remote: src.Remote(),
}
return fs, fs.Update(ctx, in, src, options...)
}
// PutStream uploads to the remote path with the modTime given of indeterminate size
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
return f.Put(ctx, in, src, options...)
}
// Mkdir creates the container if it doesn't exist
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
container, _ := f.split(dir)
return f.makeContainer(ctx, container)
}
// makeContainer creates the container if it doesn't exist
func (f *Fs) makeContainer(ctx context.Context, container string) error {
return f.cache.Create(container, func() error {
// If this is a SAS URL limited to a container then assume it is already created
if f.isLimited {
return nil
}
// now try to create the container
return f.pacer.Call(func() (bool, error) {
_, err := f.cntURL(container).Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
if err != nil {
if storageErr, ok := err.(azblob.StorageError); ok {
switch storageErr.ServiceCode() {
case azblob.ServiceCodeContainerAlreadyExists:
return false, nil
case azblob.ServiceCodeContainerBeingDeleted:
// From https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container
// When a container is deleted, a container with the same name cannot be created
// for at least 30 seconds; the container may not be available for more than 30
// seconds if the service is still processing the request.
time.Sleep(6 * time.Second) // default 10 retries will be 60 seconds
f.cache.MarkDeleted(container)
return true, err
}
}
}
return f.shouldRetry(err)
})
}, nil)
}
// isEmpty checks to see if a given (container, directory) is empty and returns an error if not
func (f *Fs) isEmpty(ctx context.Context, container, directory string) (err error) {
empty := true
err = f.list(ctx, container, directory, f.rootDirectory, f.rootContainer == "", true, 1, func(remote string, object *azblob.BlobItemInternal, isDirectory bool) error {
empty = false
return nil
})
if err != nil {
return err
}
if !empty {
return fs.ErrorDirectoryNotEmpty
}
return nil
}
// deleteContainer deletes the container. It can delete a full
// container so use isEmpty if you don't want that.
func (f *Fs) deleteContainer(ctx context.Context, container string) error {
return f.cache.Remove(container, func() error {
options := azblob.ContainerAccessConditions{}
return f.pacer.Call(func() (bool, error) {
_, err := f.cntURL(container).GetProperties(ctx, azblob.LeaseAccessConditions{})
if err == nil {
_, err = f.cntURL(container).Delete(ctx, options)
}
if err != nil {
// Check http error code along with service code, current SDK doesn't populate service code correctly sometimes
if storageErr, ok := err.(azblob.StorageError); ok && (storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound || storageErr.Response().StatusCode == http.StatusNotFound) {
return false, fs.ErrorDirNotFound
}
return f.shouldRetry(err)
}
return f.shouldRetry(err)
})
})
}
// Rmdir deletes the container if the fs is at the root
//
// Returns an error if it isn't empty
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
container, directory := f.split(dir)
if container == "" || directory != "" {
return nil
}
err := f.isEmpty(ctx, container, directory)
if err != nil {
return err
}
return f.deleteContainer(ctx, container)
}
// Precision of the remote
func (f *Fs) Precision() time.Duration {
return time.Nanosecond
}
// Hashes returns the supported hash sets.
func (f *Fs) Hashes() hash.Set {
return hash.Set(hash.MD5)
}
// Purge deletes all the files and directories including the old versions.
func (f *Fs) Purge(ctx context.Context, dir string) error {
container, directory := f.split(dir)
if container == "" || directory != "" {
// Delegate to caller if not root of a container
return fs.ErrorCantPurge
}
return f.deleteContainer(ctx, container)
}
// Copy src to this remote using server-side copy operations.
//
// This is stored with the remote path given
//
// It returns the destination Object and a possible error
//
// Will only be called if src.Fs().Name() == f.Name()
//
// If it isn't possible then return fs.ErrorCantCopy
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
dstContainer, dstPath := f.split(remote)
err := f.makeContainer(ctx, dstContainer)
if err != nil {
return nil, err
}
srcObj, ok := src.(*Object)
if !ok {
fs.Debugf(src, "Can't copy - not same remote type")
return nil, fs.ErrorCantCopy
}
dstBlobURL := f.getBlobReference(dstContainer, dstPath)
srcBlobURL := srcObj.getBlobReference()
source, err := url.Parse(srcBlobURL.String())
if err != nil {
return nil, err
}
options := azblob.BlobAccessConditions{}
var startCopy *azblob.BlobStartCopyFromURLResponse
err = f.pacer.Call(func() (bool, error) {
startCopy, err = dstBlobURL.StartCopyFromURL(ctx, *source, nil, azblob.ModifiedAccessConditions{}, options, azblob.AccessTierType(f.opt.AccessTier), nil)
return f.shouldRetry(err)
})
if err != nil {
return nil, err
}
copyStatus := startCopy.CopyStatus()
for copyStatus == azblob.CopyStatusPending {
time.Sleep(1 * time.Second)
getMetadata, err := dstBlobURL.GetProperties(ctx, options)
if err != nil {
return nil, err
}
copyStatus = getMetadata.CopyStatus()
}
return f.NewObject(ctx, remote)
}
func (f *Fs) getMemoryPool(size int64) *pool.Pool {
if size == int64(f.opt.ChunkSize) {
return f.pool
}
return pool.New(
time.Duration(f.opt.MemoryPoolFlushTime),
int(size),
f.ci.Transfers,
f.opt.MemoryPoolUseMmap,
)
}
// ------------------------------------------------------------
// Fs returns the parent Fs
func (o *Object) Fs() fs.Info {
return o.fs
}
// Return a string version
func (o *Object) String() string {
if o == nil {
return "<nil>"
}
return o.remote
}
// Remote returns the remote path
func (o *Object) Remote() string {
return o.remote
}
// Hash returns the MD5 of an object returning a lowercase hex string
func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
if t != hash.MD5 {
return "", hash.ErrUnsupported
}
// Convert base64 encoded md5 into lower case hex
if o.md5 == "" {
return "", nil
}
data, err := base64.StdEncoding.DecodeString(o.md5)
if err != nil {
return "", errors.Wrapf(err, "Failed to decode Content-MD5: %q", o.md5)
}
return hex.EncodeToString(data), nil
}
// Size returns the size of an object in bytes
func (o *Object) Size() int64 {
return o.size
}
func (o *Object) setMetadata(metadata azblob.Metadata) {
if len(metadata) > 0 {
o.meta = metadata
if modTime, ok := metadata[modTimeKey]; ok {
when, err := time.Parse(timeFormatIn, modTime)
if err != nil {
fs.Debugf(o, "Couldn't parse %v = %q: %v", modTimeKey, modTime, err)
}
o.modTime = when
}
} else {
o.meta = nil
}
}
// decodeMetaDataFromPropertiesResponse sets the metadata from the data passed in
//
// Sets
// o.id
// o.modTime
// o.size
// o.md5
// o.meta
func (o *Object) decodeMetaDataFromPropertiesResponse(info *azblob.BlobGetPropertiesResponse) (err error) {
metadata := info.NewMetadata()
size := info.ContentLength()
if isDirectoryMarker(size, metadata, o.remote) {
return fs.ErrorNotAFile
}
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
// this as base64 encoded string.
o.md5 = base64.StdEncoding.EncodeToString(info.ContentMD5())
o.mimeType = info.ContentType()
o.size = size
o.modTime = info.LastModified()
o.accessTier = azblob.AccessTierType(info.AccessTier())
o.setMetadata(metadata)
return nil
}
func (o *Object) decodeMetaDataFromBlob(info *azblob.BlobItemInternal) (err error) {
metadata := info.Metadata
size := *info.Properties.ContentLength
if isDirectoryMarker(size, metadata, o.remote) {
return fs.ErrorNotAFile
}
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
// this as base64 encoded string.
o.md5 = base64.StdEncoding.EncodeToString(info.Properties.ContentMD5)
o.mimeType = *info.Properties.ContentType
o.size = size
o.modTime = info.Properties.LastModified
o.accessTier = info.Properties.AccessTier
o.setMetadata(metadata)
return nil
}
// getBlobReference creates an empty blob reference with no metadata
func (o *Object) getBlobReference() azblob.BlobURL {
container, directory := o.split()
return o.fs.getBlobReference(container, directory)
}
// clearMetaData clears enough metadata so readMetaData will re-read it
func (o *Object) clearMetaData() {
o.modTime = time.Time{}
}
// readMetaData gets the metadata if it hasn't already been fetched
//
// Sets
// o.id
// o.modTime
// o.size
// o.md5
func (o *Object) readMetaData() (err error) {
if !o.modTime.IsZero() {
return nil
}
blob := o.getBlobReference()
// Read metadata (this includes metadata)
options := azblob.BlobAccessConditions{}
ctx := context.Background()
var blobProperties *azblob.BlobGetPropertiesResponse
err = o.fs.pacer.Call(func() (bool, error) {
blobProperties, err = blob.GetProperties(ctx, options)
return o.fs.shouldRetry(err)
})
if err != nil {
// On directories - GetProperties does not work and current SDK does not populate service code correctly hence check regular http response as well
if storageErr, ok := err.(azblob.StorageError); ok && (storageErr.ServiceCode() == azblob.ServiceCodeBlobNotFound || storageErr.Response().StatusCode == http.StatusNotFound) {
return fs.ErrorObjectNotFound
}
return err
}
return o.decodeMetaDataFromPropertiesResponse(blobProperties)
}
// ModTime returns the modification time of the object
//
// It attempts to read the objects mtime and if that isn't present the
// LastModified returned in the http headers
func (o *Object) ModTime(ctx context.Context) (result time.Time) {
// The error is logged in readMetaData
_ = o.readMetaData()
return o.modTime
}
// SetModTime sets the modification time of the local fs object
func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
// Make sure o.meta is not nil
if o.meta == nil {
o.meta = make(map[string]string, 1)
}
// Set modTimeKey in it
o.meta[modTimeKey] = modTime.Format(timeFormatOut)
blob := o.getBlobReference()
err := o.fs.pacer.Call(func() (bool, error) {
_, err := blob.SetMetadata(ctx, o.meta, azblob.BlobAccessConditions{})
return o.fs.shouldRetry(err)
})
if err != nil {
return err
}
o.modTime = modTime
return nil
}
// Storable returns if this object is storable
func (o *Object) Storable() bool {
return true
}
// Open an object for read
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
// Offset and Count for range download
var offset int64
var count int64
if o.AccessTier() == azblob.AccessTierArchive {
return nil, errors.Errorf("Blob in archive tier, you need to set tier to hot or cool first")
}
fs.FixRangeOption(options, o.size)
for _, option := range options {
switch x := option.(type) {
case *fs.RangeOption:
offset, count = x.Decode(o.size)
if count < 0 {
count = o.size - offset
}
case *fs.SeekOption:
offset = x.Offset
default:
if option.Mandatory() {
fs.Logf(o, "Unsupported mandatory option: %v", option)
}
}
}
blob := o.getBlobReference()
ac := azblob.BlobAccessConditions{}
var downloadResponse *azblob.DownloadResponse
err = o.fs.pacer.Call(func() (bool, error) {
downloadResponse, err = blob.Download(ctx, offset, count, ac, false)
return o.fs.shouldRetry(err)
})
if err != nil {
return nil, errors.Wrap(err, "failed to open for download")
}
in = downloadResponse.Body(azblob.RetryReaderOptions{})
return in, nil
}
// dontEncode is the characters that do not need percent-encoding
//
// The characters that do not need percent-encoding are a subset of
// the printable ASCII characters: upper-case letters, lower-case
// letters, digits, ".", "_", "-", "/", "~", "!", "$", "'", "(", ")",
// "*", ";", "=", ":", and "@". All other byte values in a UTF-8 must
// be replaced with "%" and the two-digit hex value of the byte.
const dontEncode = (`abcdefghijklmnopqrstuvwxyz` +
`ABCDEFGHIJKLMNOPQRSTUVWXYZ` +
`0123456789` +
`._-/~!$'()*;=:@`)
// noNeedToEncode is a bitmap of characters which don't need % encoding
var noNeedToEncode [256]bool
func init() {
for _, c := range dontEncode {
noNeedToEncode[c] = true
}
}
// readSeeker joins an io.Reader and an io.Seeker
type readSeeker struct {
io.Reader
io.Seeker
}
// increment the slice passed in as LSB binary
func increment(xs []byte) {
for i, digit := range xs {
newDigit := digit + 1
xs[i] = newDigit
if newDigit >= digit {
// exit if no carry
break
}
}
}
var warnStreamUpload sync.Once
// uploadMultipart uploads a file using multipart upload
//
// Write a larger blob, using CreateBlockBlob, PutBlock, and PutBlockList.
func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, size int64, blob *azblob.BlobURL, httpHeaders *azblob.BlobHTTPHeaders) (err error) {
// Calculate correct chunkSize
chunkSize := int64(o.fs.opt.ChunkSize)
totalParts := -1
// Note that the max size of file is 4.75 TB (100 MB X 50,000
// blocks) and this is bigger than the max uncommitted block
// size (9.52 TB) so we do not need to part commit block lists
// or garbage collect uncommitted blocks.
//
// See: https://docs.microsoft.com/en-gb/rest/api/storageservices/put-block
// size can be -1 here meaning we don't know the size of the incoming file. We use ChunkSize
// buffers here (default 4MB). With a maximum number of parts (50,000) this will be a file of
// 195GB which seems like a not too unreasonable limit.
if size == -1 {
warnStreamUpload.Do(func() {
fs.Logf(o, "Streaming uploads using chunk size %v will have maximum file size of %v",
o.fs.opt.ChunkSize, fs.SizeSuffix(chunkSize*maxTotalParts))
})
} else {
// Adjust partSize until the number of parts is small enough.
if size/chunkSize >= maxTotalParts {
// Calculate partition size rounded up to the nearest MB
chunkSize = (((size / maxTotalParts) >> 20) + 1) << 20
}
if chunkSize > int64(maxChunkSize) {
return errors.Errorf("can't upload as it is too big %v - takes more than %d chunks of %v", fs.SizeSuffix(size), totalParts, fs.SizeSuffix(chunkSize/2))
}
totalParts = int(size / chunkSize)
if size%chunkSize != 0 {
totalParts++
}
}
fs.Debugf(o, "Multipart upload session started for %d parts of size %v", totalParts, fs.SizeSuffix(chunkSize))
// unwrap the accounting from the input, we use wrap to put it
// back on after the buffering
in, wrap := accounting.UnWrap(in)
// Upload the chunks
var (
g, gCtx = errgroup.WithContext(ctx)
remaining = size // remaining size in file for logging only, -1 if size < 0
position = int64(0) // position in file
memPool = o.fs.getMemoryPool(chunkSize) // pool to get memory from
finished = false // set when we have read EOF
blocks []string // list of blocks for finalize
blockBlobURL = blob.ToBlockBlobURL() // Get BlockBlobURL, we will use default pipeline here
ac = azblob.LeaseAccessConditions{} // Use default lease access conditions
binaryBlockID = make([]byte, 8) // block counter as LSB first 8 bytes
)
for part := 0; !finished; part++ {
// Get a block of memory from the pool and a token which limits concurrency
o.fs.uploadToken.Get()
buf := memPool.Get()
free := func() {
memPool.Put(buf) // return the buf
o.fs.uploadToken.Put() // return the token
}
// Fail fast, in case an errgroup managed function returns an error
// gCtx is cancelled. There is no point in uploading all the other parts.
if gCtx.Err() != nil {
free()
break
}
// Read the chunk
n, err := readers.ReadFill(in, buf) // this can never return 0, nil
if err == io.EOF {
if n == 0 { // end if no data
free()
break
}
finished = true
} else if err != nil {
free()
return errors.Wrap(err, "multipart upload failed to read source")
}
buf = buf[:n]
// increment the blockID and save the blocks for finalize
increment(binaryBlockID)
blockID := base64.StdEncoding.EncodeToString(binaryBlockID)
blocks = append(blocks, blockID)
// Transfer the chunk
fs.Debugf(o, "Uploading part %d/%d offset %v/%v part size %v", part+1, totalParts, fs.SizeSuffix(position), fs.SizeSuffix(size), fs.SizeSuffix(chunkSize))
g.Go(func() (err error) {
defer free()
// Upload the block, with MD5 for check
md5sum := md5.Sum(buf)
transactionalMD5 := md5sum[:]
err = o.fs.pacer.Call(func() (bool, error) {
bufferReader := bytes.NewReader(buf)
wrappedReader := wrap(bufferReader)
rs := readSeeker{wrappedReader, bufferReader}
_, err = blockBlobURL.StageBlock(ctx, blockID, &rs, ac, transactionalMD5)
return o.fs.shouldRetry(err)
})
if err != nil {
return errors.Wrap(err, "multipart upload failed to upload part")
}
return nil
})
// ready for next block
if size >= 0 {
remaining -= chunkSize
}
position += chunkSize
}
err = g.Wait()
if err != nil {
return err
}
// Finalise the upload session
err = o.fs.pacer.Call(func() (bool, error) {
_, err := blockBlobURL.CommitBlockList(ctx, blocks, *httpHeaders, o.meta, azblob.BlobAccessConditions{}, azblob.AccessTierType(o.fs.opt.AccessTier), nil)
return o.fs.shouldRetry(err)
})
if err != nil {
return errors.Wrap(err, "multipart upload failed to finalize")
}
return nil
}
// Update the object with the contents of the io.Reader, modTime and size
//
// The new object may have been created if an error is returned
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
container, _ := o.split()
err = o.fs.makeContainer(ctx, container)
if err != nil {
return err
}
size := src.Size()
// Update Mod time
o.updateMetadataWithModTime(src.ModTime(ctx))
if err != nil {
return err
}
blob := o.getBlobReference()
httpHeaders := azblob.BlobHTTPHeaders{}
httpHeaders.ContentType = fs.MimeType(ctx, src)
// Compute the Content-MD5 of the file, for multiparts uploads it
// will be set in PutBlockList API call using the 'x-ms-blob-content-md5' header
// Note: If multipart, an MD5 checksum will also be computed for each uploaded block
// in order to validate its integrity during transport
if !o.fs.opt.DisableCheckSum {
if sourceMD5, _ := src.Hash(ctx, hash.MD5); sourceMD5 != "" {
sourceMD5bytes, err := hex.DecodeString(sourceMD5)
if err == nil {
httpHeaders.ContentMD5 = sourceMD5bytes
} else {
fs.Debugf(o, "Failed to decode %q as MD5: %v", sourceMD5, err)
}
}
}
putBlobOptions := azblob.UploadStreamToBlockBlobOptions{
BufferSize: int(o.fs.opt.ChunkSize),
MaxBuffers: 4,
Metadata: o.meta,
BlobHTTPHeaders: httpHeaders,
}
// FIXME Until https://github.com/Azure/azure-storage-blob-go/pull/75
// is merged the SDK can't upload a single blob of exactly the chunk
// size, so upload with a multipart upload to work around.
// See: https://github.com/rclone/rclone/issues/2653
multipartUpload := size < 0 || size >= int64(o.fs.opt.UploadCutoff)
if size == int64(o.fs.opt.ChunkSize) {
multipartUpload = true
fs.Debugf(o, "Setting multipart upload for file of chunk size (%d) to work around SDK bug", size)
}
// Don't retry, return a retry error instead
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
if multipartUpload {
// If a large file upload in chunks
err = o.uploadMultipart(ctx, in, size, &blob, &httpHeaders)
} else {
// Write a small blob in one transaction
blockBlobURL := blob.ToBlockBlobURL()
_, err = azblob.UploadStreamToBlockBlob(ctx, in, blockBlobURL, putBlobOptions)
}
return o.fs.shouldRetry(err)
})
if err != nil {
return err
}
// Refresh metadata on object
o.clearMetaData()
err = o.readMetaData()
if err != nil {
return err
}
// If tier is not changed or not specified, do not attempt to invoke `SetBlobTier` operation
if o.fs.opt.AccessTier == string(defaultAccessTier) || o.fs.opt.AccessTier == string(o.AccessTier()) {
return nil
}
// Now, set blob tier based on configured access tier
return o.SetTier(o.fs.opt.AccessTier)
}
// Remove an object
func (o *Object) Remove(ctx context.Context) error {
blob := o.getBlobReference()
snapShotOptions := azblob.DeleteSnapshotsOptionNone
ac := azblob.BlobAccessConditions{}
return o.fs.pacer.Call(func() (bool, error) {
_, err := blob.Delete(ctx, snapShotOptions, ac)
return o.fs.shouldRetry(err)
})
}
// MimeType of an Object if known, "" otherwise
func (o *Object) MimeType(ctx context.Context) string {
return o.mimeType
}
// AccessTier of an object, default is of type none
func (o *Object) AccessTier() azblob.AccessTierType {
return o.accessTier
}
// SetTier performs changing object tier
func (o *Object) SetTier(tier string) error {
if !validateAccessTier(tier) {
return errors.Errorf("Tier %s not supported by Azure Blob Storage", tier)
}
// Check if current tier already matches with desired tier
if o.GetTier() == tier {
return nil
}
desiredAccessTier := azblob.AccessTierType(tier)
blob := o.getBlobReference()
ctx := context.Background()
err := o.fs.pacer.Call(func() (bool, error) {
_, err := blob.SetTier(ctx, desiredAccessTier, azblob.LeaseAccessConditions{})
return o.fs.shouldRetry(err)
})
if err != nil {
return errors.Wrap(err, "Failed to set Blob Tier")
}
// Set access tier on local object also, this typically
// gets updated on get blob properties
o.accessTier = desiredAccessTier
fs.Debugf(o, "Successfully changed object tier to %s", tier)
return nil
}
// GetTier returns object tier in azure as string
func (o *Object) GetTier() string {
return string(o.accessTier)
}
// Check the interfaces are satisfied
var (
_ fs.Fs = &Fs{}
_ fs.Copier = &Fs{}
_ fs.PutStreamer = &Fs{}
_ fs.Purger = &Fs{}
_ fs.ListRer = &Fs{}
_ fs.Object = &Object{}
_ fs.MimeTyper = &Object{}
_ fs.GetTierer = &Object{}
_ fs.SetTierer = &Object{}
)
| 1 | 12,570 | Can you remove this blank line and put the added import in sorted order (likely your editor will do this) | rclone-rclone | go |
@@ -606,12 +606,16 @@ static int listener_setup_ssl(h2o_configurator_command_t *cmd, h2o_configurator_
: "share/h2o/fetch-ocsp-response";
if (ocsp_update_interval != 0) {
switch (conf.run_mode) {
- case RUN_MODE_WORKER:
+ case RUN_MODE_WORKER: {
+ int err;
ssl_config->ocsp_stapling.interval =
ocsp_update_interval; /* is also used as a flag for indicating if the updater thread was spawned */
ssl_config->ocsp_stapling.max_failures = ocsp_max_failures;
- pthread_create(&ssl_config->ocsp_stapling.updater_tid, NULL, ocsp_updater_thread, ssl_config);
- break;
+ err = pthread_create(&ssl_config->ocsp_stapling.updater_tid, NULL, ocsp_updater_thread, ssl_config);
+ if (err != 0) {
+ fprintf(stderr, "[OCSP Stapling] pthread_create for ocsp_updater_thread failed. errno:%d\n", err);
+ }
+ } break;
case RUN_MODE_MASTER:
case RUN_MODE_DAEMON:
/* nothing to do */ | 1 | /*
* Copyright (c) 2014,2015 DeNA Co., Ltd., Kazuho Oku, Tatsuhiko Kubo,
* Domingo Alvarez Duarte, Nick Desaulniers,
* Jeff Marison
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <pwd.h>
#include <signal.h>
#include <spawn.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#ifdef __linux__
#include <execinfo.h>
#endif
#include "yoml-parser.h"
#include "h2o.h"
#include "h2o/configurator.h"
#include "h2o/http1.h"
#include "h2o/http2.h"
#include "h2o/serverutil.h"
/* simply use a large value, and let the kernel clip it to the internal max */
#define H2O_SOMAXCONN (65535)
#ifdef TCP_FASTOPEN
#define H2O_DEFAULT_LENGTH_TCP_FASTOPEN_QUEUE 4096
#else
#define H2O_DEFAULT_LENGTH_TCP_FASTOPEN_QUEUE 0
#endif
#define H2O_DEFAULT_NUM_NAME_RESOLUTION_THREADS 32
struct listener_ssl_config_t {
H2O_VECTOR(h2o_iovec_t) hostnames;
char *certificate_file;
SSL_CTX *ctx;
#ifndef OPENSSL_NO_OCSP
struct {
uint64_t interval;
unsigned max_failures;
char *cmd;
pthread_t updater_tid; /* should be valid when and only when interval != 0 */
struct {
pthread_mutex_t mutex;
h2o_buffer_t *data;
} response;
} ocsp_stapling;
#endif
};
struct listener_config_t {
int fd;
struct sockaddr_storage addr;
socklen_t addrlen;
h2o_hostconf_t **hosts;
H2O_VECTOR(struct listener_ssl_config_t) ssl;
};
struct listener_ctx_t {
h2o_context_t *ctx;
h2o_hostconf_t **hosts;
SSL_CTX *ssl_ctx;
h2o_socket_t *sock;
};
typedef enum en_run_mode_t {
RUN_MODE_WORKER = 0,
RUN_MODE_MASTER,
RUN_MODE_DAEMON,
RUN_MODE_TEST,
} run_mode_t;
static struct {
h2o_globalconf_t globalconf;
run_mode_t run_mode;
struct {
int *fds;
char *bound_fd_map; /* has `num_fds` elements, set to 1 if fd[index] was bound to one of the listeners */
size_t num_fds;
} server_starter;
struct listener_config_t **listeners;
size_t num_listeners;
struct passwd *running_user; /* NULL if not set */
char *pid_file;
char *error_log;
int max_connections;
size_t num_threads;
int tfo_queues;
struct {
pthread_t tid;
h2o_context_t ctx;
h2o_multithread_receiver_t server_notifications;
} *threads;
volatile sig_atomic_t shutdown_requested;
struct {
/* unused buffers exist to avoid false sharing of the cache line */
char _unused1[32];
int _num_connections; /* should use atomic functions to update the value */
char _unused2[32];
} state;
} conf = {
{}, /* globalconf */
0, /* dry-run */
{}, /* server_starter */
NULL, /* listeners */
0, /* num_listeners */
NULL, /* running_user */
NULL, /* pid_file */
NULL, /* error_log */
1024, /* max_connections */
0, /* initialized in main() */
0, /* initialized in main() */
NULL, /* thread_ids */
0, /* shutdown_requested */
{}, /* state */
};
static void set_cloexec(int fd)
{
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
perror("failed to set FD_CLOEXEC");
abort();
}
}
static char *get_cmd_path(const char *cmd)
{
char *root, *cmd_fullpath;
/* just return the cmd (being strdup'ed) in case we do not need to prefix the value */
if (cmd[0] == '/' || strchr(cmd, '/') == NULL)
goto ReturnOrig;
/* obtain root */
if ((root = getenv("H2O_ROOT")) == NULL) {
#ifdef H2O_ROOT
root = H2O_ROOT;
#endif
if (root == NULL)
goto ReturnOrig;
}
/* build full-path and return */
cmd_fullpath = h2o_mem_alloc(strlen(root) + strlen(cmd) + 2);
sprintf(cmd_fullpath, "%s/%s", root, cmd);
return cmd_fullpath;
ReturnOrig:
return h2o_strdup(NULL, cmd, SIZE_MAX).base;
}
static int on_openssl_print_errors(const char *str, size_t len, void *fp)
{
fwrite(str, 1, len, fp);
return (int)len;
}
static unsigned long openssl_thread_id_callback(void)
{
return (unsigned long)pthread_self();
}
static pthread_mutex_t *openssl_thread_locks;
static void openssl_thread_lock_callback(int mode, int n, const char *file, int line)
{
if ((mode & CRYPTO_LOCK) != 0) {
pthread_mutex_lock(openssl_thread_locks + n);
} else if ((mode & CRYPTO_UNLOCK) != 0) {
pthread_mutex_unlock(openssl_thread_locks + n);
} else {
assert(!"unexpected mode");
}
}
static void init_openssl(void)
{
static int ready = 0;
if (!ready) {
int nlocks = CRYPTO_num_locks(), i;
openssl_thread_locks = h2o_mem_alloc(sizeof(*openssl_thread_locks) * nlocks);
for (i = 0; i != nlocks; ++i)
pthread_mutex_init(openssl_thread_locks + i, NULL);
CRYPTO_set_locking_callback(openssl_thread_lock_callback);
CRYPTO_set_id_callback(openssl_thread_id_callback);
/* TODO [OpenSSL] set dynlock callbacks for better performance */
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
ready = 1;
}
}
static void setup_ecc_key(SSL_CTX *ssl_ctx)
{
int nid = NID_X9_62_prime256v1;
EC_KEY *key = EC_KEY_new_by_curve_name(nid);
if (key == NULL) {
fprintf(stderr, "Failed to create curve \"%s\"\n", OBJ_nid2sn(nid));
return;
}
SSL_CTX_set_tmp_ecdh(ssl_ctx, key);
EC_KEY_free(key);
}
static int on_sni_callback(SSL *ssl, int *ad, void *arg)
{
struct listener_config_t *listener = arg;
const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
size_t ctx_index = 0;
if (name != NULL) {
size_t i, j, name_len = strlen(name);
for (i = 0; i != listener->ssl.size; ++i) {
struct listener_ssl_config_t *ssl_config = listener->ssl.entries + i;
for (j = 0; j != ssl_config->hostnames.size; ++j) {
if (h2o_lcstris(name, name_len, ssl_config->hostnames.entries[j].base, ssl_config->hostnames.entries[j].len)) {
ctx_index = i;
goto Found;
}
}
}
ctx_index = 0;
Found:
;
}
if (SSL_get_SSL_CTX(ssl) != listener->ssl.entries[ctx_index].ctx)
SSL_set_SSL_CTX(ssl, listener->ssl.entries[ctx_index].ctx);
return SSL_TLSEXT_ERR_OK;
}
#ifndef OPENSSL_NO_OCSP
static void update_ocsp_stapling(struct listener_ssl_config_t *ssl_conf, h2o_buffer_t *resp)
{
pthread_mutex_lock(&ssl_conf->ocsp_stapling.response.mutex);
if (ssl_conf->ocsp_stapling.response.data != NULL)
h2o_buffer_dispose(&ssl_conf->ocsp_stapling.response.data);
ssl_conf->ocsp_stapling.response.data = resp;
pthread_mutex_unlock(&ssl_conf->ocsp_stapling.response.mutex);
}
static int get_ocsp_response(const char *cert_fn, const char *cmd, h2o_buffer_t **resp)
{
char *cmd_fullpath = get_cmd_path(cmd), *argv[] = {cmd_fullpath, (char *)cert_fn, NULL};
int child_status, ret;
if (h2o_read_command(cmd_fullpath, argv, resp, &child_status) != 0) {
fprintf(stderr, "[OCSP Stapling] failed to execute %s:%s\n", cmd, strerror(errno));
switch (errno) {
case EACCES:
case ENOENT:
case ENOEXEC:
/* permanent errors */
ret = EX_CONFIG;
goto Exit;
default:
ret = EX_TEMPFAIL;
goto Exit;
}
}
if (!(WIFEXITED(child_status) && WEXITSTATUS(child_status) == 0))
h2o_buffer_dispose(resp);
if (!WIFEXITED(child_status)) {
fprintf(stderr, "[OCSP Stapling] command %s was killed by signal %d\n", cmd_fullpath, WTERMSIG(child_status));
ret = EX_TEMPFAIL;
goto Exit;
}
ret = WEXITSTATUS(child_status);
Exit:
free(cmd_fullpath);
return ret;
}
static void *ocsp_updater_thread(void *_ssl_conf)
{
struct listener_ssl_config_t *ssl_conf = _ssl_conf;
time_t next_at = 0, now;
unsigned fail_cnt = 0;
int status;
h2o_buffer_t *resp;
assert(ssl_conf->ocsp_stapling.interval != 0);
while (1) {
/* sleep until next_at */
if ((now = time(NULL)) < next_at) {
time_t sleep_secs = next_at - now;
sleep(sleep_secs < UINT_MAX ? (unsigned)sleep_secs : UINT_MAX);
continue;
}
/* fetch the response */
status = get_ocsp_response(ssl_conf->certificate_file, ssl_conf->ocsp_stapling.cmd, &resp);
switch (status) {
case 0: /* success */
fail_cnt = 0;
update_ocsp_stapling(ssl_conf, resp);
fprintf(stderr, "[OCSP Stapling] successfully updated the response for certificate file:%s\n",
ssl_conf->certificate_file);
break;
case EX_TEMPFAIL: /* temporary failure */
if (fail_cnt == ssl_conf->ocsp_stapling.max_failures) {
fprintf(stderr,
"[OCSP Stapling] OCSP stapling is temporary disabled due to repeated errors for certificate file:%s\n",
ssl_conf->certificate_file);
update_ocsp_stapling(ssl_conf, NULL);
} else {
fprintf(stderr, "[OCSP Stapling] reusing old response due to a temporary error occurred while fetching OCSP "
"response for certificate file:%s\n",
ssl_conf->certificate_file);
++fail_cnt;
}
break;
default: /* permanent failure */
fprintf(stderr, "[OCSP Stapling] disabled for certificate file:%s\n", ssl_conf->certificate_file);
goto Exit;
}
/* update next_at */
next_at = time(NULL) + ssl_conf->ocsp_stapling.interval;
}
Exit:
return NULL;
}
static int on_ocsp_stapling_callback(SSL *ssl, void *_ssl_conf)
{
struct listener_ssl_config_t *ssl_conf = _ssl_conf;
void *resp = NULL;
size_t len = 0;
/* fetch ocsp response */
pthread_mutex_lock(&ssl_conf->ocsp_stapling.response.mutex);
if (ssl_conf->ocsp_stapling.response.data != NULL) {
resp = CRYPTO_malloc((int)ssl_conf->ocsp_stapling.response.data->size, __FILE__, __LINE__);
if (resp != NULL) {
len = ssl_conf->ocsp_stapling.response.data->size;
memcpy(resp, ssl_conf->ocsp_stapling.response.data->bytes, len);
}
}
pthread_mutex_unlock(&ssl_conf->ocsp_stapling.response.mutex);
if (resp != NULL) {
SSL_set_tlsext_status_ocsp_resp(ssl, resp, len);
return SSL_TLSEXT_ERR_OK;
} else {
return SSL_TLSEXT_ERR_NOACK;
}
}
#endif
static void listener_setup_ssl_add_host(struct listener_ssl_config_t *ssl_config, h2o_iovec_t host)
{
const char *host_end = memchr(host.base, ':', host.len);
if (host_end == NULL)
host_end = host.base + host.len;
h2o_vector_reserve(NULL, (void *)&ssl_config->hostnames, sizeof(ssl_config->hostnames.entries[0]),
ssl_config->hostnames.size + 1);
ssl_config->hostnames.entries[ssl_config->hostnames.size++] = h2o_iovec_init(host.base, host_end - host.base);
}
static int listener_setup_ssl(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *listen_node,
yoml_t *ssl_node, struct listener_config_t *listener, int listener_is_new)
{
SSL_CTX *ssl_ctx = NULL;
yoml_t *certificate_file = NULL, *key_file = NULL, *dh_file = NULL, *minimum_version = NULL, *cipher_suite = NULL,
*ocsp_update_cmd = NULL, *ocsp_update_interval_node = NULL, *ocsp_max_failures_node = NULL;
long ssl_options = SSL_OP_ALL;
uint64_t ocsp_update_interval = 4 * 60 * 60; /* defaults to 4 hours */
unsigned ocsp_max_failures = 3; /* defaults to 3; permit 3 failures before temporary disabling OCSP stapling */
if (!listener_is_new) {
if (listener->ssl.size != 0 && ssl_node == NULL) {
h2o_configurator_errprintf(cmd, listen_node, "cannot accept HTTP; already defined to accept HTTPS");
return -1;
}
if (listener->ssl.size == 0 && ssl_node != NULL) {
h2o_configurator_errprintf(cmd, ssl_node, "cannot accept HTTPS; already defined to accept HTTP");
return -1;
}
}
if (ssl_node == NULL)
return 0;
if (ssl_node->type != YOML_TYPE_MAPPING) {
h2o_configurator_errprintf(cmd, ssl_node, "`ssl` is not a mapping");
return -1;
}
{ /* parse */
size_t i;
for (i = 0; i != ssl_node->data.sequence.size; ++i) {
yoml_t *key = ssl_node->data.mapping.elements[i].key, *value = ssl_node->data.mapping.elements[i].value;
/* obtain the target command */
if (key->type != YOML_TYPE_SCALAR) {
h2o_configurator_errprintf(NULL, key, "command must be a string");
return -1;
}
#define FETCH_PROPERTY(n, p) \
if (strcmp(key->data.scalar, n) == 0) { \
if (value->type != YOML_TYPE_SCALAR) { \
h2o_configurator_errprintf(cmd, value, "property of `" n "` must be a string"); \
return -1; \
} \
p = value; \
continue; \
}
FETCH_PROPERTY("certificate-file", certificate_file);
FETCH_PROPERTY("key-file", key_file);
FETCH_PROPERTY("minimum-version", minimum_version);
FETCH_PROPERTY("cipher-suite", cipher_suite);
FETCH_PROPERTY("ocsp-update-cmd", ocsp_update_cmd);
FETCH_PROPERTY("ocsp-update-interval", ocsp_update_interval_node);
FETCH_PROPERTY("ocsp-max-failures", ocsp_max_failures_node);
FETCH_PROPERTY("dh-file", dh_file);
if (strcmp(key->data.scalar, "cipher-preference") == 0) {
if (value->type == YOML_TYPE_SCALAR && strcasecmp(value->data.scalar, "client") == 0) {
ssl_options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
} else if (value->type == YOML_TYPE_SCALAR && strcasecmp(value->data.scalar, "server") == 0) {
ssl_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
} else {
h2o_configurator_errprintf(cmd, value, "property of `cipher-preference` must be either of: `client`, `server`");
return -1;
}
continue;
}
h2o_configurator_errprintf(cmd, key, "unknown property: %s", key->data.scalar);
return -1;
#undef FETCH_PROPERTY
}
if (certificate_file == NULL) {
h2o_configurator_errprintf(cmd, ssl_node, "could not find mandatory property `certificate-file`");
return -1;
}
if (key_file == NULL) {
h2o_configurator_errprintf(cmd, ssl_node, "could not find mandatory property `key-file`");
return -1;
}
if (minimum_version != NULL) {
#define MAP(tok, op) \
if (strcasecmp(minimum_version->data.scalar, tok) == 0) { \
ssl_options |= (op); \
goto VersionFound; \
}
MAP("sslv2", 0);
MAP("sslv3", SSL_OP_NO_SSLv2);
MAP("tlsv1", SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
MAP("tlsv1.1", SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1);
#ifdef SSL_OP_NO_TLSv1_1
MAP("tlsv1.2", SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
#endif
#ifdef SSL_OP_NO_TLSv1_2
MAP("tlsv1.3", SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
#endif
#undef MAP
h2o_configurator_errprintf(cmd, minimum_version, "unknown protocol version: %s", minimum_version->data.scalar);
VersionFound:
;
} else {
/* default is >= TLSv1 */
ssl_options |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
}
if (ocsp_update_interval_node != NULL) {
if (h2o_configurator_scanf(cmd, ocsp_update_interval_node, "%" PRIu64, &ocsp_update_interval) != 0)
goto Error;
}
if (ocsp_max_failures_node != NULL) {
if (h2o_configurator_scanf(cmd, ocsp_max_failures_node, "%u", &ocsp_max_failures) != 0)
goto Error;
}
}
/* add the host to the existing SSL config, if the certificate file is already registered */
if (ctx->hostconf != NULL) {
size_t i;
for (i = 0; i != listener->ssl.size; ++i) {
struct listener_ssl_config_t *ssl_config = listener->ssl.entries + i;
if (strcmp(ssl_config->certificate_file, certificate_file->data.scalar) == 0) {
listener_setup_ssl_add_host(ssl_config, ctx->hostconf->authority.hostport);
return 0;
}
}
}
/* disable tls compression to avoid "CRIME" attacks (see http://en.wikipedia.org/wiki/CRIME) */
#ifdef SSL_OP_NO_COMPRESSION
ssl_options |= SSL_OP_NO_COMPRESSION;
#endif
/* setup */
init_openssl();
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
SSL_CTX_set_options(ssl_ctx, ssl_options);
setup_ecc_key(ssl_ctx);
if (SSL_CTX_use_certificate_chain_file(ssl_ctx, certificate_file->data.scalar) != 1) {
h2o_configurator_errprintf(cmd, certificate_file, "failed to load certificate file:%s\n", certificate_file->data.scalar);
ERR_print_errors_cb(on_openssl_print_errors, stderr);
goto Error;
}
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, key_file->data.scalar, SSL_FILETYPE_PEM) != 1) {
h2o_configurator_errprintf(cmd, key_file, "failed to load private key file:%s\n", key_file->data.scalar);
ERR_print_errors_cb(on_openssl_print_errors, stderr);
goto Error;
}
if (cipher_suite != NULL && SSL_CTX_set_cipher_list(ssl_ctx, cipher_suite->data.scalar) != 1) {
h2o_configurator_errprintf(cmd, cipher_suite, "failed to setup SSL cipher suite\n");
ERR_print_errors_cb(on_openssl_print_errors, stderr);
goto Error;
}
if (dh_file != NULL) {
BIO *bio = BIO_new_file(dh_file->data.scalar, "r");
if (bio == NULL) {
h2o_configurator_errprintf(cmd, dh_file, "failed to load dhparam file:%s\n", dh_file->data.scalar);
ERR_print_errors_cb(on_openssl_print_errors, stderr);
goto Error;
}
DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
if (dh == NULL) {
h2o_configurator_errprintf(cmd, dh_file, "failed to load dhparam file:%s\n", dh_file->data.scalar);
ERR_print_errors_cb(on_openssl_print_errors, stderr);
goto Error;
}
SSL_CTX_set_tmp_dh(ssl_ctx, dh);
SSL_CTX_set_options(ssl_ctx, SSL_OP_SINGLE_DH_USE);
DH_free(dh);
}
/* setup protocol negotiation methods */
#if H2O_USE_NPN
h2o_ssl_register_npn_protocols(ssl_ctx, h2o_http2_npn_protocols);
#endif
#if H2O_USE_ALPN
h2o_ssl_register_alpn_protocols(ssl_ctx, h2o_http2_alpn_protocols);
#endif
/* set SNI callback to the first SSL context, when and only when it should be used */
if (listener->ssl.size == 1) {
SSL_CTX_set_tlsext_servername_callback(listener->ssl.entries[0].ctx, on_sni_callback);
SSL_CTX_set_tlsext_servername_arg(listener->ssl.entries[0].ctx, listener);
}
{ /* create a new entry in the SSL context list */
struct listener_ssl_config_t *ssl_config;
h2o_vector_reserve(NULL, (void *)&listener->ssl, sizeof(listener->ssl.entries[0]), listener->ssl.size + 1);
ssl_config = listener->ssl.entries + listener->ssl.size++;
memset(ssl_config, 0, sizeof(*ssl_config));
if (ctx->hostconf != NULL) {
listener_setup_ssl_add_host(ssl_config, ctx->hostconf->authority.hostport);
}
ssl_config->ctx = ssl_ctx;
ssl_config->certificate_file = h2o_strdup(NULL, certificate_file->data.scalar, SIZE_MAX).base;
#ifdef OPENSSL_NO_OCSP
if (ocsp_update_interval != 0)
fprintf(stderr, "[OCSP Stapling] disabled (not support by the SSL library)\n");
#else
SSL_CTX_set_tlsext_status_cb(ssl_ctx, on_ocsp_stapling_callback);
SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_config);
pthread_mutex_init(&ssl_config->ocsp_stapling.response.mutex, NULL);
ssl_config->ocsp_stapling.cmd = ocsp_update_cmd != NULL ? h2o_strdup(NULL, ocsp_update_cmd->data.scalar, SIZE_MAX).base
: "share/h2o/fetch-ocsp-response";
if (ocsp_update_interval != 0) {
switch (conf.run_mode) {
case RUN_MODE_WORKER:
ssl_config->ocsp_stapling.interval =
ocsp_update_interval; /* is also used as a flag for indicating if the updater thread was spawned */
ssl_config->ocsp_stapling.max_failures = ocsp_max_failures;
pthread_create(&ssl_config->ocsp_stapling.updater_tid, NULL, ocsp_updater_thread, ssl_config);
break;
case RUN_MODE_MASTER:
case RUN_MODE_DAEMON:
/* nothing to do */
break;
case RUN_MODE_TEST: {
h2o_buffer_t *respbuf;
fprintf(stderr, "[OCSP Stapling] testing for certificate file:%s\n", certificate_file->data.scalar);
switch (get_ocsp_response(certificate_file->data.scalar, ssl_config->ocsp_stapling.cmd, &respbuf)) {
case 0:
h2o_buffer_dispose(&respbuf);
fprintf(stderr, "[OCSP Stapling] stapling works for file:%s\n", certificate_file->data.scalar);
break;
case EX_TEMPFAIL:
h2o_configurator_errprintf(cmd, certificate_file, "[OCSP Stapling] temporary failed for file:%s\n",
certificate_file->data.scalar);
break;
default:
h2o_configurator_errprintf(cmd, certificate_file,
"[OCSP Stapling] does not work, will be disabled for file:%s\n",
certificate_file->data.scalar);
break;
}
} break;
}
}
#endif
}
return 0;
Error:
if (ssl_ctx != NULL)
SSL_CTX_free(ssl_ctx);
return -1;
}
static struct listener_config_t *find_listener(struct sockaddr *addr, socklen_t addrlen)
{
size_t i;
for (i = 0; i != conf.num_listeners; ++i) {
struct listener_config_t *listener = conf.listeners[i];
if (listener->addrlen == addrlen && h2o_socket_compare_address((void *)&listener->addr, addr) == 0)
return listener;
}
return NULL;
}
static struct listener_config_t *add_listener(int fd, struct sockaddr *addr, socklen_t addrlen, int is_global)
{
struct listener_config_t *listener = h2o_mem_alloc(sizeof(*listener));
memcpy(&listener->addr, addr, addrlen);
listener->fd = fd;
listener->addrlen = addrlen;
if (is_global) {
listener->hosts = NULL;
} else {
listener->hosts = h2o_mem_alloc(sizeof(listener->hosts[0]));
listener->hosts[0] = NULL;
}
memset(&listener->ssl, 0, sizeof(listener->ssl));
conf.listeners = h2o_mem_realloc(conf.listeners, sizeof(*conf.listeners) * (conf.num_listeners + 1));
conf.listeners[conf.num_listeners++] = listener;
return listener;
}
static int find_listener_from_server_starter(struct sockaddr *addr)
{
size_t i;
assert(conf.server_starter.fds != NULL);
assert(conf.server_starter.num_fds != 0);
for (i = 0; i != conf.server_starter.num_fds; ++i) {
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
if (getsockname(conf.server_starter.fds[i], (void *)&sa, &salen) != 0) {
fprintf(stderr, "could not get the socket address of fd %d given as $SERVER_STARTER_PORT\n",
conf.server_starter.fds[i]);
exit(EX_CONFIG);
}
if (h2o_socket_compare_address((void *)&sa, addr) == 0)
goto Found;
}
/* not found */
return -1;
Found:
conf.server_starter.bound_fd_map[i] = 1;
return conf.server_starter.fds[i];
}
static int open_unix_listener(h2o_configurator_command_t *cmd, yoml_t *node, struct sockaddr_un *sun)
{
struct stat st;
int fd;
/* remove existing socket file as suggested in #45 */
if (lstat(sun->sun_path, &st) == 0) {
if (S_ISSOCK(st.st_mode)) {
unlink(sun->sun_path);
} else {
h2o_configurator_errprintf(cmd, node, "path:%s already exists and is not an unix socket.", sun->sun_path);
return -1;
}
}
/* add new listener */
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1 || bind(fd, (void *)sun, sizeof(*sun)) != 0 ||
listen(fd, H2O_SOMAXCONN) != 0) {
if (fd != -1)
close(fd);
h2o_configurator_errprintf(NULL, node, "failed to listen to socket:%s: %s", sun->sun_path, strerror(errno));
return -1;
}
set_cloexec(fd);
return fd;
}
static int open_tcp_listener(h2o_configurator_command_t *cmd, yoml_t *node, const char *hostname, const char *servname, int domain,
int type, int protocol, struct sockaddr *addr, socklen_t addrlen)
{
int fd;
if ((fd = socket(domain, type, protocol)) == -1)
goto Error;
set_cloexec(fd);
{ /* set reuseaddr */
int flag = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) != 0)
goto Error;
}
#ifdef TCP_DEFER_ACCEPT
{ /* set TCP_DEFER_ACCEPT */
int flag = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &flag, sizeof(flag)) != 0)
goto Error;
}
#endif
#ifdef IPV6_V6ONLY
/* set IPv6only */
if (domain == AF_INET6) {
int flag = 1;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &flag, sizeof(flag)) != 0)
goto Error;
}
#endif
/* set TCP_FASTOPEN; when tfo_queues is zero TFO is always disabled */
if (conf.tfo_queues > 0) {
#ifdef TCP_FASTOPEN
if (setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, (const void *)&conf.tfo_queues, sizeof(conf.tfo_queues)) != 0) {
fprintf(stderr, "failed to set TCP_FASTOPEN:%s\n", strerror(errno));
goto Error;
}
#else
assert(!"conf.tfo_queues not zero on platform without TCP_FASTOPEN");
#endif
}
if (bind(fd, addr, addrlen) != 0)
goto Error;
if (listen(fd, H2O_SOMAXCONN) != 0)
goto Error;
return fd;
Error:
if (fd != -1)
close(fd);
h2o_configurator_errprintf(NULL, node, "failed to listen to port %s:%s: %s", hostname != NULL ? hostname : "ANY", servname,
strerror(errno));
return -1;
}
static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
const char *hostname = NULL, *servname = NULL, *type = "tcp";
yoml_t *ssl_node = NULL;
/* fetch servname (and hostname) */
switch (node->type) {
case YOML_TYPE_SCALAR:
servname = node->data.scalar;
break;
case YOML_TYPE_MAPPING: {
yoml_t *t;
if ((t = yoml_get(node, "host")) != NULL) {
if (t->type != YOML_TYPE_SCALAR) {
h2o_configurator_errprintf(cmd, t, "`host` is not a string");
return -1;
}
hostname = t->data.scalar;
}
if ((t = yoml_get(node, "port")) == NULL) {
h2o_configurator_errprintf(cmd, node, "cannot find mandatory property `port`");
return -1;
}
if (t->type != YOML_TYPE_SCALAR) {
h2o_configurator_errprintf(cmd, node, "`port` is not a string");
return -1;
}
servname = t->data.scalar;
if ((t = yoml_get(node, "type")) != NULL) {
if (t->type != YOML_TYPE_SCALAR) {
h2o_configurator_errprintf(cmd, t, "`type` is not a string");
return -1;
}
type = t->data.scalar;
}
if ((t = yoml_get(node, "ssl")) != NULL)
ssl_node = t;
} break;
default:
h2o_configurator_errprintf(cmd, node, "value must be a string or a mapping (with keys: `port` and optionally `host`)");
return -1;
}
if (strcmp(type, "unix") == 0) {
/* unix socket */
struct sockaddr_un sun;
int listener_is_new;
struct listener_config_t *listener;
/* build sockaddr */
if (strlen(servname) >= sizeof(sun.sun_path)) {
h2o_configurator_errprintf(cmd, node, "path:%s is too long as a unix socket name", servname);
return -1;
}
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path, servname);
/* find existing listener or create a new one */
listener_is_new = 0;
if ((listener = find_listener((void *)&sun, sizeof(sun))) == NULL) {
int fd = -1;
switch (conf.run_mode) {
case RUN_MODE_WORKER:
if (conf.server_starter.fds != NULL) {
if ((fd = find_listener_from_server_starter((void *)&sun)) == -1) {
h2o_configurator_errprintf(cmd, node, "unix socket:%s is not being bound to the server\n", sun.sun_path);
return -1;
}
} else {
if ((fd = open_unix_listener(cmd, node, &sun)) == -1)
return -1;
}
break;
default:
break;
}
listener = add_listener(fd, (struct sockaddr *)&sun, sizeof(sun), ctx->hostconf == NULL);
listener_is_new = 1;
}
if (listener_setup_ssl(cmd, ctx, node, ssl_node, listener, listener_is_new) != 0)
return -1;
if (listener->hosts != NULL && ctx->hostconf != NULL)
h2o_append_to_null_terminated_list((void *)&listener->hosts, ctx->hostconf);
} else if (strcmp(type, "tcp") == 0) {
/* TCP socket */
struct addrinfo hints, *res, *ai;
int error;
/* call getaddrinfo */
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV | AI_PASSIVE;
if ((error = getaddrinfo(hostname, servname, &hints, &res)) != 0) {
h2o_configurator_errprintf(cmd, node, "failed to resolve the listening address: %s", gai_strerror(error));
return -1;
} else if (res == NULL) {
h2o_configurator_errprintf(cmd, node, "failed to resolve the listening address: getaddrinfo returned an empty list");
return -1;
}
/* listen to the returned addresses */
for (ai = res; ai != NULL; ai = ai->ai_next) {
struct listener_config_t *listener = find_listener(ai->ai_addr, ai->ai_addrlen);
int listener_is_new = 0;
if (listener == NULL) {
int fd = -1;
switch (conf.run_mode) {
case RUN_MODE_WORKER:
if (conf.server_starter.fds != NULL) {
if ((fd = find_listener_from_server_starter(ai->ai_addr)) == -1) {
h2o_configurator_errprintf(cmd, node, "tcp socket:%s:%s is not being bound to the server\n", hostname,
servname);
return -1;
}
} else {
if ((fd = open_tcp_listener(cmd, node, hostname, servname, ai->ai_family, ai->ai_socktype, ai->ai_protocol,
ai->ai_addr, ai->ai_addrlen)) == -1)
return -1;
}
break;
default:
break;
}
listener = add_listener(fd, ai->ai_addr, ai->ai_addrlen, ctx->hostconf == NULL);
listener_is_new = 1;
}
if (listener_setup_ssl(cmd, ctx, node, ssl_node, listener, listener_is_new) != 0)
return -1;
if (listener->hosts != NULL && ctx->hostconf != NULL)
h2o_append_to_null_terminated_list((void *)&listener->hosts, ctx->hostconf);
}
/* release res */
freeaddrinfo(res);
} else {
h2o_configurator_errprintf(cmd, node, "unknown listen type: %s", type);
return -1;
}
return 0;
}
static int on_config_listen_enter(h2o_configurator_t *_configurator, h2o_configurator_context_t *ctx, yoml_t *node)
{
return 0;
}
static int on_config_listen_exit(h2o_configurator_t *_configurator, h2o_configurator_context_t *ctx, yoml_t *node)
{
if (ctx->hostconf == NULL) {
/* at global level: bind all hostconfs to the global-level listeners */
size_t i;
for (i = 0; i != conf.num_listeners; ++i) {
struct listener_config_t *listener = conf.listeners[i];
if (listener->hosts == NULL)
listener->hosts = conf.globalconf.hosts;
}
} else if (ctx->pathconf == NULL) {
/* at host-level */
if (conf.num_listeners == 0) {
h2o_configurator_errprintf(
NULL, node,
"mandatory configuration directive `listen` does not exist, neither at global level or at this host level");
return -1;
}
}
return 0;
}
static int setup_running_user(const char *login)
{
struct passwd *passwdbuf = h2o_mem_alloc(sizeof(*passwdbuf));
char *buf;
size_t bufsz = 4096;
Redo:
buf = h2o_mem_alloc(bufsz);
if (getpwnam_r(login, passwdbuf, buf, bufsz, &conf.running_user) != 0) {
if (errno == ERANGE
#ifdef __APPLE__
|| errno == EINVAL /* OS X 10.9.5 returns EINVAL if bufsz == 16 */
#endif
) {
free(buf);
bufsz *= 2;
goto Redo;
}
perror("getpwnam_r");
}
if (conf.running_user == NULL)
return -1;
return 0;
}
static int on_config_user(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
if (setup_running_user(node->data.scalar) != 0) {
h2o_configurator_errprintf(cmd, node, "user:%s does not exist", node->data.scalar);
return -1;
}
return 0;
}
static int on_config_pid_file(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
conf.pid_file = h2o_strdup(NULL, node->data.scalar, SIZE_MAX).base;
return 0;
}
static int on_config_error_log(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
conf.error_log = h2o_strdup(NULL, node->data.scalar, SIZE_MAX).base;
return 0;
}
static int on_config_max_connections(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
return h2o_configurator_scanf(cmd, node, "%d", &conf.max_connections);
}
static int on_config_num_threads(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
if (h2o_configurator_scanf(cmd, node, "%zu", &conf.num_threads) != 0)
return -1;
if (conf.num_threads == 0) {
h2o_configurator_errprintf(cmd, node, "num-threads should be >=1");
return -1;
}
return 0;
}
static int on_config_num_name_resolution_threads(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
if (h2o_configurator_scanf(cmd, node, "%zu", &h2o_hostinfo_max_threads) != 0)
return -1;
if (h2o_hostinfo_max_threads == 0) {
h2o_configurator_errprintf(cmd, node, "num-name-resolution-threads should be >=1");
return -1;
}
return 0;
}
static int on_config_tcp_fastopen(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
if (h2o_configurator_scanf(cmd, node, "%d", &conf.tfo_queues) != 0)
return -1;
#ifndef TCP_FASTOPEN
if (conf.tfo_queues != 0) {
h2o_configurator_errprintf(cmd, node, "[warning] ignoring the value; the platform does not support TCP_FASTOPEN");
conf.tfo_queues = 0;
}
#endif
return 0;
}
yoml_t *load_config(const char *fn)
{
FILE *fp;
yaml_parser_t parser;
yoml_t *yoml;
if ((fp = fopen(fn, "rb")) == NULL) {
fprintf(stderr, "could not open configuration file:%s:%s\n", fn, strerror(errno));
return NULL;
}
yaml_parser_initialize(&parser);
yaml_parser_set_input_file(&parser, fp);
yoml = yoml_parse_document(&parser, NULL, fn);
if (yoml == NULL)
fprintf(stderr, "failed to parse configuration file:%s:line %d:%s\n", fn, (int)parser.problem_mark.line, parser.problem);
yaml_parser_delete(&parser);
fclose(fp);
return yoml;
}
static void notify_all_threads(void)
{
unsigned i;
for (i = 0; i != conf.num_threads; ++i) {
h2o_multithread_message_t *message = h2o_mem_alloc(sizeof(*message));
*message = (h2o_multithread_message_t){};
h2o_multithread_send_message(&conf.threads[i].server_notifications, message);
}
}
static void on_sigterm(int signo)
{
conf.shutdown_requested = 1;
notify_all_threads();
}
#ifdef __linux__
static int popen_annotate_backtrace_symbols(void)
{
char *cmd_fullpath = get_cmd_path("share/h2o/annotate-backtrace-symbols"), *argv[] = {cmd_fullpath, NULL};
int pipefds[2];
/* create pipe */
if (pipe(pipefds) != 0) {
perror("pipe failed");
return -1;
}
if (fcntl(pipefds[1], F_SETFD, FD_CLOEXEC) == -1) {
perror("failed to set FD_CLOEXEC on pipefds[1]");
return -1;
}
/* spawn the logger */
int mapped_fds[] = {
pipefds[0], 0, /* output of the pipe is connected to STDIN of the spawned process */
pipefds[0], -1, /* close pipefds[0] before exec */
2, 1, /* STDOUT of the spawned process in connected to STDERR of h2o */
-1
};
if (h2o_spawnp(cmd_fullpath, argv, mapped_fds) == -1) {
/* silently ignore error */
close(pipefds[0]);
close(pipefds[1]);
return -1;
}
/* do the rest, and return the fd */
close(pipefds[0]);
return pipefds[1];
}
static int backtrace_symbols_to_fd = -1;
static void on_sigfatal(int signo)
{
fprintf(stderr, "received fatal signal %d; backtrace follows\n", signo);
h2o_set_signal_handler(signo, SIG_DFL);
void *frames[128];
int framecnt = backtrace(frames, sizeof(frames) / sizeof(frames[0]));
backtrace_symbols_fd(frames, framecnt, backtrace_symbols_to_fd);
raise(signo);
}
#endif
static void setup_signal_handlers(void)
{
h2o_set_signal_handler(SIGTERM, on_sigterm);
h2o_set_signal_handler(SIGPIPE, SIG_IGN);
#ifdef __linux__
if ((backtrace_symbols_to_fd = popen_annotate_backtrace_symbols()) == -1)
backtrace_symbols_to_fd = 2;
h2o_set_signal_handler(SIGABRT, on_sigfatal);
h2o_set_signal_handler(SIGBUS, on_sigfatal);
h2o_set_signal_handler(SIGFPE, on_sigfatal);
h2o_set_signal_handler(SIGILL, on_sigfatal);
h2o_set_signal_handler(SIGSEGV, on_sigfatal);
#endif
}
static int num_connections(int delta)
{
return __sync_fetch_and_add(&conf.state._num_connections, delta);
}
static void on_socketclose(void *data)
{
int prev_num_connections = num_connections(-1);
if (prev_num_connections == conf.max_connections) {
/* ready to accept new connections. wake up all the threads! */
notify_all_threads();
}
}
static void on_accept(h2o_socket_t *listener, int status)
{
struct listener_ctx_t *ctx = listener->data;
size_t num_accepts = conf.max_connections / 16 / conf.num_threads;
if (num_accepts < 8)
num_accepts = 8;
if (status == -1) {
return;
}
do {
h2o_socket_t *sock;
if (num_connections(0) >= conf.max_connections) {
/* The accepting socket is disactivated before entering the next in `run_loop`.
* Note: it is possible that the server would accept at most `max_connections + num_threads` connections, since the
* server does not check if the number of connections has exceeded _after_ epoll notifies of a new connection _but_
* _before_ calling `accept`. In other words t/40max-connections.t may fail.
*/
break;
}
if ((sock = h2o_evloop_socket_accept(listener)) == NULL) {
break;
}
num_connections(1);
sock->on_close.cb = on_socketclose;
sock->on_close.data = ctx->ctx;
if (ctx->ssl_ctx != NULL)
h2o_accept_ssl(ctx->ctx, ctx->hosts, sock, ctx->ssl_ctx);
else
h2o_http1_accept(ctx->ctx, ctx->hosts, sock);
} while (--num_accepts != 0);
}
static void update_listener_state(struct listener_ctx_t *listeners)
{
size_t i;
if (num_connections(0) < conf.max_connections) {
for (i = 0; i != conf.num_listeners; ++i) {
if (!h2o_socket_is_reading(listeners[i].sock))
h2o_socket_read_start(listeners[i].sock, on_accept);
}
} else {
for (i = 0; i != conf.num_listeners; ++i) {
if (h2o_socket_is_reading(listeners[i].sock))
h2o_socket_read_stop(listeners[i].sock);
}
}
}
static void on_server_notification(h2o_multithread_receiver_t *receiver, h2o_linklist_t *messages)
{
/* the notification is used only for exitting h2o_evloop_run; actual changes are done in the main loop of run_loop */
while (!h2o_linklist_is_empty(messages)) {
h2o_multithread_message_t *message = H2O_STRUCT_FROM_MEMBER(h2o_multithread_message_t, link, messages->next);
h2o_linklist_unlink(&message->link);
free(message);
}
}
H2O_NORETURN static void *run_loop(void *_thread_index)
{
size_t thread_index = (size_t)_thread_index;
struct listener_ctx_t *listeners = alloca(sizeof(*listeners) * conf.num_listeners);
size_t i;
h2o_context_init(&conf.threads[thread_index].ctx, h2o_evloop_create(), &conf.globalconf);
h2o_multithread_register_receiver(conf.threads[thread_index].ctx.queue, &conf.threads[thread_index].server_notifications,
on_server_notification);
conf.threads[thread_index].tid = pthread_self();
/* setup listeners */
for (i = 0; i != conf.num_listeners; ++i) {
struct listener_config_t *listener_config = conf.listeners[i];
int fd;
/* dup the listener fd for other threads than the main thread */
if (thread_index == 0) {
fd = listener_config->fd;
} else {
if ((fd = dup(listener_config->fd)) == -1) {
perror("failed to dup listening socket");
abort();
}
set_cloexec(fd);
}
listeners[i] = (struct listener_ctx_t){
&conf.threads[thread_index].ctx, /* ctx */
listener_config->hosts, /* hosts */
listener_config->ssl.size != 0 ? listener_config->ssl.entries[0].ctx : NULL, /* ssl_ctx */
h2o_evloop_socket_create(conf.threads[thread_index].ctx.loop, fd, (struct sockaddr *)&listener_config->addr,
listener_config->addrlen, H2O_SOCKET_FLAG_DONT_READ) /* sock */
};
listeners[i].sock->data = listeners + i;
}
/* and start listening */
update_listener_state(listeners);
/* the main loop */
while (1) {
if (conf.shutdown_requested)
break;
update_listener_state(listeners);
/* run the loop once */
h2o_evloop_run(conf.threads[thread_index].ctx.loop);
}
if (thread_index == 0)
fprintf(stderr, "received SIGTERM, gracefully shutting down\n");
/* shutdown requested, close the listeners, notify the protocol handlers */
for (i = 0; i != conf.num_listeners; ++i) {
h2o_socket_close(listeners[i].sock);
listeners[i].sock = NULL;
}
h2o_context_request_shutdown(&conf.threads[thread_index].ctx);
/* wait until all the connection gets closed */
while (num_connections(0) != 0)
h2o_evloop_run(conf.threads[thread_index].ctx.loop);
/* the process that detects num_connections becoming zero performs the last cleanup */
if (conf.pid_file != NULL)
unlink(conf.pid_file);
_exit(0);
}
static char **build_server_starter_argv(const char *h2o_cmd, const char *config_file)
{
H2O_VECTOR(char *)args = {};
size_t i;
h2o_vector_reserve(NULL, (void *)&args, sizeof(args.entries[0]), 1);
args.entries[args.size++] = get_cmd_path("share/h2o/start_server");
/* error-log and pid-file are the directives that are handled by server-starter */
if (conf.pid_file != NULL) {
h2o_vector_reserve(NULL, (void *)&args, sizeof(args.entries[0]), args.size + 1);
args.entries[args.size++] =
h2o_concat(NULL, h2o_iovec_init(H2O_STRLIT("--pid-file=")), h2o_iovec_init(conf.pid_file, strlen(conf.pid_file))).base;
}
if (conf.error_log != NULL) {
h2o_vector_reserve(NULL, (void *)&args, sizeof(args.entries[0]), args.size + 1);
args.entries[args.size++] = h2o_concat(NULL, h2o_iovec_init(H2O_STRLIT("--log-file=")),
h2o_iovec_init(conf.error_log, strlen(conf.error_log))).base;
}
switch (conf.run_mode) {
case RUN_MODE_DAEMON:
h2o_vector_reserve(NULL, (void *)&args, sizeof(args.entries[0]), args.size + 1);
args.entries[args.size++] = "--daemonize";
break;
default:
break;
}
for (i = 0; i != conf.num_listeners; ++i) {
char *newarg;
switch (conf.listeners[i]->addr.ss_family) {
default: {
char host[NI_MAXHOST], serv[NI_MAXSERV];
int err;
if ((err = getnameinfo((void *)&conf.listeners[i]->addr, conf.listeners[i]->addrlen, host, sizeof(host), serv,
sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
fprintf(stderr, "failed to stringify the address of %zu-th listen directive:%s\n", i, gai_strerror(err));
exit(EX_OSERR);
}
newarg = h2o_mem_alloc(sizeof("--port=[]:") + strlen(host) + strlen(serv));
if (strchr(host, ':') != NULL) {
sprintf(newarg, "--port=[%s]:%s", host, serv);
} else {
sprintf(newarg, "--port=%s:%s", host, serv);
}
} break;
case AF_UNIX: {
struct sockaddr_un *sun = (void *)&conf.listeners[i]->addr;
newarg = h2o_mem_alloc(sizeof("--path=") + strlen(sun->sun_path));
sprintf(newarg, "--path=%s", sun->sun_path);
} break;
}
h2o_vector_reserve(NULL, (void *)&args, sizeof(args.entries[0]), args.size + 1);
args.entries[args.size++] = newarg;
}
h2o_vector_reserve(NULL, (void *)&args, sizeof(args.entries[0]), args.size + 5);
args.entries[args.size++] = "--";
args.entries[args.size++] = (char *)h2o_cmd;
args.entries[args.size++] = "-c";
args.entries[args.size++] = (char *)config_file;
args.entries[args.size] = NULL;
return args.entries;
}
static int run_using_server_starter(const char *h2o_cmd, const char *config_file)
{
char **args = build_server_starter_argv(h2o_cmd, config_file);
setenv("H2O_VIA_MASTER", "", 1);
execvp(args[0], args);
fprintf(stderr, "failed to spawn %s:%s\n", args[0], strerror(errno));
return EX_CONFIG;
}
static void setup_configurators(void)
{
h2o_config_init(&conf.globalconf);
{
h2o_configurator_t *c = h2o_configurator_create(&conf.globalconf, sizeof(*c));
c->enter = on_config_listen_enter;
c->exit = on_config_listen_exit;
h2o_configurator_define_command(c, "listen", H2O_CONFIGURATOR_FLAG_GLOBAL | H2O_CONFIGURATOR_FLAG_HOST, on_config_listen);
}
{
h2o_configurator_t *c = h2o_configurator_create(&conf.globalconf, sizeof(*c));
h2o_configurator_define_command(c, "user", H2O_CONFIGURATOR_FLAG_GLOBAL | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR,
on_config_user);
h2o_configurator_define_command(c, "pid-file", H2O_CONFIGURATOR_FLAG_GLOBAL | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR,
on_config_pid_file);
h2o_configurator_define_command(c, "error-log", H2O_CONFIGURATOR_FLAG_GLOBAL | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR,
on_config_error_log);
h2o_configurator_define_command(c, "max-connections", H2O_CONFIGURATOR_FLAG_GLOBAL, on_config_max_connections);
h2o_configurator_define_command(c, "num-threads", H2O_CONFIGURATOR_FLAG_GLOBAL, on_config_num_threads);
h2o_configurator_define_command(c, "num-name-resolution-threads", H2O_CONFIGURATOR_FLAG_GLOBAL,
on_config_num_name_resolution_threads);
h2o_configurator_define_command(c, "tcp-fastopen", H2O_CONFIGURATOR_FLAG_GLOBAL, on_config_tcp_fastopen);
}
h2o_access_log_register_configurator(&conf.globalconf);
h2o_expires_register_configurator(&conf.globalconf);
h2o_fastcgi_register_configurator(&conf.globalconf);
h2o_file_register_configurator(&conf.globalconf);
h2o_headers_register_configurator(&conf.globalconf);
h2o_proxy_register_configurator(&conf.globalconf);
h2o_reproxy_register_configurator(&conf.globalconf);
h2o_redirect_register_configurator(&conf.globalconf);
}
int main(int argc, char **argv)
{
const char *cmd = argv[0], *opt_config_file = "h2o.conf";
int error_log_fd = -1;
conf.num_threads = h2o_numproc();
conf.tfo_queues = H2O_DEFAULT_LENGTH_TCP_FASTOPEN_QUEUE;
h2o_hostinfo_max_threads = H2O_DEFAULT_NUM_NAME_RESOLUTION_THREADS;
setup_configurators();
{ /* parse options */
int ch;
static struct option longopts[] = {{"conf", required_argument, NULL, 'c'},
{"mode", required_argument, NULL, 'm'},
{"test", no_argument, NULL, 't'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}};
while ((ch = getopt_long(argc, argv, "c:m:tvh", longopts, NULL)) != -1) {
switch (ch) {
case 'c':
opt_config_file = optarg;
break;
case 'm':
if (strcmp(optarg, "worker") == 0) {
conf.run_mode = RUN_MODE_WORKER;
} else if (strcmp(optarg, "master") == 0) {
conf.run_mode = RUN_MODE_MASTER;
} else if (strcmp(optarg, "daemon") == 0) {
conf.run_mode = RUN_MODE_DAEMON;
} else if (strcmp(optarg, "test") == 0) {
conf.run_mode = RUN_MODE_TEST;
} else {
fprintf(stderr, "unknown mode:%s\n", optarg);
}
switch (conf.run_mode) {
case RUN_MODE_MASTER:
case RUN_MODE_DAEMON:
if (getenv("SERVER_STARTER_PORT") != NULL) {
fprintf(stderr, "refusing to start in `%s` mode, environment variable SERVER_STARTER_PORT is already set\n",
optarg);
exit(EX_SOFTWARE);
}
break;
default:
break;
}
break;
case 't':
conf.run_mode = RUN_MODE_TEST;
break;
case 'v':
printf("h2o version " H2O_VERSION "\n");
exit(0);
case 'h':
printf("h2o version " H2O_VERSION "\n"
"\n"
"Usage:\n"
" h2o [options]\n"
"\n"
"Options:\n"
" -c, --conf FILE configuration file (default: h2o.conf)\n"
" -m, --mode <mode> specifies one of the following mode\n"
" - worker: invoked process handles incoming connections\n"
" (default)\n"
" - daemon: spawns a master process and exits. `error-log`\n"
" must be configured when using this mode, as all\n"
" the errors are logged to the file instead of\n"
" being emitted to STDERR\n"
" - master: invoked process becomes a master process (using\n"
" the `share/h2o/start_server` command) and spawns\n"
" a worker process for handling incoming\n"
" connections. Users may send SIGHUP to the master\n"
" process to reconfigure or upgrade the server.\n"
" - test: tests the configuration and exits\n"
" -t, --test synonym of `--mode=test`\n"
" -v, --version prints the version number\n"
" -h, --help print this help\n"
"\n"
"Please refer to the documentation under `share/doc/h2o` (or available online at\n"
"http://h2o.examp1e.net/) for how to configure the server.\n"
"\n");
exit(0);
break;
case ':':
case '?':
exit(EX_CONFIG);
default:
assert(0);
break;
}
}
argc -= optind;
argv += optind;
}
/* setup conf.server_starter */
if ((conf.server_starter.num_fds = h2o_server_starter_get_fds(&conf.server_starter.fds)) == SIZE_MAX)
exit(EX_CONFIG);
if (conf.server_starter.fds != 0) {
size_t i;
for (i = 0; i != conf.server_starter.num_fds; ++i)
set_cloexec(conf.server_starter.fds[i]);
conf.server_starter.bound_fd_map = alloca(conf.server_starter.num_fds);
}
{ /* configure */
yoml_t *yoml;
if ((yoml = load_config(opt_config_file)) == NULL)
exit(EX_CONFIG);
if (h2o_configurator_apply(&conf.globalconf, yoml) != 0)
exit(EX_CONFIG);
yoml_free(yoml);
}
/* check if all the fds passed in by server::starter were bound */
if (conf.server_starter.fds != NULL) {
size_t i;
int all_were_bound = 1;
for (i = 0; i != conf.server_starter.num_fds; ++i) {
if (!conf.server_starter.bound_fd_map[i]) {
fprintf(stderr, "no configuration found for fd:%d passed in by $SERVER_STARTER_PORT\n", conf.server_starter.fds[i]);
all_were_bound = 0;
}
}
if (!all_were_bound) {
fprintf(stderr, "note: $SERVER_STARTER_PORT was \"%s\"\n", getenv("SERVER_STARTER_PORT"));
return EX_CONFIG;
}
}
unsetenv("SERVER_STARTER_PORT");
/* handle run_mode == MASTER|TEST */
switch (conf.run_mode) {
case RUN_MODE_WORKER:
break;
case RUN_MODE_DAEMON:
if (conf.error_log == NULL) {
fprintf(stderr, "to run in `daemon` mode, `error-log` must be specified in the configuration file\n");
return EX_CONFIG;
}
return run_using_server_starter(cmd, opt_config_file);
case RUN_MODE_MASTER:
return run_using_server_starter(cmd, opt_config_file);
case RUN_MODE_TEST:
printf("configuration OK\n");
return 0;
}
if (getenv("H2O_VIA_MASTER") != NULL) {
/* pid_file and error_log are the directives that are handled by the master process (invoking start_server) */
conf.pid_file = NULL;
conf.error_log = NULL;
}
{ /* raise RLIMIT_NOFILE */
struct rlimit limit;
if (getrlimit(RLIMIT_NOFILE, &limit) == 0) {
limit.rlim_cur = limit.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &limit) == 0
#ifdef __APPLE__
|| (limit.rlim_cur = OPEN_MAX, setrlimit(RLIMIT_NOFILE, &limit)) == 0
#endif
) {
fprintf(stderr, "[INFO] raised RLIMIT_NOFILE to %d\n", (int)limit.rlim_cur);
}
}
}
setup_signal_handlers();
/* open the log file to redirect STDIN/STDERR to, before calling setuid */
if (conf.error_log != NULL) {
if ((error_log_fd = h2o_access_log_open_log(conf.error_log)) == -1)
return EX_CONFIG;
}
/* setuid */
if (conf.running_user != NULL) {
if (h2o_setuidgid(conf.running_user) != 0) {
fprintf(stderr, "failed to change the running user (are you sure you are running as root?)\n");
return EX_OSERR;
}
} else {
if (getuid() == 0) {
if (setup_running_user("nobody") == 0) {
fprintf(stderr, "cowardly switching to nobody; please use the `user` directive to set the running user\n");
} else {
fprintf(stderr, "refusing to run as root (and failed to switch to `nobody`); you can use the `user` directive to "
"set the running user\n");
return EX_CONFIG;
}
}
}
/* pid file must be written after setuid, since we need to remove it */
if (conf.pid_file != NULL) {
FILE *fp = fopen(conf.pid_file, "wt");
if (fp == NULL) {
fprintf(stderr, "failed to open pid file:%s:%s\n", conf.pid_file, strerror(errno));
return EX_OSERR;
}
fprintf(fp, "%d\n", (int)getpid());
fclose(fp);
}
/* all setup should be complete by now */
/* replace STDIN to an closed pipe */
{
int fds[2];
if (pipe(fds) != 0) {
perror("pipe failed");
return EX_OSERR;
}
close(fds[1]);
dup2(fds[0], 0);
close(fds[0]);
}
/* redirect STDOUT and STDERR to error_log (if specified) */
if (error_log_fd != -1) {
if (dup2(error_log_fd, 1) == -1 || dup2(error_log_fd, 2) == -1) {
perror("dup(2) failed");
return EX_OSERR;
}
close(error_log_fd);
error_log_fd = -1;
}
fprintf(stderr, "h2o server (pid:%d) is ready to serve requests\n", (int)getpid());
assert(conf.num_threads != 0);
/* start the threads */
conf.threads = alloca(sizeof(conf.threads[0]) * conf.num_threads);
size_t i;
for (i = 1; i != conf.num_threads; ++i) {
pthread_t tid;
pthread_create(&tid, NULL, run_loop, (void *)i);
}
/* this thread becomes the first thread */
run_loop((void *)0);
/* notreached */
return 0;
}
| 1 | 10,649 | Even if `pthread_create()` for `ocsp_updater_thread()` fails, `h2o` can continue to serve. But I'm a little worried whether `h2o` should continue to serve in this case. How about you? | h2o-h2o | c |
@@ -37,6 +37,15 @@ import { __, _x, sprintf } from '@wordpress/i18n';
import { Component, Fragment } from '@wordpress/element';
import { addFilter, removeFilter } from '@wordpress/hooks';
+/**
+ * Internal dependencies
+ */
+import { isValidAccountID, isValidContainerID } from './util';
+
+const ACCOUNT_CREATE = 'account_create';
+const ACCOUNT_CHOOSE = 'account_choose';
+const CONTAINER_CREATE = 'container_create';
+
class TagmanagerSetup extends Component {
constructor( props ) {
super( props ); | 1 | /**
* TagmanagerSetup component.
*
* Site Kit by Google, 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.
*/
/**
* External dependencies
*/
import Button from 'GoogleComponents/button';
import Link from 'GoogleComponents/link';
import Switch from 'GoogleComponents/switch';
import data, { TYPE_MODULES } from 'GoogleComponents/data';
import ProgressBar from 'GoogleComponents/progress-bar';
import { Select, Option } from 'SiteKitCore/material-components';
import SvgIcon from 'GoogleUtil/svg-icon';
import PropTypes from 'prop-types';
import { getExistingTag, toggleConfirmModuleSettings } from 'GoogleUtil';
import { get } from 'lodash';
/**
* WordPress dependencies
*/
import { __, _x, sprintf } from '@wordpress/i18n';
import { Component, Fragment } from '@wordpress/element';
import { addFilter, removeFilter } from '@wordpress/hooks';
class TagmanagerSetup extends Component {
constructor( props ) {
super( props );
const { settings } = global.googlesitekit.modules.tagmanager;
const usageContext = global.googlesitekit.admin.ampMode === 'primary' ? 'amp' : 'web';
const containerKey = usageContext === 'amp' ? 'ampContainerID' : 'containerID';
this.state = {
isLoading: true,
accounts: [],
containers: [],
errorCode: false,
errorMsg: '',
refetch: false,
selectedAccount: settings.accountID,
selectedContainer: settings[ containerKey ],
containersLoading: false,
usageContext,
containerKey,
hasExistingTag: false,
useSnippet: settings.useSnippet,
};
this.handleSubmit = this.handleSubmit.bind( this );
this.renderAccountDropdownForm = this.renderAccountDropdownForm.bind( this );
this.handleAccountChange = this.handleAccountChange.bind( this );
this.handleContainerChange = this.handleContainerChange.bind( this );
this.refetchAccount = this.refetchAccount.bind( this );
}
async componentDidMount() {
const {
isOpen,
onSettingsPage,
} = this.props;
this._isMounted = true;
// If on settings page, only run the rest if the module is "open".
if ( onSettingsPage && ! isOpen ) {
return;
}
await this.loadAccountsContainers();
// Handle save hook from the settings page.
addFilter( 'googlekit.SettingsConfirmed',
'googlekit.TagmanagerSettingsConfirmed',
( chain, module ) => {
if ( 'tagmanager' !== module.replace( '-module', '' ) ) {
return chain;
}
const { isEditing } = this.props;
if ( isEditing ) {
return this.handleSubmit();
}
} );
this.toggleConfirmChangesButton();
}
componentDidUpdate() {
const { refetch } = this.state;
if ( refetch ) {
this.requestTagManagerAccounts();
}
this.toggleConfirmChangesButton();
}
componentWillUnmount() {
this._isMounted = false;
removeFilter( 'googlekit.SettingsConfirmed', 'googlekit.TagmanagerSettingsConfirmed' );
}
/**
* Toggle confirm changes button disable/enable depending on the changed settings.
*/
toggleConfirmChangesButton() {
if ( ! this.props.isEditing ) {
return;
}
const { containerKey, errorCode } = this.state;
let settingsMapping = {
selectedContainer: containerKey,
selectedAccount: 'selectedAccount',
useSnippet: 'useSnippet',
};
// Disable the confirmation button if user lacks necessary permission on the existing tag.
if ( 'tag_manager_existing_tag_permission' === errorCode ) {
settingsMapping = {};
}
toggleConfirmModuleSettings( 'tagmanager', settingsMapping, this.state );
}
async loadAccountsContainers() {
const existingContainerID = await getExistingTag( 'tagmanager' );
if ( existingContainerID ) {
// Verify the user has access to existing tag if found.
try {
const { account, container } = await data.get( TYPE_MODULES, 'tagmanager', 'tag-permission', { tag: existingContainerID } );
// If the user has access, they may continue but must use the found account+container.
this.setState(
{
isLoading: false,
selectedAccount: account.accountId, // Capitalization rule exception: `accountId` is a property of an API returned value.
selectedContainer: container.publicId, // Capitalization rule exception: `publicId` is a property of an API returned value.
accounts: [ account ],
containers: [ container ],
hasExistingTag: true,
}
);
} catch ( err ) {
this.setState(
{
isLoading: false,
errorCode: err.code,
errorMsg: err.message,
errorReason: err.data && err.data.reason ? err.data.reason : false,
hasExistingTag: !! existingContainerID,
}
);
}
} else {
// Only load accounts if there is no existing tag.
await this.requestTagManagerAccounts();
}
}
/**
* Request Tag Manager accounts.
*/
async requestTagManagerAccounts() {
try {
const {
selectedAccount,
usageContext,
} = this.state;
let { selectedContainer } = this.state;
const queryArgs = {
accountID: selectedAccount,
usageContext,
};
let errorCode = false;
let errorMsg = '';
const { accounts, containers } = await data.get( TYPE_MODULES, 'tagmanager', 'accounts-containers', queryArgs );
if ( ! selectedAccount && 0 === accounts.length ) {
errorCode = 'accountEmpty';
errorMsg = __(
'We didn’t find an associated Google Tag Manager account, would you like to set it up now? If you’ve just set up an account please re-fetch your account to sync it with Site Kit.',
'google-site-kit'
);
}
// Verify if user has access to the selected account.
if ( selectedAccount && ! accounts.find( ( account ) => account.accountId === selectedAccount ) ) { // Capitalization rule exception: `accountId` is a property of an API returned value.
data.invalidateCacheGroup( TYPE_MODULES, 'tagmanager', 'accounts-containers' );
errorCode = 'insufficientPermissions';
errorMsg = __( 'You currently don\'t have access to this Google Tag Manager account. You can either request access from your team, or remove this Google Tag Manager snippet and connect to a different account.', 'google-site-kit' );
}
// If the selectedContainer is not in the list of containers, clear it.
if ( selectedContainer && ! containers.find( ( container ) => container.publicId === selectedContainer ) ) {
selectedContainer = null;
}
if ( this._isMounted ) {
this.setState( {
isLoading: false,
accounts,
selectedAccount: selectedAccount || get( containers, [ 0, 'accountId' ] ), // Capitalization rule exception: `accountId` is a property of an API returned value.
containers,
selectedContainer: selectedContainer || get( containers, [ 0, 'publicId' ] ), // Capitalization rule exception: `publicId` is a property of an API returned value.
refetch: false,
errorCode,
errorMsg,
} );
}
} catch ( err ) {
if ( this._isMounted ) {
this.setState( {
isLoading: false,
errorCode: err.code,
errorMsg: err.message,
refetch: false,
} );
}
}
}
/**
* Request Tag Manager accounts.
*
* @param {string} selectedAccount The account ID to get containers from.
*/
async requestTagManagerContainers( selectedAccount ) {
try {
const queryArgs = {
accountID: selectedAccount,
usageContext: this.state.usageContext,
};
const containers = await data.get( TYPE_MODULES, 'tagmanager', 'containers', queryArgs );
if ( this._isMounted ) {
this.setState( {
containersLoading: false,
containers,
selectedContainer: get( containers, [ 0, 'publicId' ] ), // Capitalization rule exception: `publicId` is a property of an API returned value.
errorCode: false,
} );
}
} catch ( err ) {
if ( this._isMounted ) {
this.setState( {
errorCode: err.code,
errorMsg: err.message,
} );
}
}
}
async handleSubmit() {
const {
containerKey,
hasExistingTag,
selectedAccount,
selectedContainer,
usageContext,
useSnippet,
} = this.state;
const { finishSetup } = this.props;
try {
const dataParams = {
accountID: selectedAccount,
[ containerKey ]: selectedContainer,
usageContext,
useSnippet: hasExistingTag ? false : useSnippet,
};
const savedSettings = await data.set( TYPE_MODULES, 'tagmanager', 'settings', dataParams );
if ( finishSetup ) {
finishSetup();
}
global.googlesitekit.modules.tagmanager.settings = savedSettings;
if ( this._isMounted ) {
this.setState( {
isSaving: false,
} );
}
} catch ( err ) {
if ( this._isMounted ) {
this.setState( {
isLoading: false,
errorCode: err.code,
errorMsg: err.message,
} );
}
// Catches error in handleButtonAction from <SettingsModules> component.
return new Promise.reject( err );
}
}
static createNewAccount( e ) {
e.preventDefault();
global.open( 'https://marketingplatform.google.com/about/tag-manager/', '_blank' );
}
handleAccountChange( index, item ) {
const { selectedAccount } = this.state;
const selectValue = item.getAttribute( 'data-value' );
if ( selectValue === selectedAccount ) {
return;
}
if ( this._isMounted ) {
this.setState( {
containersLoading: true,
selectedAccount: selectValue,
} );
}
this.requestTagManagerContainers( selectValue );
}
handleContainerChange( index, item ) {
const { selectedContainer } = this.state;
const selectValue = item.getAttribute( 'data-value' );
if ( selectValue === selectedContainer ) {
return;
}
if ( this._isMounted ) {
this.setState( {
selectedContainer: selectValue,
} );
}
}
refetchAccount( e ) {
e.preventDefault();
if ( this._isMounted ) {
this.setState( {
isLoading: true,
refetch: true,
errorCode: false,
} );
}
}
renderSettingsInfo() {
const { settings } = global.googlesitekit.modules.tagmanager;
const {
hasExistingTag,
containerKey,
isLoading,
} = this.state;
const {
accountID,
useSnippet,
} = settings;
if ( isLoading ) {
return <ProgressBar />;
}
return (
<Fragment>
<div className="googlesitekit-settings-module__meta-items">
<div className="googlesitekit-settings-module__meta-item">
<p className="googlesitekit-settings-module__meta-item-type">
{ __( 'Account', 'google-site-kit' ) }
</p>
<h5 className="googlesitekit-settings-module__meta-item-data">
{ accountID || false }
</h5>
</div>
<div className="googlesitekit-settings-module__meta-item">
<p className="googlesitekit-settings-module__meta-item-type">
{ __( 'Container ID', 'google-site-kit' ) }
</p>
<h5 className="googlesitekit-settings-module__meta-item-data">
{ settings[ containerKey ] || false }
</h5>
</div>
</div>
<div className="googlesitekit-settings-module__meta-items">
<div className="googlesitekit-settings-module__meta-item">
<p className="googlesitekit-settings-module__meta-item-type">
{ __( 'Tag Manager Code Snippet', 'google-site-kit' ) }
</p>
<h5 className="googlesitekit-settings-module__meta-item-data">
{ useSnippet && __( 'Snippet is inserted', 'google-site-kit' ) }
{ ! useSnippet && __( 'Snippet is not inserted', 'google-site-kit' ) }
</h5>
{ hasExistingTag &&
<p>{ __( 'Placing two tags at the same time is not recommended.', 'google-site-kit' ) }</p>
}
</div>
</div>
</Fragment>
);
}
renderAccountDropdownForm() {
const {
accounts,
selectedAccount,
containers,
selectedContainer,
hasExistingTag,
isLoading,
containersLoading,
errorCode,
useSnippet,
} = this.state;
const {
onSettingsPage,
} = this.props;
if ( isLoading ) {
return <ProgressBar />;
}
// If the user doesn't have the necessary permissions for an existing tag
// don't render the form as we may not have enough data to properly display dropdowns.
// The user is blocked from completing setup.
if ( 'tag_manager_existing_tag_permission' === errorCode ) {
return null;
}
if ( 'accountEmpty' === errorCode ) {
return (
<Fragment>
<div className="googlesitekit-setup-module__action">
<Button onClick={ TagmanagerSetup.createNewAccount }>{ __( 'Create an account', 'google-site-kit' ) }</Button>
<div className="googlesitekit-setup-module__sub-action">
<Link onClick={ this.refetchAccount }>{ __( 'Re-fetch My Account', 'google-site-kit' ) }</Link>
</div>
</div>
</Fragment>
);
}
return (
<Fragment>
{ hasExistingTag && (
<p>
{ sprintf(
// translators: %s: the existing container ID.
__( 'An existing tag was found on your site (%s). If you later decide to replace this tag, Site Kit can place the new tag for you. Make sure you remove the old tag first.', 'google-site-kit' ),
selectedContainer
) }
</p>
) }
{ ! hasExistingTag && (
<p>{ __( 'Please select your Tag Manager account and container below, the snippet will be inserted automatically into your site.', 'google-site-kit' ) }</p>
) }
<div className="googlesitekit-setup-module__inputs">
<Select
enhanced
name="accounts"
label={ __( 'Account', 'google-site-kit' ) }
value={ selectedAccount }
disabled={ hasExistingTag }
onEnhancedChange={ this.handleAccountChange }
outlined
>
{ accounts.map( ( account ) => {
return (
<Option
key={ account.accountId /* Capitalization rule exception: `accountId` is a property of an API returned value. */ }
value={ account.accountId /* Capitalization rule exception: `accountId` is a property of an API returned value. */ }>
{ account.name }
</Option>
);
} ) }
</Select>
{ containersLoading ? ( <ProgressBar small /> ) : (
<Select
enhanced
name="containers"
label={ __( 'Container', 'google-site-kit' ) }
value={ selectedContainer }
disabled={ hasExistingTag }
onEnhancedChange={ this.handleContainerChange }
outlined
>
{ containers.concat( {
name: __( 'Set up a new container', 'google-site-kit' ),
publicId: 0,
} ).map( ( { name, publicId }, i ) =>
<Option
key={ i }
value={ publicId /* Capitalization rule exception: `publicId` is a property of an API returned value. */ }>
{ name }
</Option>
) }
</Select>
) }
</div>
{ onSettingsPage &&
<Fragment>
{ hasExistingTag &&
<p>{ __( 'Placing two tags at the same time is not recommended.', 'google-site-kit' ) }</p>
}
<Switch
id="tagmanagerUseSnippet"
onClick={ () => this.setState( { useSnippet: ! useSnippet } ) }
name="useSnippet"
checked={ useSnippet }
label={ __( 'Let Site Kit place code on your site', 'google-site-kit' ) }
hideLabel={ false }
/>
<p>
{ useSnippet ?
__( 'Site Kit will add the code automatically', 'google-site-kit' ) :
__( 'Site Kit will not add the code to your site', 'google-site-kit' )
}
</p>
</Fragment>
}
{ /*Render the continue and skip button.*/ }
{
! onSettingsPage &&
<div className="googlesitekit-setup-module__action">
<Button onClick={ this.handleSubmit }>{ __( 'Confirm & Continue', 'google-site-kit' ) }</Button>
</div>
}
</Fragment>
);
}
/**
* Render Error or Notice format depending on the errorCode.
* @return {WPElement|null} Error message if any, or null.
*/
renderErrorOrNotice() {
const {
errorCode,
errorMsg,
} = this.state;
const {
onSettingsPage,
} = this.props;
if ( 0 === errorMsg.length ) {
return null;
}
const showErrorFormat = onSettingsPage && 'insufficientPermissions' === errorCode ? false : true; // default error format.
return (
<div className={ showErrorFormat ? 'googlesitekit-error-text' : '' }>
<p>{
showErrorFormat ?
/* translators: %s: Error message */
sprintf( __( 'Error: %s', 'google-site-kit' ), errorMsg ) :
errorMsg
}</p>
</div>
);
}
render() {
const {
onSettingsPage,
isEditing,
} = this.props;
return (
<div className="googlesitekit-setup-module googlesitekit-setup-module--tag-manager">
{
! onSettingsPage &&
<Fragment>
<div className="googlesitekit-setup-module__logo">
<SvgIcon id="tagmanager" width="33" height="33" />
</div>
<h2 className="
googlesitekit-heading-3
googlesitekit-setup-module__title
">
{ _x( 'Tag Manager', 'Service name', 'google-site-kit' ) }
</h2>
</Fragment>
}
{ this.renderErrorOrNotice() }
{ isEditing && this.renderAccountDropdownForm() }
{ ! isEditing && this.renderSettingsInfo() }
</div>
);
}
}
TagmanagerSetup.propTypes = {
onSettingsPage: PropTypes.bool,
finishSetup: PropTypes.func,
isEditing: PropTypes.bool,
};
TagmanagerSetup.defaultProps = {
onSettingsPage: true,
isEditing: false,
};
export default TagmanagerSetup;
| 1 | 26,177 | I like introduction of these constants for account/container creation, but the `ACCOUNT_CHOOSE` one isn't needed I think. This should instead be an "empty" value (either `''` or `0`), to indicate more clearly that this field is not filled. It should be the same for choosing a container. | google-site-kit-wp | js |
@@ -101,3 +101,16 @@ Blockly.scratchBlocksUtils.isShadowArgumentReporter = function(block) {
return (block.isShadow() && (block.type == 'argument_reporter_boolean' ||
block.type == 'argument_reporter_string_number'));
};
+
+/**
+ * Compare strings with natural number sorting.
+ * @param {string} str1 First input.
+ * @param {string} str2 Second input.
+ * @return {number} -1, 0, or 1 to signify greater than, equality, or less than.
+ */
+Blockly.scratchBlocksUtils.compareStrings = function(str1, str2) {
+ return str1.localeCompare(str2, undefined, {
+ sensitivity: 'base',
+ numeric: true
+ });
+}; | 1 | /**
* @license
* Visual Blocks Editor
*
* Copyright 2018 Google Inc.
* https://developers.google.com/blockly/
*
* 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.
*/
/**
* @fileoverview Utility methods for Scratch Blocks but not Blockly.
* @author [email protected] (Rachel Fenichel)
*/
'use strict';
/**
* @name Blockly.scratchBlocksUtils
* @namespace
**/
goog.provide('Blockly.scratchBlocksUtils');
/**
* Measure some text using a canvas in-memory.
* Does not exist in Blockly, but needed in scratch-blocks
* @param {string} fontSize E.g., '10pt'
* @param {string} fontFamily E.g., 'Arial'
* @param {string} fontWeight E.g., '600'
* @param {string} text The actual text to measure
* @return {number} Width of the text in px.
* @package
*/
Blockly.scratchBlocksUtils.measureText = function(fontSize, fontFamily,
fontWeight, text) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = fontWeight + ' ' + fontSize + ' ' + fontFamily;
return context.measureText(text).width;
};
/**
* Encode a string's HTML entities.
* E.g., <a> -> <a>
* Does not exist in Blockly, but needed in scratch-blocks
* @param {string} rawStr Unencoded raw string to encode.
* @return {string} String with HTML entities encoded.
* @package
*/
Blockly.scratchBlocksUtils.encodeEntities = function(rawStr) {
// CC-BY-SA https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
return rawStr.replace(/[\u00A0-\u9999<>&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
};
/**
* Re-assign obscured shadow blocks new IDs to prevent collisions
* Scratch specific to help the VM handle deleting obscured shadows.
* @param {Blockly.Block} block the root block to be processed.
* @package
*/
Blockly.scratchBlocksUtils.changeObscuredShadowIds = function(block) {
var blocks = block.getDescendants();
for (var i = blocks.length - 1; i >= 0; i--) {
var descendant = blocks[i];
for (var j = 0; j < descendant.inputList.length; j++) {
var connection = descendant.inputList[j].connection;
if (connection) {
var shadowDom = connection.getShadowDom();
if (shadowDom) {
shadowDom.setAttribute('id', Blockly.utils.genUid());
connection.setShadowDom(shadowDom);
}
}
}
}
};
/**
* Whether a block is both a shadow block and an argument reporter. These
* blocks have special behaviour in scratch-blocks: they're duplicated when
* dragged, and they are rendered slightly differently from normal shadow
* blocks.
* @param {!Blockly.BlockSvg} block The block that should be used to make this
* decision.
* @return {boolean} True if the block should be duplicated on drag.
* @package
*/
Blockly.scratchBlocksUtils.isShadowArgumentReporter = function(block) {
return (block.isShadow() && (block.type == 'argument_reporter_boolean' ||
block.type == 'argument_reporter_string_number'));
};
| 1 | 9,414 | I noticed that passing in `[]` for the locales argument instead of 'undefined' seems to have the same effect. I think that's preferred over passing in `undefined` as a value, and unfortunately passing in `null` seems to throw an error. | LLK-scratch-blocks | js |
@@ -114,12 +114,11 @@ func getEngine() (*xorm.Engine, error) {
}
case "postgres":
host, port := "127.0.0.1", "5432"
- fields := strings.Split(DbCfg.Host, ":")
- if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
- host = fields[0]
- }
- if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
- port = fields[1]
+ if strings.Contains(DbCfg.Host, ":") && !strings.HasSuffix(DbCfg.Host, "]") {
+ host = DbCfg.Host[0:strings.LastIndex(DbCfg.Host, ":")]
+ port = DbCfg.Host[strings.LastIndex(DbCfg.Host, ":")+1:]
+ } else if len(DbCfg.Host) > 0 {
+ host = DbCfg.Host
}
if host[0] == '/' { // looks like a unix socket | 1 | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"database/sql"
"errors"
"fmt"
"net/url"
"os"
"path"
"strings"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
_ "github.com/lib/pq"
"github.com/gogits/gogs/models/migrations"
"github.com/gogits/gogs/modules/setting"
)
// Engine represents a xorm engine or session.
type Engine interface {
Delete(interface{}) (int64, error)
Exec(string, ...interface{}) (sql.Result, error)
Find(interface{}, ...interface{}) error
Get(interface{}) (bool, error)
Id(interface{}) *xorm.Session
Insert(...interface{}) (int64, error)
InsertOne(interface{}) (int64, error)
Iterate(interface{}, xorm.IterFunc) error
Sql(string, ...interface{}) *xorm.Session
Where(string, ...interface{}) *xorm.Session
}
func sessionRelease(sess *xorm.Session) {
if !sess.IsCommitedOrRollbacked {
sess.Rollback()
}
sess.Close()
}
var (
x *xorm.Engine
tables []interface{}
HasEngine bool
DbCfg struct {
Type, Host, Name, User, Passwd, Path, SSLMode string
}
EnableSQLite3 bool
EnableTiDB bool
)
func init() {
tables = append(tables,
new(User), new(PublicKey), new(AccessToken),
new(Repository), new(DeployKey), new(Collaboration), new(Access),
new(Watch), new(Star), new(Follow), new(Action),
new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
new(Label), new(IssueLabel), new(Milestone),
new(Mirror), new(Release), new(LoginSource), new(Webhook),
new(UpdateTask), new(HookTask),
new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
new(Notice), new(EmailAddress))
gonicNames := []string{"SSL"}
for _, name := range gonicNames {
core.LintGonicMapper[name] = true
}
}
func LoadConfigs() {
sec := setting.Cfg.Section("database")
DbCfg.Type = sec.Key("DB_TYPE").String()
switch DbCfg.Type {
case "sqlite3":
setting.UseSQLite3 = true
case "mysql":
setting.UseMySQL = true
case "postgres":
setting.UsePostgreSQL = true
case "tidb":
setting.UseTiDB = true
}
DbCfg.Host = sec.Key("HOST").String()
DbCfg.Name = sec.Key("NAME").String()
DbCfg.User = sec.Key("USER").String()
if len(DbCfg.Passwd) == 0 {
DbCfg.Passwd = sec.Key("PASSWD").String()
}
DbCfg.SSLMode = sec.Key("SSL_MODE").String()
DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
}
func getEngine() (*xorm.Engine, error) {
connStr := ""
var Param string = "?"
if strings.Contains(DbCfg.Name, Param) {
Param = "&"
}
switch DbCfg.Type {
case "mysql":
if DbCfg.Host[0] == '/' { // looks like a unix socket
connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
} else {
connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
}
case "postgres":
host, port := "127.0.0.1", "5432"
fields := strings.Split(DbCfg.Host, ":")
if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
host = fields[0]
}
if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
port = fields[1]
}
if host[0] == '/' { // looks like a unix socket
connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
} else {
connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
}
case "sqlite3":
if !EnableSQLite3 {
return nil, errors.New("This binary version does not build support for SQLite3.")
}
if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
return nil, fmt.Errorf("Fail to create directories: %v", err)
}
connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
case "tidb":
if !EnableTiDB {
return nil, errors.New("This binary version does not build support for TiDB.")
}
if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
return nil, fmt.Errorf("Fail to create directories: %v", err)
}
connStr = "goleveldb://" + DbCfg.Path
default:
return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
}
return xorm.NewEngine(DbCfg.Type, connStr)
}
func NewTestEngine(x *xorm.Engine) (err error) {
x, err = getEngine()
if err != nil {
return fmt.Errorf("Connect to database: %v", err)
}
x.SetMapper(core.GonicMapper{})
return x.StoreEngine("InnoDB").Sync2(tables...)
}
func SetEngine() (err error) {
x, err = getEngine()
if err != nil {
return fmt.Errorf("Fail to connect to database: %v", err)
}
x.SetMapper(core.GonicMapper{})
// WARNING: for serv command, MUST remove the output to os.stdout,
// so use log file to instead print to stdout.
logPath := path.Join(setting.LogRootPath, "xorm.log")
os.MkdirAll(path.Dir(logPath), os.ModePerm)
f, err := os.Create(logPath)
if err != nil {
return fmt.Errorf("Fail to create xorm.log: %v", err)
}
x.SetLogger(xorm.NewSimpleLogger(f))
x.ShowSQL(true)
return nil
}
func NewEngine() (err error) {
if err = SetEngine(); err != nil {
return err
}
if err = migrations.Migrate(x); err != nil {
return fmt.Errorf("migrate: %v", err)
}
if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
return fmt.Errorf("sync database struct error: %v\n", err)
}
return nil
}
type Statistic struct {
Counter struct {
User, Org, PublicKey,
Repo, Watch, Star, Action, Access,
Issue, Comment, Oauth, Follow,
Mirror, Release, LoginSource, Webhook,
Milestone, Label, HookTask,
Team, UpdateTask, Attachment int64
}
}
func GetStatistic() (stats Statistic) {
stats.Counter.User = CountUsers()
stats.Counter.Org = CountOrganizations()
stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
stats.Counter.Repo = CountRepositories(true)
stats.Counter.Watch, _ = x.Count(new(Watch))
stats.Counter.Star, _ = x.Count(new(Star))
stats.Counter.Action, _ = x.Count(new(Action))
stats.Counter.Access, _ = x.Count(new(Access))
stats.Counter.Issue, _ = x.Count(new(Issue))
stats.Counter.Comment, _ = x.Count(new(Comment))
stats.Counter.Oauth = 0
stats.Counter.Follow, _ = x.Count(new(Follow))
stats.Counter.Mirror, _ = x.Count(new(Mirror))
stats.Counter.Release, _ = x.Count(new(Release))
stats.Counter.LoginSource = CountLoginSources()
stats.Counter.Webhook, _ = x.Count(new(Webhook))
stats.Counter.Milestone, _ = x.Count(new(Milestone))
stats.Counter.Label, _ = x.Count(new(Label))
stats.Counter.HookTask, _ = x.Count(new(HookTask))
stats.Counter.Team, _ = x.Count(new(Team))
stats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))
stats.Counter.Attachment, _ = x.Count(new(Attachment))
return
}
func Ping() error {
return x.Ping()
}
// DumpDatabase dumps all data from database to file system.
func DumpDatabase(filePath string) error {
return x.DumpAllToFile(filePath)
}
| 1 | 11,785 | 1. `0` is redundant. 2. We should save result of `strings.LastIndex(DbCfg.Host, ":")` to a variable and reuse. | gogs-gogs | go |
@@ -157,6 +157,7 @@ type Options struct {
NoLog bool `json:"-"`
NoSigs bool `json:"-"`
NoSublistCache bool `json:"-"`
+ NoHeaderSupport bool `json:"-"`
DisableShortFirstPing bool `json:"-"`
Logtime bool `json:"-"`
MaxConn int `json:"max_connections"` | 1 | // Copyright 2012-2020 The NATS 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 server
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/nats-io/jwt"
"github.com/nats-io/nkeys"
"github.com/nats-io/nats-server/v2/conf"
)
var allowUnknownTopLevelField = int32(0)
// NoErrOnUnknownFields can be used to change the behavior the processing
// of a configuration file. By default, an error is reported if unknown
// fields are found. If `noError` is set to true, no error will be reported
// if top-level unknown fields are found.
func NoErrOnUnknownFields(noError bool) {
var val int32
if noError {
val = int32(1)
}
atomic.StoreInt32(&allowUnknownTopLevelField, val)
}
// ClusterOpts are options for clusters.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type ClusterOpts struct {
Host string `json:"addr,omitempty"`
Port int `json:"cluster_port,omitempty"`
Username string `json:"-"`
Password string `json:"-"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
Permissions *RoutePermissions `json:"-"`
TLSTimeout float64 `json:"-"`
TLSConfig *tls.Config `json:"-"`
TLSMap bool `json:"-"`
ListenStr string `json:"-"`
Advertise string `json:"-"`
NoAdvertise bool `json:"-"`
ConnectRetries int `json:"-"`
}
// GatewayOpts are options for gateways.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type GatewayOpts struct {
Name string `json:"name"`
Host string `json:"addr,omitempty"`
Port int `json:"port,omitempty"`
Username string `json:"-"`
Password string `json:"-"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
TLSConfig *tls.Config `json:"-"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
TLSMap bool `json:"-"`
Advertise string `json:"advertise,omitempty"`
ConnectRetries int `json:"connect_retries,omitempty"`
Gateways []*RemoteGatewayOpts `json:"gateways,omitempty"`
RejectUnknown bool `json:"reject_unknown,omitempty"`
// Not exported, for tests.
resolver netResolver
sendQSubsBufSize int
}
// RemoteGatewayOpts are options for connecting to a remote gateway
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type RemoteGatewayOpts struct {
Name string `json:"name"`
TLSConfig *tls.Config `json:"-"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
URLs []*url.URL `json:"urls,omitempty"`
}
// LeafNodeOpts are options for a given server to accept leaf node connections and/or connect to a remote cluster.
type LeafNodeOpts struct {
Host string `json:"addr,omitempty"`
Port int `json:"port,omitempty"`
Username string `json:"-"`
Password string `json:"-"`
Account string `json:"-"`
Users []*User `json:"-"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
TLSConfig *tls.Config `json:"-"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
TLSMap bool `json:"-"`
Advertise string `json:"-"`
NoAdvertise bool `json:"-"`
ReconnectInterval time.Duration `json:"-"`
// For solicited connections to other clusters/superclusters.
Remotes []*RemoteLeafOpts `json:"remotes,omitempty"`
// Not exported, for tests.
resolver netResolver
dialTimeout time.Duration
connDelay time.Duration
}
// RemoteLeafOpts are options for connecting to a remote server as a leaf node.
type RemoteLeafOpts struct {
LocalAccount string `json:"local_account,omitempty"`
URLs []*url.URL `json:"urls,omitempty"`
Credentials string `json:"-"`
TLS bool `json:"-"`
TLSConfig *tls.Config `json:"-"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
Hub bool `json:"hub,omitempty"`
DenyImports []string `json:"-"`
DenyExports []string `json:"-"`
}
// Options block for nats-server.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type Options struct {
ConfigFile string `json:"-"`
ServerName string `json:"server_name"`
Host string `json:"addr"`
Port int `json:"port"`
ClientAdvertise string `json:"-"`
Trace bool `json:"-"`
Debug bool `json:"-"`
TraceVerbose bool `json:"-"`
NoLog bool `json:"-"`
NoSigs bool `json:"-"`
NoSublistCache bool `json:"-"`
DisableShortFirstPing bool `json:"-"`
Logtime bool `json:"-"`
MaxConn int `json:"max_connections"`
MaxSubs int `json:"max_subscriptions,omitempty"`
Nkeys []*NkeyUser `json:"-"`
Users []*User `json:"-"`
Accounts []*Account `json:"-"`
SystemAccount string `json:"-"`
AllowNewAccounts bool `json:"-"`
Username string `json:"-"`
Password string `json:"-"`
Authorization string `json:"-"`
PingInterval time.Duration `json:"ping_interval"`
MaxPingsOut int `json:"ping_max"`
HTTPHost string `json:"http_host"`
HTTPPort int `json:"http_port"`
HTTPSPort int `json:"https_port"`
AuthTimeout float64 `json:"auth_timeout"`
MaxControlLine int32 `json:"max_control_line"`
MaxPayload int32 `json:"max_payload"`
MaxPending int64 `json:"max_pending"`
Cluster ClusterOpts `json:"cluster,omitempty"`
Gateway GatewayOpts `json:"gateway,omitempty"`
LeafNode LeafNodeOpts `json:"leaf,omitempty"`
JetStream bool `json:"jetstream"`
JetStreamMaxMemory int64 `json:"-"`
JetStreamMaxStore int64 `json:"-"`
StoreDir string `json:"-"`
ProfPort int `json:"-"`
PidFile string `json:"-"`
PortsFileDir string `json:"-"`
LogFile string `json:"-"`
LogSizeLimit int64 `json:"-"`
Syslog bool `json:"-"`
RemoteSyslog string `json:"-"`
Routes []*url.URL `json:"-"`
RoutesStr string `json:"-"`
TLSTimeout float64 `json:"tls_timeout"`
TLS bool `json:"-"`
TLSVerify bool `json:"-"`
TLSMap bool `json:"-"`
TLSCert string `json:"-"`
TLSKey string `json:"-"`
TLSCaCert string `json:"-"`
TLSConfig *tls.Config `json:"-"`
WriteDeadline time.Duration `json:"-"`
MaxClosedClients int `json:"-"`
LameDuckDuration time.Duration `json:"-"`
// MaxTracedMsgLen is the maximum printable length for traced messages.
MaxTracedMsgLen int `json:"-"`
// Operating a trusted NATS server
TrustedKeys []string `json:"-"`
TrustedOperators []*jwt.OperatorClaims `json:"-"`
AccountResolver AccountResolver `json:"-"`
AccountResolverTLSConfig *tls.Config `json:"-"`
resolverPreloads map[string]string
CustomClientAuthentication Authentication `json:"-"`
CustomRouterAuthentication Authentication `json:"-"`
// CheckConfig configuration file syntax test was successful and exit.
CheckConfig bool `json:"-"`
// ConnectErrorReports specifies the number of failed attempts
// at which point server should report the failure of an initial
// connection to a route, gateway or leaf node.
// See DEFAULT_CONNECT_ERROR_REPORTS for default value.
ConnectErrorReports int
// ReconnectErrorReports is similar to ConnectErrorReports except
// that this applies to reconnect events.
ReconnectErrorReports int
// private fields, used to know if bool options are explicitly
// defined in config and/or command line params.
inConfig map[string]bool
inCmdLine map[string]bool
// private fields, used for testing
gatewaysSolicitDelay time.Duration
routeProto int
}
type netResolver interface {
LookupHost(ctx context.Context, host string) ([]string, error)
}
// Clone performs a deep copy of the Options struct, returning a new clone
// with all values copied.
func (o *Options) Clone() *Options {
if o == nil {
return nil
}
clone := &Options{}
*clone = *o
if o.Users != nil {
clone.Users = make([]*User, len(o.Users))
for i, user := range o.Users {
clone.Users[i] = user.clone()
}
}
if o.Nkeys != nil {
clone.Nkeys = make([]*NkeyUser, len(o.Nkeys))
for i, nkey := range o.Nkeys {
clone.Nkeys[i] = nkey.clone()
}
}
if o.Routes != nil {
clone.Routes = deepCopyURLs(o.Routes)
}
if o.TLSConfig != nil {
clone.TLSConfig = o.TLSConfig.Clone()
}
if o.Cluster.TLSConfig != nil {
clone.Cluster.TLSConfig = o.Cluster.TLSConfig.Clone()
}
if o.Gateway.TLSConfig != nil {
clone.Gateway.TLSConfig = o.Gateway.TLSConfig.Clone()
}
if len(o.Gateway.Gateways) > 0 {
clone.Gateway.Gateways = make([]*RemoteGatewayOpts, len(o.Gateway.Gateways))
for i, g := range o.Gateway.Gateways {
clone.Gateway.Gateways[i] = g.clone()
}
}
// FIXME(dlc) - clone leaf node stuff.
return clone
}
func deepCopyURLs(urls []*url.URL) []*url.URL {
if urls == nil {
return nil
}
curls := make([]*url.URL, len(urls))
for i, u := range urls {
cu := &url.URL{}
*cu = *u
curls[i] = cu
}
return curls
}
// Configuration file authorization section.
type authorization struct {
// Singles
user string
pass string
token string
acc string
// Multiple Nkeys/Users
nkeys []*NkeyUser
users []*User
timeout float64
defaultPermissions *Permissions
}
// TLSConfigOpts holds the parsed tls config information,
// used with flag parsing
type TLSConfigOpts struct {
CertFile string
KeyFile string
CaFile string
Verify bool
Insecure bool
Map bool
Timeout float64
Ciphers []uint16
CurvePreferences []tls.CurveID
}
var tlsUsage = `
TLS configuration is specified in the tls section of a configuration file:
e.g.
tls {
cert_file: "./certs/server-cert.pem"
key_file: "./certs/server-key.pem"
ca_file: "./certs/ca.pem"
verify: true
verify_and_map: true
cipher_suites: [
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
]
curve_preferences: [
"CurveP256",
"CurveP384",
"CurveP521"
]
}
Available cipher suites include:
`
// ProcessConfigFile processes a configuration file.
// FIXME(dlc): A bit hacky
func ProcessConfigFile(configFile string) (*Options, error) {
opts := &Options{}
if err := opts.ProcessConfigFile(configFile); err != nil {
// If only warnings then continue and return the options.
if cerr, ok := err.(*processConfigErr); ok && len(cerr.Errors()) == 0 {
return opts, nil
}
return nil, err
}
return opts, nil
}
// token is an item parsed from the configuration.
type token interface {
Value() interface{}
Line() int
IsUsedVariable() bool
SourceFile() string
Position() int
}
// unwrapValue can be used to get the token and value from an item
// to be able to report the line number in case of an incorrect
// configuration.
// also stores the token in lastToken for use in convertPanicToError
func unwrapValue(v interface{}, lastToken *token) (token, interface{}) {
switch tk := v.(type) {
case token:
if lastToken != nil {
*lastToken = tk
}
return tk, tk.Value()
default:
return nil, v
}
}
// use in defer to recover from panic and turn it into an error associated with last token
func convertPanicToErrorList(lastToken *token, errors *[]error) {
// only recover if an error can be stored
if errors == nil {
return
} else if err := recover(); err == nil {
return
} else if lastToken != nil && *lastToken != nil {
*errors = append(*errors, &configErr{*lastToken, fmt.Sprint(err)})
} else {
*errors = append(*errors, fmt.Errorf("encountered panic without a token %v", err))
}
}
// use in defer to recover from panic and turn it into an error associated with last token
func convertPanicToError(lastToken *token, e *error) {
// only recover if an error can be stored
if e == nil || *e != nil {
return
} else if err := recover(); err == nil {
return
} else if lastToken != nil && *lastToken != nil {
*e = &configErr{*lastToken, fmt.Sprint(err)}
} else {
*e = fmt.Errorf("%v", err)
}
}
// configureSystemAccount configures a system account
// if present in the configuration.
func configureSystemAccount(o *Options, m map[string]interface{}) (retErr error) {
var lt token
defer convertPanicToError(<, &retErr)
configure := func(v interface{}) error {
tk, v := unwrapValue(v, <)
sa, ok := v.(string)
if !ok {
return &configErr{tk, "system account name must be a string"}
}
o.SystemAccount = sa
return nil
}
if v, ok := m["system_account"]; ok {
return configure(v)
} else if v, ok := m["system"]; ok {
return configure(v)
}
return nil
}
// ProcessConfigFile updates the Options structure with options
// present in the given configuration file.
// This version is convenient if one wants to set some default
// options and then override them with what is in the config file.
// For instance, this version allows you to do something such as:
//
// opts := &Options{Debug: true}
// opts.ProcessConfigFile(myConfigFile)
//
// If the config file contains "debug: false", after this call,
// opts.Debug would really be false. It would be impossible to
// achieve that with the non receiver ProcessConfigFile() version,
// since one would not know after the call if "debug" was not present
// or was present but set to false.
func (o *Options) ProcessConfigFile(configFile string) error {
o.ConfigFile = configFile
if configFile == "" {
return nil
}
m, err := conf.ParseFileWithChecks(configFile)
if err != nil {
return err
}
// Collect all errors and warnings and report them all together.
errors := make([]error, 0)
warnings := make([]error, 0)
// First check whether a system account has been defined,
// as that is a condition for other features to be enabled.
if err := configureSystemAccount(o, m); err != nil {
errors = append(errors, err)
}
for k, v := range m {
o.processConfigFileLine(k, v, &errors, &warnings)
}
if len(errors) > 0 || len(warnings) > 0 {
return &processConfigErr{
errors: errors,
warnings: warnings,
}
}
return nil
}
func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error, warnings *[]error) {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
switch strings.ToLower(k) {
case "listen":
hp, err := parseListen(v)
if err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
return
}
o.Host = hp.host
o.Port = hp.port
case "client_advertise":
o.ClientAdvertise = v.(string)
case "port":
o.Port = int(v.(int64))
case "server_name":
o.ServerName = v.(string)
case "host", "net":
o.Host = v.(string)
case "debug":
o.Debug = v.(bool)
trackExplicitVal(o, &o.inConfig, "Debug", o.Debug)
case "trace":
o.Trace = v.(bool)
trackExplicitVal(o, &o.inConfig, "Trace", o.Trace)
case "trace_verbose":
o.TraceVerbose = v.(bool)
o.Trace = v.(bool)
trackExplicitVal(o, &o.inConfig, "TraceVerbose", o.TraceVerbose)
trackExplicitVal(o, &o.inConfig, "Trace", o.Trace)
case "logtime":
o.Logtime = v.(bool)
trackExplicitVal(o, &o.inConfig, "Logtime", o.Logtime)
case "disable_sublist_cache", "no_sublist_cache":
o.NoSublistCache = v.(bool)
case "accounts":
err := parseAccounts(tk, o, errors, warnings)
if err != nil {
*errors = append(*errors, err)
return
}
case "authorization":
auth, err := parseAuthorization(tk, o, errors, warnings)
if err != nil {
*errors = append(*errors, err)
return
}
o.Username = auth.user
o.Password = auth.pass
o.Authorization = auth.token
if (auth.user != "" || auth.pass != "") && auth.token != "" {
err := &configErr{tk, "Cannot have a user/pass and token"}
*errors = append(*errors, err)
return
}
o.AuthTimeout = auth.timeout
// Check for multiple users defined
if auth.users != nil {
if auth.user != "" {
err := &configErr{tk, "Can not have a single user/pass and a users array"}
*errors = append(*errors, err)
return
}
if auth.token != "" {
err := &configErr{tk, "Can not have a token and a users array"}
*errors = append(*errors, err)
return
}
// Users may have been added from Accounts parsing, so do an append here
o.Users = append(o.Users, auth.users...)
}
// Check for nkeys
if auth.nkeys != nil {
// NKeys may have been added from Accounts parsing, so do an append here
o.Nkeys = append(o.Nkeys, auth.nkeys...)
}
case "http":
hp, err := parseListen(v)
if err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
return
}
o.HTTPHost = hp.host
o.HTTPPort = hp.port
case "https":
hp, err := parseListen(v)
if err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
return
}
o.HTTPHost = hp.host
o.HTTPSPort = hp.port
case "http_port", "monitor_port":
o.HTTPPort = int(v.(int64))
case "https_port":
o.HTTPSPort = int(v.(int64))
case "cluster":
err := parseCluster(tk, o, errors, warnings)
if err != nil {
*errors = append(*errors, err)
return
}
case "gateway":
if err := parseGateway(tk, o, errors, warnings); err != nil {
*errors = append(*errors, err)
return
}
case "leaf", "leafnodes":
err := parseLeafNodes(tk, o, errors, warnings)
if err != nil {
*errors = append(*errors, err)
return
}
case "jetstream":
err := parseJetStream(tk, o, errors, warnings)
if err != nil {
*errors = append(*errors, err)
return
}
case "logfile", "log_file":
o.LogFile = v.(string)
case "logfile_size_limit", "log_size_limit":
o.LogSizeLimit = v.(int64)
case "syslog":
o.Syslog = v.(bool)
trackExplicitVal(o, &o.inConfig, "Syslog", o.Syslog)
case "remote_syslog":
o.RemoteSyslog = v.(string)
case "pidfile", "pid_file":
o.PidFile = v.(string)
case "ports_file_dir":
o.PortsFileDir = v.(string)
case "prof_port":
o.ProfPort = int(v.(int64))
case "max_control_line":
if v.(int64) > 1<<31-1 {
err := &configErr{tk, fmt.Sprintf("%s value is too big", k)}
*errors = append(*errors, err)
return
}
o.MaxControlLine = int32(v.(int64))
case "max_payload":
if v.(int64) > 1<<31-1 {
err := &configErr{tk, fmt.Sprintf("%s value is too big", k)}
*errors = append(*errors, err)
return
}
o.MaxPayload = int32(v.(int64))
case "max_pending":
o.MaxPending = v.(int64)
case "max_connections", "max_conn":
o.MaxConn = int(v.(int64))
case "max_traced_msg_len":
o.MaxTracedMsgLen = int(v.(int64))
case "max_subscriptions", "max_subs":
o.MaxSubs = int(v.(int64))
case "ping_interval":
o.PingInterval = parseDuration("ping_interval", tk, v, errors, warnings)
case "ping_max":
o.MaxPingsOut = int(v.(int64))
case "tls":
tc, err := parseTLS(tk)
if err != nil {
*errors = append(*errors, err)
return
}
if o.TLSConfig, err = GenTLSConfig(tc); err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
return
}
o.TLSTimeout = tc.Timeout
o.TLSMap = tc.Map
case "write_deadline":
o.WriteDeadline = parseDuration("write_deadline", tk, v, errors, warnings)
case "lame_duck_duration":
dur, err := time.ParseDuration(v.(string))
if err != nil {
err := &configErr{tk, fmt.Sprintf("error parsing lame_duck_duration: %v", err)}
*errors = append(*errors, err)
return
}
if dur < 30*time.Second {
err := &configErr{tk, fmt.Sprintf("invalid lame_duck_duration of %v, minimum is 30 seconds", dur)}
*errors = append(*errors, err)
return
}
o.LameDuckDuration = dur
case "operator", "operators", "roots", "root", "root_operators", "root_operator":
opFiles := []string{}
switch v := v.(type) {
case string:
opFiles = append(opFiles, v)
case []string:
opFiles = append(opFiles, v...)
default:
err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T", v)}
*errors = append(*errors, err)
}
// Assume for now these are file names, but they can also be the JWT itself inline.
o.TrustedOperators = make([]*jwt.OperatorClaims, 0, len(opFiles))
for _, fname := range opFiles {
opc, err := ReadOperatorJWT(fname)
if err != nil {
err := &configErr{tk, fmt.Sprintf("error parsing operator JWT: %v", err)}
*errors = append(*errors, err)
continue
}
o.TrustedOperators = append(o.TrustedOperators, opc)
}
// In case "resolver" is defined as well, it takes precedence
if o.AccountResolver == nil && len(o.TrustedOperators) == 1 {
if accUrl, err := parseURL(o.TrustedOperators[0].AccountServerURL, "account resolver"); err == nil {
// accommodate nsc which appends "/accounts" during nsc push
suffix := ""
if accUrl.Path == "/jwt/v1/" || accUrl.Path == "/jwt/v1" {
suffix = "/accounts"
}
o.AccountResolver, _ = NewURLAccResolver(accUrl.String() + suffix)
}
}
case "resolver", "account_resolver", "accounts_resolver":
// "resolver" takes precedence over value obtained from "operator".
// Clear so that parsing errors are not silently ignored.
o.AccountResolver = nil
var memResolverRe = regexp.MustCompile(`(MEM|MEMORY|mem|memory)\s*`)
var resolverRe = regexp.MustCompile(`(?:URL|url){1}(?:\({1}\s*"?([^\s"]*)"?\s*\){1})?\s*`)
str, ok := v.(string)
if !ok {
err := &configErr{tk, fmt.Sprintf("error parsing operator resolver, wrong type %T", v)}
*errors = append(*errors, err)
return
}
if memResolverRe.MatchString(str) {
o.AccountResolver = &MemAccResolver{}
} else {
items := resolverRe.FindStringSubmatch(str)
if len(items) == 2 {
url := items[1]
_, err := parseURL(url, "account resolver")
if err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
return
}
if ur, err := NewURLAccResolver(url); err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
return
} else {
o.AccountResolver = ur
}
}
}
if o.AccountResolver == nil {
err := &configErr{tk, "error parsing account resolver, should be MEM or URL(\"url\")"}
*errors = append(*errors, err)
}
case "resolver_tls":
tc, err := parseTLS(tk)
if err != nil {
*errors = append(*errors, err)
return
}
if o.AccountResolverTLSConfig, err = GenTLSConfig(tc); err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
return
}
case "resolver_preload":
mp, ok := v.(map[string]interface{})
if !ok {
err := &configErr{tk, "preload should be a map of account_public_key:account_jwt"}
*errors = append(*errors, err)
return
}
o.resolverPreloads = make(map[string]string)
for key, val := range mp {
tk, val = unwrapValue(val, <)
if jwtstr, ok := val.(string); !ok {
err := &configErr{tk, "preload map value should be a string JWT"}
*errors = append(*errors, err)
continue
} else {
// Make sure this is a valid account JWT, that is a config error.
// We will warn of expirations, etc later.
if _, err := jwt.DecodeAccountClaims(jwtstr); err != nil {
err := &configErr{tk, "invalid account JWT"}
*errors = append(*errors, err)
continue
}
o.resolverPreloads[key] = jwtstr
}
}
case "system_account", "system":
// Already processed at the beginning so we just skip them
// to not treat them as unknown values.
return
case "trusted", "trusted_keys":
switch v := v.(type) {
case string:
o.TrustedKeys = []string{v}
case []string:
o.TrustedKeys = v
case []interface{}:
keys := make([]string, 0, len(v))
for _, mv := range v {
tk, mv = unwrapValue(mv, <)
if key, ok := mv.(string); ok {
keys = append(keys, key)
} else {
err := &configErr{tk, fmt.Sprintf("error parsing trusted: unsupported type in array %T", mv)}
*errors = append(*errors, err)
continue
}
}
o.TrustedKeys = keys
default:
err := &configErr{tk, fmt.Sprintf("error parsing trusted: unsupported type %T", v)}
*errors = append(*errors, err)
}
// Do a quick sanity check on keys
for _, key := range o.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
err := &configErr{tk, fmt.Sprintf("trust key %q required to be a valid public operator nkey", key)}
*errors = append(*errors, err)
}
}
case "connect_error_reports":
o.ConnectErrorReports = int(v.(int64))
case "reconnect_error_reports":
o.ReconnectErrorReports = int(v.(int64))
default:
if au := atomic.LoadInt32(&allowUnknownTopLevelField); au == 0 && !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: k,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
func parseDuration(field string, tk token, v interface{}, errors *[]error, warnings *[]error) time.Duration {
if wd, ok := v.(string); ok {
if dur, err := time.ParseDuration(wd); err != nil {
err := &configErr{tk, fmt.Sprintf("error parsing %s: %v", field, err)}
*errors = append(*errors, err)
return 0
} else {
return dur
}
} else {
// Backward compatible with old type, assume this is the
// number of seconds.
err := &configWarningErr{
field: field,
configErr: configErr{
token: tk,
reason: field + " should be converted to a duration",
},
}
*warnings = append(*warnings, err)
return time.Duration(v.(int64)) * time.Second
}
}
func trackExplicitVal(opts *Options, pm *map[string]bool, name string, val bool) {
m := *pm
if m == nil {
m = make(map[string]bool)
*pm = m
}
m[name] = val
}
// hostPort is simple struct to hold parsed listen/addr strings.
type hostPort struct {
host string
port int
}
// parseListen will parse listen option which is replacing host/net and port
func parseListen(v interface{}) (*hostPort, error) {
hp := &hostPort{}
switch vv := v.(type) {
// Only a port
case int64:
hp.port = int(vv)
case string:
host, port, err := net.SplitHostPort(vv)
if err != nil {
return nil, fmt.Errorf("could not parse address string %q", vv)
}
hp.port, err = strconv.Atoi(port)
if err != nil {
return nil, fmt.Errorf("could not parse port %q", port)
}
hp.host = host
}
return hp, nil
}
// parseCluster will parse the cluster config.
func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]error) error {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
cm, ok := v.(map[string]interface{})
if !ok {
return &configErr{tk, fmt.Sprintf("Expected map to define cluster, got %T", v)}
}
for mk, mv := range cm {
// Again, unwrap token value if line check is required.
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "listen":
hp, err := parseListen(mv)
if err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
continue
}
opts.Cluster.Host = hp.host
opts.Cluster.Port = hp.port
case "port":
opts.Cluster.Port = int(mv.(int64))
case "host", "net":
opts.Cluster.Host = mv.(string)
case "authorization":
auth, err := parseAuthorization(tk, opts, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
if auth.users != nil {
err := &configErr{tk, "Cluster authorization does not allow multiple users"}
*errors = append(*errors, err)
continue
}
opts.Cluster.Username = auth.user
opts.Cluster.Password = auth.pass
opts.Cluster.AuthTimeout = auth.timeout
if auth.defaultPermissions != nil {
err := &configWarningErr{
field: mk,
configErr: configErr{
token: tk,
reason: `setting "permissions" within cluster authorization block is deprecated`,
},
}
*warnings = append(*warnings, err)
// Do not set permissions if they were specified in top-level cluster block.
if opts.Cluster.Permissions == nil {
setClusterPermissions(&opts.Cluster, auth.defaultPermissions)
}
}
case "routes":
ra := mv.([]interface{})
routes, errs := parseURLs(ra, "route")
if errs != nil {
*errors = append(*errors, errs...)
continue
}
opts.Routes = routes
case "tls":
config, tlsopts, err := getTLSConfig(tk)
if err != nil {
*errors = append(*errors, err)
continue
}
opts.Cluster.TLSConfig = config
opts.Cluster.TLSTimeout = tlsopts.Timeout
opts.Cluster.TLSMap = tlsopts.Map
case "cluster_advertise", "advertise":
opts.Cluster.Advertise = mv.(string)
case "no_advertise":
opts.Cluster.NoAdvertise = mv.(bool)
trackExplicitVal(opts, &opts.inConfig, "Cluster.NoAdvertise", opts.Cluster.NoAdvertise)
case "connect_retries":
opts.Cluster.ConnectRetries = int(mv.(int64))
case "permissions":
perms, err := parseUserPermissions(mv, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
// Dynamic response permissions do not make sense here.
if perms.Response != nil {
err := &configErr{tk, "Cluster permissions do not support dynamic responses"}
*errors = append(*errors, err)
continue
}
// This will possibly override permissions that were define in auth block
setClusterPermissions(&opts.Cluster, perms)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
return nil
}
func parseURLs(a []interface{}, typ string) (urls []*url.URL, errors []error) {
urls = make([]*url.URL, 0, len(a))
var lt token
defer convertPanicToErrorList(<, &errors)
for _, u := range a {
tk, u := unwrapValue(u, <)
sURL := u.(string)
url, err := parseURL(sURL, typ)
if err != nil {
err := &configErr{tk, err.Error()}
errors = append(errors, err)
continue
}
urls = append(urls, url)
}
return urls, errors
}
func parseURL(u string, typ string) (*url.URL, error) {
urlStr := strings.TrimSpace(u)
url, err := url.Parse(urlStr)
if err != nil {
return nil, fmt.Errorf("error parsing %s url [%q]", typ, urlStr)
}
return url, nil
}
func parseGateway(v interface{}, o *Options, errors *[]error, warnings *[]error) error {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
gm, ok := v.(map[string]interface{})
if !ok {
return &configErr{tk, fmt.Sprintf("Expected gateway to be a map, got %T", v)}
}
for mk, mv := range gm {
// Again, unwrap token value if line check is required.
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "name":
o.Gateway.Name = mv.(string)
case "listen":
hp, err := parseListen(mv)
if err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
continue
}
o.Gateway.Host = hp.host
o.Gateway.Port = hp.port
case "port":
o.Gateway.Port = int(mv.(int64))
case "host", "net":
o.Gateway.Host = mv.(string)
case "authorization":
auth, err := parseAuthorization(tk, o, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
if auth.users != nil {
*errors = append(*errors, &configErr{tk, "Gateway authorization does not allow multiple users"})
continue
}
o.Gateway.Username = auth.user
o.Gateway.Password = auth.pass
o.Gateway.AuthTimeout = auth.timeout
case "tls":
config, tlsopts, err := getTLSConfig(tk)
if err != nil {
*errors = append(*errors, err)
continue
}
o.Gateway.TLSConfig = config
o.Gateway.TLSTimeout = tlsopts.Timeout
o.Gateway.TLSMap = tlsopts.Map
case "advertise":
o.Gateway.Advertise = mv.(string)
case "connect_retries":
o.Gateway.ConnectRetries = int(mv.(int64))
case "gateways":
gateways, err := parseGateways(mv, errors, warnings)
if err != nil {
return err
}
o.Gateway.Gateways = gateways
case "reject_unknown":
o.Gateway.RejectUnknown = mv.(bool)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
return nil
}
var dynamicJSAccountLimits = &JetStreamAccountLimits{-1, -1, -1, -1}
// Parses jetstream account limits for an account. Simple setup with boolen is allowed, and we will
// use dynamic account limits.
func parseJetStreamForAccount(v interface{}, acc *Account, errors *[]error, warnings *[]error) error {
var lt token
tk, v := unwrapValue(v, <)
// Value here can be bool, or string "enabled" or a map.
switch vv := v.(type) {
case bool:
if vv {
acc.jsLimits = dynamicJSAccountLimits
}
case string:
switch strings.ToLower(vv) {
case "enabled", "enable":
acc.jsLimits = dynamicJSAccountLimits
case "disabled", "disable":
acc.jsLimits = nil
default:
return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)}
}
case map[string]interface{}:
jsLimits := &JetStreamAccountLimits{-1, -1, -1, -1}
for mk, mv := range vv {
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "max_memory", "max_mem", "mem", "memory":
vv, ok := mv.(int64)
if !ok {
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
}
jsLimits.MaxMemory = int64(vv)
case "max_store", "max_file", "max_disk", "store", "disk":
vv, ok := mv.(int64)
if !ok {
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
}
jsLimits.MaxStore = int64(vv)
case "max_streams", "streams":
vv, ok := mv.(int64)
if !ok {
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
}
jsLimits.MaxStreams = int(vv)
case "max_consumers", "consumers":
vv, ok := mv.(int64)
if !ok {
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
}
jsLimits.MaxConsumers = int(vv)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
acc.jsLimits = jsLimits
default:
return &configErr{tk, fmt.Sprintf("Expected map, bool or string to define JetStream, got %T", v)}
}
return nil
}
// Parse enablement of jetstream for a server.
func parseJetStream(v interface{}, opts *Options, errors *[]error, warnings *[]error) error {
var lt token
tk, v := unwrapValue(v, <)
// Value here can be bool, or string "enabled" or a map.
switch vv := v.(type) {
case bool:
opts.JetStream = v.(bool)
case string:
switch strings.ToLower(vv) {
case "enabled", "enable":
opts.JetStream = true
case "disabled", "disable":
opts.JetStream = false
default:
return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)}
}
case map[string]interface{}:
for mk, mv := range vv {
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "store_dir", "storedir":
opts.StoreDir = mv.(string)
case "max_memory_store", "max_mem_store":
opts.JetStreamMaxMemory = mv.(int64)
case "max_file_store":
opts.JetStreamMaxStore = mv.(int64)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
opts.JetStream = true
default:
return &configErr{tk, fmt.Sprintf("Expected map, bool or string to define JetStream, got %T", v)}
}
return nil
}
// parseLeafNodes will parse the leaf node config.
func parseLeafNodes(v interface{}, opts *Options, errors *[]error, warnings *[]error) error {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
cm, ok := v.(map[string]interface{})
if !ok {
return &configErr{tk, fmt.Sprintf("Expected map to define a leafnode, got %T", v)}
}
for mk, mv := range cm {
// Again, unwrap token value if line check is required.
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "listen":
hp, err := parseListen(mv)
if err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
continue
}
opts.LeafNode.Host = hp.host
opts.LeafNode.Port = hp.port
case "port":
opts.LeafNode.Port = int(mv.(int64))
case "host", "net":
opts.LeafNode.Host = mv.(string)
case "authorization":
auth, err := parseLeafAuthorization(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
opts.LeafNode.Username = auth.user
opts.LeafNode.Password = auth.pass
opts.LeafNode.AuthTimeout = auth.timeout
opts.LeafNode.Account = auth.acc
opts.LeafNode.Users = auth.users
// Validate user info config for leafnode authorization
if err := validateLeafNodeAuthOptions(opts); err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
case "remotes":
// Parse the remote options here.
remotes, err := parseRemoteLeafNodes(mv, errors, warnings)
if err != nil {
continue
}
opts.LeafNode.Remotes = remotes
case "reconnect", "reconnect_delay", "reconnect_interval":
opts.LeafNode.ReconnectInterval = time.Duration(int(mv.(int64))) * time.Second
case "tls":
tc, err := parseTLS(tk)
if err != nil {
*errors = append(*errors, err)
continue
}
if opts.LeafNode.TLSConfig, err = GenTLSConfig(tc); err != nil {
err := &configErr{tk, err.Error()}
*errors = append(*errors, err)
continue
}
opts.LeafNode.TLSTimeout = tc.Timeout
case "leafnode_advertise", "advertise":
opts.LeafNode.Advertise = mv.(string)
case "no_advertise":
opts.LeafNode.NoAdvertise = mv.(bool)
trackExplicitVal(opts, &opts.inConfig, "LeafNode.NoAdvertise", opts.LeafNode.NoAdvertise)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
return nil
}
// This is the authorization parser adapter for the leafnode's
// authorization config.
func parseLeafAuthorization(v interface{}, errors *[]error, warnings *[]error) (*authorization, error) {
var (
am map[string]interface{}
tk token
lt token
auth = &authorization{}
)
defer convertPanicToErrorList(<, errors)
_, v = unwrapValue(v, <)
am = v.(map[string]interface{})
for mk, mv := range am {
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "user", "username":
auth.user = mv.(string)
case "pass", "password":
auth.pass = mv.(string)
case "timeout":
at := float64(1)
switch mv := mv.(type) {
case int64:
at = float64(mv)
case float64:
at = mv
}
auth.timeout = at
case "users":
users, err := parseLeafUsers(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.users = users
case "account":
auth.acc = mv.(string)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
continue
}
}
return auth, nil
}
// This is a trimmed down version of parseUsers that is adapted
// for the users possibly defined in the authorization{} section
// of leafnodes {}.
func parseLeafUsers(mv interface{}, errors *[]error, warnings *[]error) ([]*User, error) {
var (
tk token
lt token
users = []*User{}
)
defer convertPanicToErrorList(<, errors)
tk, mv = unwrapValue(mv, <)
// Make sure we have an array
uv, ok := mv.([]interface{})
if !ok {
return nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)}
}
for _, u := range uv {
tk, u = unwrapValue(u, <)
// Check its a map/struct
um, ok := u.(map[string]interface{})
if !ok {
err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)}
*errors = append(*errors, err)
continue
}
user := &User{}
for k, v := range um {
tk, v = unwrapValue(v, <)
switch strings.ToLower(k) {
case "user", "username":
user.Username = v.(string)
case "pass", "password":
user.Password = v.(string)
case "account":
// We really want to save just the account name here, but
// the User object is *Account. So we create an account object
// but it won't be registered anywhere. The server will just
// use opts.LeafNode.Users[].Account.Name. Alternatively
// we need to create internal objects to store u/p and account
// name and have a server structure to hold that.
user.Account = NewAccount(v.(string))
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: k,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
users = append(users, user)
}
return users, nil
}
func parseRemoteLeafNodes(v interface{}, errors *[]error, warnings *[]error) ([]*RemoteLeafOpts, error) {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
ra, ok := v.([]interface{})
if !ok {
return nil, &configErr{tk, fmt.Sprintf("Expected remotes field to be an array, got %T", v)}
}
remotes := make([]*RemoteLeafOpts, 0, len(ra))
for _, r := range ra {
tk, r = unwrapValue(r, <)
// Check its a map/struct
rm, ok := r.(map[string]interface{})
if !ok {
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected remote leafnode entry to be a map/struct, got %v", r)})
continue
}
remote := &RemoteLeafOpts{}
for k, v := range rm {
tk, v = unwrapValue(v, <)
switch strings.ToLower(k) {
case "url", "urls":
switch v := v.(type) {
case []interface{}, []string:
urls, errs := parseURLs(v.([]interface{}), "leafnode")
if errs != nil {
*errors = append(*errors, errs...)
continue
}
remote.URLs = urls
case string:
url, err := parseURL(v, "leafnode")
if err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
remote.URLs = append(remote.URLs, url)
}
case "account", "local":
remote.LocalAccount = v.(string)
case "creds", "credentials":
p, err := expandPath(v.(string))
if err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
remote.Credentials = p
case "tls":
tc, err := parseTLS(tk)
if err != nil {
*errors = append(*errors, err)
continue
}
if remote.TLSConfig, err = GenTLSConfig(tc); err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
// If ca_file is defined, GenTLSConfig() sets TLSConfig.ClientCAs.
// Set RootCAs since this tls.Config is used when soliciting
// a connection (therefore behaves as a client).
remote.TLSConfig.RootCAs = remote.TLSConfig.ClientCAs
if tc.Timeout > 0 {
remote.TLSTimeout = tc.Timeout
} else {
remote.TLSTimeout = float64(DEFAULT_LEAF_TLS_TIMEOUT)
}
case "hub":
remote.Hub = v.(bool)
case "deny_imports", "deny_import":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
remote.DenyImports = subjects
case "deny_exports", "deny_export":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
remote.DenyExports = subjects
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: k,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
remotes = append(remotes, remote)
}
return remotes, nil
}
// Parse TLS and returns a TLSConfig and TLSTimeout.
// Used by cluster and gateway parsing.
func getTLSConfig(tk token) (*tls.Config, *TLSConfigOpts, error) {
tc, err := parseTLS(tk)
if err != nil {
return nil, nil, err
}
config, err := GenTLSConfig(tc)
if err != nil {
err := &configErr{tk, err.Error()}
return nil, nil, err
}
// For clusters/gateways, we will force strict verification. We also act
// as both client and server, so will mirror the rootCA to the
// clientCA pool.
config.ClientAuth = tls.RequireAndVerifyClientCert
config.RootCAs = config.ClientCAs
return config, tc, nil
}
func parseGateways(v interface{}, errors *[]error, warnings *[]error) ([]*RemoteGatewayOpts, error) {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
// Make sure we have an array
ga, ok := v.([]interface{})
if !ok {
return nil, &configErr{tk, fmt.Sprintf("Expected gateways field to be an array, got %T", v)}
}
gateways := []*RemoteGatewayOpts{}
for _, g := range ga {
tk, g = unwrapValue(g, <)
// Check its a map/struct
gm, ok := g.(map[string]interface{})
if !ok {
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected gateway entry to be a map/struct, got %v", g)})
continue
}
gateway := &RemoteGatewayOpts{}
for k, v := range gm {
tk, v = unwrapValue(v, <)
switch strings.ToLower(k) {
case "name":
gateway.Name = v.(string)
case "tls":
tls, tlsopts, err := getTLSConfig(tk)
if err != nil {
*errors = append(*errors, err)
continue
}
gateway.TLSConfig = tls
gateway.TLSTimeout = tlsopts.Timeout
case "url":
url, err := parseURL(v.(string), "gateway")
if err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
gateway.URLs = append(gateway.URLs, url)
case "urls":
urls, errs := parseURLs(v.([]interface{}), "gateway")
if errs != nil {
*errors = append(*errors, errs...)
continue
}
gateway.URLs = urls
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: k,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
gateways = append(gateways, gateway)
}
return gateways, nil
}
// Sets cluster's permissions based on given pub/sub permissions,
// doing the appropriate translation.
func setClusterPermissions(opts *ClusterOpts, perms *Permissions) {
// Import is whether or not we will send a SUB for interest to the other side.
// Export is whether or not we will accept a SUB from the remote for a given subject.
// Both only effect interest registration.
// The parsing sets Import into Publish and Export into Subscribe, convert
// accordingly.
opts.Permissions = &RoutePermissions{
Import: perms.Publish,
Export: perms.Subscribe,
}
}
// Temp structures to hold account import and export defintions since they need
// to be processed after being parsed.
type export struct {
acc *Account
sub string
accs []string
rt ServiceRespType
lat *serviceLatency
rthr time.Duration
}
type importStream struct {
acc *Account
an string
sub string
pre string
}
type importService struct {
acc *Account
an string
sub string
to string
share bool
}
// Checks if an account name is reserved.
func isReservedAccount(name string) bool {
return name == globalAccountName
}
// parseAccounts will parse the different accounts syntax.
func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]error) error {
var (
importStreams []*importStream
importServices []*importService
exportStreams []*export
exportServices []*export
lt token
)
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
switch vv := v.(type) {
// Simple array of account names.
case []interface{}, []string:
m := make(map[string]struct{}, len(v.([]interface{})))
for _, n := range v.([]interface{}) {
tk, name := unwrapValue(n, <)
ns := name.(string)
// Check for reserved names.
if isReservedAccount(ns) {
err := &configErr{tk, fmt.Sprintf("%q is a Reserved Account", ns)}
*errors = append(*errors, err)
continue
}
if _, ok := m[ns]; ok {
err := &configErr{tk, fmt.Sprintf("Duplicate Account Entry: %s", ns)}
*errors = append(*errors, err)
continue
}
opts.Accounts = append(opts.Accounts, NewAccount(ns))
m[ns] = struct{}{}
}
// More common map entry
case map[string]interface{}:
// Track users across accounts, must be unique across
// accounts and nkeys vs users.
uorn := make(map[string]struct{})
for aname, mv := range vv {
tk, amv := unwrapValue(mv, <)
// Skip referenced config vars within the account block.
if tk.IsUsedVariable() {
continue
}
// These should be maps.
mv, ok := amv.(map[string]interface{})
if !ok {
err := &configErr{tk, "Expected map entries for accounts"}
*errors = append(*errors, err)
continue
}
if isReservedAccount(aname) {
err := &configErr{tk, fmt.Sprintf("%q is a Reserved Account", aname)}
*errors = append(*errors, err)
continue
}
acc := NewAccount(aname)
opts.Accounts = append(opts.Accounts, acc)
for k, v := range mv {
tk, mv := unwrapValue(v, <)
switch strings.ToLower(k) {
case "nkey":
nk, ok := mv.(string)
if !ok || !nkeys.IsValidPublicAccountKey(nk) {
err := &configErr{tk, fmt.Sprintf("Not a valid public nkey for an account: %q", mv)}
*errors = append(*errors, err)
continue
}
acc.Nkey = nk
case "imports":
streams, services, err := parseAccountImports(tk, acc, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
importStreams = append(importStreams, streams...)
importServices = append(importServices, services...)
case "exports":
streams, services, err := parseAccountExports(tk, acc, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
exportStreams = append(exportStreams, streams...)
exportServices = append(exportServices, services...)
case "jetstream":
err := parseJetStreamForAccount(mv, acc, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
case "users":
nkeys, users, err := parseUsers(mv, opts, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
for _, u := range users {
if _, ok := uorn[u.Username]; ok {
err := &configErr{tk, fmt.Sprintf("Duplicate user %q detected", u.Username)}
*errors = append(*errors, err)
continue
}
uorn[u.Username] = struct{}{}
u.Account = acc
}
opts.Users = append(opts.Users, users...)
for _, u := range nkeys {
if _, ok := uorn[u.Nkey]; ok {
err := &configErr{tk, fmt.Sprintf("Duplicate nkey %q detected", u.Nkey)}
*errors = append(*errors, err)
continue
}
uorn[u.Nkey] = struct{}{}
u.Account = acc
}
opts.Nkeys = append(opts.Nkeys, nkeys...)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: k,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
}
}
lt = tk
// Bail already if there are previous errors.
if len(*errors) > 0 {
return nil
}
// Parse Imports and Exports here after all accounts defined.
// Do exports first since they need to be defined for imports to succeed
// since we do permissions checks.
// Create a lookup map for accounts lookups.
am := make(map[string]*Account, len(opts.Accounts))
for _, a := range opts.Accounts {
am[a.Name] = a
}
// Do stream exports
for _, stream := range exportStreams {
// Make array of accounts if applicable.
var accounts []*Account
for _, an := range stream.accs {
ta := am[an]
if ta == nil {
msg := fmt.Sprintf("%q account not defined for stream export", an)
*errors = append(*errors, &configErr{tk, msg})
continue
}
accounts = append(accounts, ta)
}
if err := stream.acc.AddStreamExport(stream.sub, accounts); err != nil {
msg := fmt.Sprintf("Error adding stream export %q: %v", stream.sub, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
}
for _, service := range exportServices {
// Make array of accounts if applicable.
var accounts []*Account
for _, an := range service.accs {
ta := am[an]
if ta == nil {
msg := fmt.Sprintf("%q account not defined for service export", an)
*errors = append(*errors, &configErr{tk, msg})
continue
}
accounts = append(accounts, ta)
}
if err := service.acc.AddServiceExportWithResponse(service.sub, service.rt, accounts); err != nil {
msg := fmt.Sprintf("Error adding service export %q: %v", service.sub, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
if service.rthr != 0 {
// Response threshold was set in options.
if err := service.acc.SetServiceExportResponseThreshold(service.sub, service.rthr); err != nil {
msg := fmt.Sprintf("Error adding service export response threshold for %q: %v", service.sub, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
}
if service.lat != nil {
if opts.SystemAccount == "" {
msg := fmt.Sprintf("Error adding service latency sampling for %q: %v", service.sub, ErrNoSysAccount.Error())
*errors = append(*errors, &configErr{tk, msg})
continue
}
if err := service.acc.TrackServiceExportWithSampling(service.sub, service.lat.subject, int(service.lat.sampling)); err != nil {
msg := fmt.Sprintf("Error adding service latency sampling for %q on subject %q: %v", service.sub, service.lat.subject, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
}
}
for _, stream := range importStreams {
ta := am[stream.an]
if ta == nil {
msg := fmt.Sprintf("%q account not defined for stream import", stream.an)
*errors = append(*errors, &configErr{tk, msg})
continue
}
if err := stream.acc.AddStreamImport(ta, stream.sub, stream.pre); err != nil {
msg := fmt.Sprintf("Error adding stream import %q: %v", stream.sub, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
}
for _, service := range importServices {
ta := am[service.an]
if ta == nil {
msg := fmt.Sprintf("%q account not defined for service import", service.an)
*errors = append(*errors, &configErr{tk, msg})
continue
}
if service.to == "" {
service.to = service.sub
}
if err := service.acc.AddServiceImport(ta, service.to, service.sub); err != nil {
msg := fmt.Sprintf("Error adding service import %q: %v", service.sub, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
if err := service.acc.SetServiceImportSharing(ta, service.sub, service.share); err != nil {
msg := fmt.Sprintf("Error setting service import sharing %q: %v", service.sub, err)
*errors = append(*errors, &configErr{tk, msg})
continue
}
}
return nil
}
// Parse the account exports
func parseAccountExports(v interface{}, acc *Account, errors, warnings *[]error) ([]*export, []*export, error) {
var lt token
defer convertPanicToErrorList(<, errors)
// This should be an array of objects/maps.
tk, v := unwrapValue(v, <)
ims, ok := v.([]interface{})
if !ok {
return nil, nil, &configErr{tk, fmt.Sprintf("Exports should be an array, got %T", v)}
}
var services []*export
var streams []*export
for _, v := range ims {
// Should have stream or service
stream, service, err := parseExportStreamOrService(v, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
if service != nil {
service.acc = acc
services = append(services, service)
}
if stream != nil {
stream.acc = acc
streams = append(streams, stream)
}
}
return streams, services, nil
}
// Parse the account imports
func parseAccountImports(v interface{}, acc *Account, errors, warnings *[]error) ([]*importStream, []*importService, error) {
var lt token
defer convertPanicToErrorList(<, errors)
// This should be an array of objects/maps.
tk, v := unwrapValue(v, <)
ims, ok := v.([]interface{})
if !ok {
return nil, nil, &configErr{tk, fmt.Sprintf("Imports should be an array, got %T", v)}
}
var services []*importService
var streams []*importStream
svcSubjects := map[string]*importService{}
for _, v := range ims {
// Should have stream or service
stream, service, err := parseImportStreamOrService(v, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
if service != nil {
if dup := svcSubjects[service.to]; dup != nil {
tk, _ := unwrapValue(v, <)
err := &configErr{tk,
fmt.Sprintf("Duplicate service import subject %q, previously used in import for account %q, subject %q",
service.to, dup.an, dup.sub)}
*errors = append(*errors, err)
continue
}
svcSubjects[service.to] = service
service.acc = acc
services = append(services, service)
}
if stream != nil {
stream.acc = acc
streams = append(streams, stream)
}
}
return streams, services, nil
}
// Helper to parse an embedded account description for imported services or streams.
func parseAccount(v map[string]interface{}, errors, warnings *[]error) (string, string, error) {
var lt token
defer convertPanicToErrorList(<, errors)
var accountName, subject string
for mk, mv := range v {
tk, mv := unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "account":
accountName = mv.(string)
case "subject":
subject = mv.(string)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
return accountName, subject, nil
}
// Parse an export stream or service.
// e.g.
// {stream: "public.>"} # No accounts means public.
// {stream: "synadia.private.>", accounts: [cncf, natsio]}
// {service: "pub.request"} # No accounts means public.
// {service: "pub.special.request", accounts: [nats.io]}
func parseExportStreamOrService(v interface{}, errors, warnings *[]error) (*export, *export, error) {
var (
curStream *export
curService *export
accounts []string
rt ServiceRespType
rtSeen bool
rtToken token
lat *serviceLatency
threshSeen bool
thresh time.Duration
latToken token
lt token
)
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
vv, ok := v.(map[string]interface{})
if !ok {
return nil, nil, &configErr{tk, fmt.Sprintf("Export Items should be a map with type entry, got %T", v)}
}
for mk, mv := range vv {
tk, mv := unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "stream":
if curService != nil {
err := &configErr{tk, fmt.Sprintf("Detected stream %q but already saw a service", mv)}
*errors = append(*errors, err)
continue
}
if rtToken != nil {
err := &configErr{rtToken, "Detected response directive on non-service"}
*errors = append(*errors, err)
continue
}
if latToken != nil {
err := &configErr{latToken, "Detected latency directive on non-service"}
*errors = append(*errors, err)
continue
}
mvs, ok := mv.(string)
if !ok {
err := &configErr{tk, fmt.Sprintf("Expected stream name to be string, got %T", mv)}
*errors = append(*errors, err)
continue
}
curStream = &export{sub: mvs}
if accounts != nil {
curStream.accs = accounts
}
case "service":
if curStream != nil {
err := &configErr{tk, fmt.Sprintf("Detected service %q but already saw a stream", mv)}
*errors = append(*errors, err)
continue
}
mvs, ok := mv.(string)
if !ok {
err := &configErr{tk, fmt.Sprintf("Expected service name to be string, got %T", mv)}
*errors = append(*errors, err)
continue
}
curService = &export{sub: mvs}
if accounts != nil {
curService.accs = accounts
}
if rtSeen {
curService.rt = rt
}
if lat != nil {
curService.lat = lat
}
if threshSeen {
curService.rthr = thresh
}
case "response", "response_type":
if rtSeen {
err := &configErr{tk, "Duplicate response type definition"}
*errors = append(*errors, err)
continue
}
rtSeen = true
rtToken = tk
mvs, ok := mv.(string)
if !ok {
err := &configErr{tk, fmt.Sprintf("Expected response type to be string, got %T", mv)}
*errors = append(*errors, err)
continue
}
switch strings.ToLower(mvs) {
case "single", "singleton":
rt = Singleton
case "stream":
rt = Streamed
case "chunk", "chunked":
rt = Chunked
default:
err := &configErr{tk, fmt.Sprintf("Unknown response type: %q", mvs)}
*errors = append(*errors, err)
continue
}
if curService != nil {
curService.rt = rt
}
if curStream != nil {
err := &configErr{tk, "Detected response directive on non-service"}
*errors = append(*errors, err)
}
case "threshold", "response_threshold", "response_max_time", "response_time":
if threshSeen {
err := &configErr{tk, "Duplicate response threshold detected"}
*errors = append(*errors, err)
continue
}
threshSeen = true
mvs, ok := mv.(string)
if !ok {
err := &configErr{tk, fmt.Sprintf("Expected response threshold to be a parseable time duration, got %T", mv)}
*errors = append(*errors, err)
continue
}
var err error
thresh, err = time.ParseDuration(mvs)
if err != nil {
err := &configErr{tk, fmt.Sprintf("Expected response threshold to be a parseable time duration, got %q", mvs)}
*errors = append(*errors, err)
continue
}
if curService != nil {
curService.rthr = thresh
}
if curStream != nil {
err := &configErr{tk, "Detected response directive on non-service"}
*errors = append(*errors, err)
}
case "accounts":
for _, iv := range mv.([]interface{}) {
_, mv := unwrapValue(iv, <)
accounts = append(accounts, mv.(string))
}
if curStream != nil {
curStream.accs = accounts
} else if curService != nil {
curService.accs = accounts
}
case "latency":
latToken = tk
var err error
lat, err = parseServiceLatency(tk, mv)
if err != nil {
*errors = append(*errors, err)
continue
}
if curStream != nil {
err = &configErr{tk, "Detected latency directive on non-service"}
*errors = append(*errors, err)
continue
}
if curService != nil {
curService.lat = lat
}
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
return curStream, curService, nil
}
// parseServiceLatency returns a latency config block.
func parseServiceLatency(root token, v interface{}) (l *serviceLatency, retErr error) {
var lt token
defer convertPanicToError(<, &retErr)
if subject, ok := v.(string); ok {
return &serviceLatency{
subject: subject,
sampling: DEFAULT_SERVICE_LATENCY_SAMPLING,
}, nil
}
latency, ok := v.(map[string]interface{})
if !ok {
return nil, &configErr{token: root,
reason: fmt.Sprintf("Expected latency entry to be a map/struct or string, got %T", v)}
}
sl := serviceLatency{
sampling: DEFAULT_SERVICE_LATENCY_SAMPLING,
}
// Read sampling value.
if v, ok := latency["sampling"]; ok {
tk, v := unwrapValue(v, <)
var sample int64
switch vv := v.(type) {
case int64:
// Sample is an int, like 50.
sample = vv
case string:
// Sample is a string, like "50%".
s := strings.TrimSuffix(vv, "%")
n, err := strconv.Atoi(s)
if err != nil {
return nil, &configErr{token: tk,
reason: fmt.Sprintf("Failed to parse latency sample: %v", err)}
}
sample = int64(n)
default:
return nil, &configErr{token: tk,
reason: fmt.Sprintf("Expected latency sample to be a string or map/struct, got %T", v)}
}
if sample < 1 || sample > 100 {
return nil, &configErr{token: tk,
reason: ErrBadSampling.Error()}
}
sl.sampling = int8(sample)
}
// Read subject value.
v, ok = latency["subject"]
if !ok {
return nil, &configErr{token: root,
reason: "Latency subject required, but missing"}
}
tk, v := unwrapValue(v, <)
subject, ok := v.(string)
if !ok {
return nil, &configErr{token: tk,
reason: fmt.Sprintf("Expected latency subject to be a string, got %T", subject)}
}
sl.subject = subject
return &sl, nil
}
// Parse an import stream or service.
// e.g.
// {stream: {account: "synadia", subject:"public.synadia"}, prefix: "imports.synadia"}
// {stream: {account: "synadia", subject:"synadia.private.*"}}
// {service: {account: "synadia", subject: "pub.special.request"}, to: "synadia.request"}
func parseImportStreamOrService(v interface{}, errors, warnings *[]error) (*importStream, *importService, error) {
var (
curStream *importStream
curService *importService
pre, to string
share bool
lt token
)
defer convertPanicToErrorList(<, errors)
tk, mv := unwrapValue(v, <)
vv, ok := mv.(map[string]interface{})
if !ok {
return nil, nil, &configErr{tk, fmt.Sprintf("Import Items should be a map with type entry, got %T", mv)}
}
for mk, mv := range vv {
tk, mv := unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "stream":
if curService != nil {
err := &configErr{tk, "Detected stream but already saw a service"}
*errors = append(*errors, err)
continue
}
ac, ok := mv.(map[string]interface{})
if !ok {
err := &configErr{tk, fmt.Sprintf("Stream entry should be an account map, got %T", mv)}
*errors = append(*errors, err)
continue
}
// Make sure this is a map with account and subject
accountName, subject, err := parseAccount(ac, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
if accountName == "" || subject == "" {
err := &configErr{tk, "Expect an account name and a subject"}
*errors = append(*errors, err)
continue
}
curStream = &importStream{an: accountName, sub: subject}
if pre != "" {
curStream.pre = pre
}
case "service":
if curStream != nil {
err := &configErr{tk, "Detected service but already saw a stream"}
*errors = append(*errors, err)
continue
}
ac, ok := mv.(map[string]interface{})
if !ok {
err := &configErr{tk, fmt.Sprintf("Service entry should be an account map, got %T", mv)}
*errors = append(*errors, err)
continue
}
// Make sure this is a map with account and subject
accountName, subject, err := parseAccount(ac, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
if accountName == "" || subject == "" {
err := &configErr{tk, "Expect an account name and a subject"}
*errors = append(*errors, err)
continue
}
curService = &importService{an: accountName, sub: subject}
if to != "" {
curService.to = to
} else {
curService.to = subject
}
curService.share = share
case "prefix":
pre = mv.(string)
if curStream != nil {
curStream.pre = pre
}
case "to":
to = mv.(string)
if curService != nil {
curService.to = to
}
case "share":
share = mv.(bool)
if curService != nil {
curService.share = share
}
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
return curStream, curService, nil
}
// Helper function to parse Authorization configs.
func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings *[]error) (*authorization, error) {
var (
am map[string]interface{}
tk token
lt token
auth = &authorization{}
)
defer convertPanicToErrorList(<, errors)
_, v = unwrapValue(v, <)
am = v.(map[string]interface{})
for mk, mv := range am {
tk, mv = unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "user", "username":
auth.user = mv.(string)
case "pass", "password":
auth.pass = mv.(string)
case "token":
auth.token = mv.(string)
case "timeout":
at := float64(1)
switch mv := mv.(type) {
case int64:
at = float64(mv)
case float64:
at = mv
}
auth.timeout = at
case "users":
nkeys, users, err := parseUsers(tk, opts, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.users = users
auth.nkeys = nkeys
case "default_permission", "default_permissions", "permissions":
permissions, err := parseUserPermissions(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.defaultPermissions = permissions
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
continue
}
// Now check for permission defaults with multiple users, etc.
if auth.users != nil && auth.defaultPermissions != nil {
for _, user := range auth.users {
if user.Permissions == nil {
user.Permissions = auth.defaultPermissions
}
}
}
}
return auth, nil
}
// Helper function to parse multiple users array with optional permissions.
func parseUsers(mv interface{}, opts *Options, errors *[]error, warnings *[]error) ([]*NkeyUser, []*User, error) {
var (
tk token
lt token
keys []*NkeyUser
users = []*User{}
)
defer convertPanicToErrorList(<, errors)
tk, mv = unwrapValue(mv, <)
// Make sure we have an array
uv, ok := mv.([]interface{})
if !ok {
return nil, nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)}
}
for _, u := range uv {
tk, u = unwrapValue(u, <)
// Check its a map/struct
um, ok := u.(map[string]interface{})
if !ok {
err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)}
*errors = append(*errors, err)
continue
}
var (
user = &User{}
nkey = &NkeyUser{}
perms *Permissions
err error
)
for k, v := range um {
// Also needs to unwrap first
tk, v = unwrapValue(v, <)
switch strings.ToLower(k) {
case "nkey":
nkey.Nkey = v.(string)
case "user", "username":
user.Username = v.(string)
case "pass", "password":
user.Password = v.(string)
case "permission", "permissions", "authorization":
perms, err = parseUserPermissions(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: k,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
continue
}
}
}
// Place perms if we have them.
if perms != nil {
// nkey takes precedent.
if nkey.Nkey != "" {
nkey.Permissions = perms
} else {
user.Permissions = perms
}
}
// Check to make sure we have at least an nkey or username <password> defined.
if nkey.Nkey == "" && user.Username == "" {
return nil, nil, &configErr{tk, "User entry requires a user"}
} else if nkey.Nkey != "" {
// Make sure the nkey a proper public nkey for a user..
if !nkeys.IsValidPublicUserKey(nkey.Nkey) {
return nil, nil, &configErr{tk, "Not a valid public nkey for a user"}
}
// If we have user or password defined here that is an error.
if user.Username != "" || user.Password != "" {
return nil, nil, &configErr{tk, "Nkey users do not take usernames or passwords"}
}
keys = append(keys, nkey)
} else {
users = append(users, user)
}
}
return keys, users, nil
}
// Helper function to parse user/account permissions
func parseUserPermissions(mv interface{}, errors, warnings *[]error) (*Permissions, error) {
var (
tk token
lt token
p = &Permissions{}
)
defer convertPanicToErrorList(<, errors)
tk, mv = unwrapValue(mv, <)
pm, ok := mv.(map[string]interface{})
if !ok {
return nil, &configErr{tk, fmt.Sprintf("Expected permissions to be a map/struct, got %+v", mv)}
}
for k, v := range pm {
tk, mv = unwrapValue(v, <)
switch strings.ToLower(k) {
// For routes:
// Import is Publish
// Export is Subscribe
case "pub", "publish", "import":
perms, err := parseVariablePermissions(mv, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Publish = perms
case "sub", "subscribe", "export":
perms, err := parseVariablePermissions(mv, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Subscribe = perms
case "publish_allow_responses", "allow_responses":
rp := &ResponsePermission{
MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS,
Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION,
}
// Try boolean first
responses, ok := mv.(bool)
if ok {
if responses {
p.Response = rp
}
} else {
p.Response = parseAllowResponses(v, errors, warnings)
}
if p.Response != nil {
if p.Publish == nil {
p.Publish = &SubjectPermission{}
}
if p.Publish.Allow == nil {
// We turn off the blanket allow statement.
p.Publish.Allow = []string{}
}
}
default:
if !tk.IsUsedVariable() {
err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing permissions", k)}
*errors = append(*errors, err)
}
}
}
return p, nil
}
// Top level parser for authorization configurations.
func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
switch vv := v.(type) {
case map[string]interface{}:
// New style with allow and/or deny properties.
return parseSubjectPermission(vv, errors, warnings)
default:
// Old style
return parseOldPermissionStyle(v, errors, warnings)
}
}
// Helper function to parse subject singletons and/or arrays
func parseSubjects(v interface{}, errors, warnings *[]error) ([]string, error) {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
var subjects []string
switch vv := v.(type) {
case string:
subjects = append(subjects, vv)
case []string:
subjects = vv
case []interface{}:
for _, i := range vv {
tk, i := unwrapValue(i, <)
subject, ok := i.(string)
if !ok {
return nil, &configErr{tk, "Subject in permissions array cannot be cast to string"}
}
subjects = append(subjects, subject)
}
default:
return nil, &configErr{tk, fmt.Sprintf("Expected subject permissions to be a subject, or array of subjects, got %T", v)}
}
if err := checkSubjectArray(subjects); err != nil {
return nil, &configErr{tk, err.Error()}
}
return subjects, nil
}
// Helper function to parse a ResponsePermission.
func parseAllowResponses(v interface{}, errors, warnings *[]error) *ResponsePermission {
var lt token
defer convertPanicToErrorList(<, errors)
tk, v := unwrapValue(v, <)
// Check if this is a map.
pm, ok := v.(map[string]interface{})
if !ok {
err := &configErr{tk, "error parsing response permissions, expected a boolean or a map"}
*errors = append(*errors, err)
return nil
}
rp := &ResponsePermission{
MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS,
Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION,
}
for k, v := range pm {
tk, v = unwrapValue(v, <)
switch strings.ToLower(k) {
case "max", "max_msgs", "max_messages", "max_responses":
max := int(v.(int64))
// Negative values are accepted (mean infinite), and 0
// means default value (set above).
if max != 0 {
rp.MaxMsgs = max
}
case "expires", "expiration", "ttl":
wd, ok := v.(string)
if ok {
ttl, err := time.ParseDuration(wd)
if err != nil {
err := &configErr{tk, fmt.Sprintf("error parsing expires: %v", err)}
*errors = append(*errors, err)
return nil
}
// Negative values are accepted (mean infinite), and 0
// means default value (set above).
if ttl != 0 {
rp.Expires = ttl
}
} else {
err := &configErr{tk, "error parsing expires, not a duration string"}
*errors = append(*errors, err)
return nil
}
default:
if !tk.IsUsedVariable() {
err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing permissions", k)}
*errors = append(*errors, err)
}
}
}
return rp
}
// Helper function to parse old style authorization configs.
func parseOldPermissionStyle(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
subjects, err := parseSubjects(v, errors, warnings)
if err != nil {
return nil, err
}
return &SubjectPermission{Allow: subjects}, nil
}
// Helper function to parse new style authorization into a SubjectPermission with Allow and Deny.
func parseSubjectPermission(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
var lt token
defer convertPanicToErrorList(<, errors)
m := v.(map[string]interface{})
if len(m) == 0 {
return nil, nil
}
p := &SubjectPermission{}
for k, v := range m {
tk, _ := unwrapValue(v, <)
switch strings.ToLower(k) {
case "allow":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Allow = subjects
case "deny":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Deny = subjects
default:
if !tk.IsUsedVariable() {
err := &configErr{tk, fmt.Sprintf("Unknown field name %q parsing subject permissions, only 'allow' or 'deny' are permitted", k)}
*errors = append(*errors, err)
}
}
}
return p, nil
}
// Helper function to validate subjects, etc for account permissioning.
func checkSubjectArray(sa []string) error {
for _, s := range sa {
if !IsValidSubject(s) {
return fmt.Errorf("subject %q is not a valid subject", s)
}
}
return nil
}
// PrintTLSHelpAndDie prints TLS usage and exits.
func PrintTLSHelpAndDie() {
fmt.Printf("%s", tlsUsage)
for k := range cipherMap {
fmt.Printf(" %s\n", k)
}
fmt.Printf("\nAvailable curve preferences include:\n")
for k := range curvePreferenceMap {
fmt.Printf(" %s\n", k)
}
os.Exit(0)
}
func parseCipher(cipherName string) (uint16, error) {
cipher, exists := cipherMap[cipherName]
if !exists {
return 0, fmt.Errorf("unrecognized cipher %s", cipherName)
}
return cipher, nil
}
func parseCurvePreferences(curveName string) (tls.CurveID, error) {
curve, exists := curvePreferenceMap[curveName]
if !exists {
return 0, fmt.Errorf("unrecognized curve preference %s", curveName)
}
return curve, nil
}
// Helper function to parse TLS configs.
func parseTLS(v interface{}) (t *TLSConfigOpts, retErr error) {
var (
tlsm map[string]interface{}
tc = TLSConfigOpts{}
lt token
)
defer convertPanicToError(<, &retErr)
_, v = unwrapValue(v, <)
tlsm = v.(map[string]interface{})
for mk, mv := range tlsm {
tk, mv := unwrapValue(mv, <)
switch strings.ToLower(mk) {
case "cert_file":
certFile, ok := mv.(string)
if !ok {
return nil, &configErr{tk, "error parsing tls config, expected 'cert_file' to be filename"}
}
tc.CertFile = certFile
case "key_file":
keyFile, ok := mv.(string)
if !ok {
return nil, &configErr{tk, "error parsing tls config, expected 'key_file' to be filename"}
}
tc.KeyFile = keyFile
case "ca_file":
caFile, ok := mv.(string)
if !ok {
return nil, &configErr{tk, "error parsing tls config, expected 'ca_file' to be filename"}
}
tc.CaFile = caFile
case "insecure":
insecure, ok := mv.(bool)
if !ok {
return nil, &configErr{tk, "error parsing tls config, expected 'insecure' to be a boolean"}
}
tc.Insecure = insecure
case "verify":
verify, ok := mv.(bool)
if !ok {
return nil, &configErr{tk, "error parsing tls config, expected 'verify' to be a boolean"}
}
tc.Verify = verify
case "verify_and_map":
verify, ok := mv.(bool)
if !ok {
return nil, &configErr{tk, "error parsing tls config, expected 'verify_and_map' to be a boolean"}
}
tc.Verify = verify
tc.Map = verify
case "cipher_suites":
ra := mv.([]interface{})
if len(ra) == 0 {
return nil, &configErr{tk, "error parsing tls config, 'cipher_suites' cannot be empty"}
}
tc.Ciphers = make([]uint16, 0, len(ra))
for _, r := range ra {
tk, r := unwrapValue(r, <)
cipher, err := parseCipher(r.(string))
if err != nil {
return nil, &configErr{tk, err.Error()}
}
tc.Ciphers = append(tc.Ciphers, cipher)
}
case "curve_preferences":
ra := mv.([]interface{})
if len(ra) == 0 {
return nil, &configErr{tk, "error parsing tls config, 'curve_preferences' cannot be empty"}
}
tc.CurvePreferences = make([]tls.CurveID, 0, len(ra))
for _, r := range ra {
tk, r := unwrapValue(r, <)
cps, err := parseCurvePreferences(r.(string))
if err != nil {
return nil, &configErr{tk, err.Error()}
}
tc.CurvePreferences = append(tc.CurvePreferences, cps)
}
case "timeout":
at := float64(0)
switch mv := mv.(type) {
case int64:
at = float64(mv)
case float64:
at = mv
}
tc.Timeout = at
default:
return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, unknown field [%q]", mk)}
}
}
// If cipher suites were not specified then use the defaults
if tc.Ciphers == nil {
tc.Ciphers = defaultCipherSuites()
}
// If curve preferences were not specified, then use the defaults
if tc.CurvePreferences == nil {
tc.CurvePreferences = defaultCurvePreferences()
}
return &tc, nil
}
// GenTLSConfig loads TLS related configuration parameters.
func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {
// Create the tls.Config from our options before including the certs.
// It will determine the cipher suites that we prefer.
// FIXME(dlc) change if ARM based.
config := tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: tc.Ciphers,
PreferServerCipherSuites: true,
CurvePreferences: tc.CurvePreferences,
InsecureSkipVerify: tc.Insecure,
}
switch {
case tc.CertFile != "" && tc.KeyFile == "":
return nil, fmt.Errorf("missing 'key_file' in TLS configuration")
case tc.CertFile == "" && tc.KeyFile != "":
return nil, fmt.Errorf("missing 'cert_file' in TLS configuration")
case tc.CertFile != "" && tc.KeyFile != "":
// Now load in cert and private key
cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
if err != nil {
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("error parsing certificate: %v", err)
}
config.Certificates = []tls.Certificate{cert}
}
// Require client certificates as needed
if tc.Verify {
config.ClientAuth = tls.RequireAndVerifyClientCert
}
// Add in CAs if applicable.
if tc.CaFile != "" {
rootPEM, err := ioutil.ReadFile(tc.CaFile)
if err != nil || rootPEM == nil {
return nil, err
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
return nil, fmt.Errorf("failed to parse root ca certificate")
}
config.ClientCAs = pool
}
return &config, nil
}
// MergeOptions will merge two options giving preference to the flagOpts
// if the item is present.
func MergeOptions(fileOpts, flagOpts *Options) *Options {
if fileOpts == nil {
return flagOpts
}
if flagOpts == nil {
return fileOpts
}
// Merge the two, flagOpts override
opts := *fileOpts
if flagOpts.Port != 0 {
opts.Port = flagOpts.Port
}
if flagOpts.Host != "" {
opts.Host = flagOpts.Host
}
if flagOpts.ClientAdvertise != "" {
opts.ClientAdvertise = flagOpts.ClientAdvertise
}
if flagOpts.Username != "" {
opts.Username = flagOpts.Username
}
if flagOpts.Password != "" {
opts.Password = flagOpts.Password
}
if flagOpts.Authorization != "" {
opts.Authorization = flagOpts.Authorization
}
if flagOpts.HTTPPort != 0 {
opts.HTTPPort = flagOpts.HTTPPort
}
if flagOpts.Debug {
opts.Debug = true
}
if flagOpts.Trace {
opts.Trace = true
}
if flagOpts.Logtime {
opts.Logtime = true
}
if flagOpts.LogFile != "" {
opts.LogFile = flagOpts.LogFile
}
if flagOpts.PidFile != "" {
opts.PidFile = flagOpts.PidFile
}
if flagOpts.PortsFileDir != "" {
opts.PortsFileDir = flagOpts.PortsFileDir
}
if flagOpts.ProfPort != 0 {
opts.ProfPort = flagOpts.ProfPort
}
if flagOpts.Cluster.ListenStr != "" {
opts.Cluster.ListenStr = flagOpts.Cluster.ListenStr
}
if flagOpts.Cluster.NoAdvertise {
opts.Cluster.NoAdvertise = true
}
if flagOpts.Cluster.ConnectRetries != 0 {
opts.Cluster.ConnectRetries = flagOpts.Cluster.ConnectRetries
}
if flagOpts.Cluster.Advertise != "" {
opts.Cluster.Advertise = flagOpts.Cluster.Advertise
}
if flagOpts.RoutesStr != "" {
mergeRoutes(&opts, flagOpts)
}
return &opts
}
// RoutesFromStr parses route URLs from a string
func RoutesFromStr(routesStr string) []*url.URL {
routes := strings.Split(routesStr, ",")
if len(routes) == 0 {
return nil
}
routeUrls := []*url.URL{}
for _, r := range routes {
r = strings.TrimSpace(r)
u, _ := url.Parse(r)
routeUrls = append(routeUrls, u)
}
return routeUrls
}
// This will merge the flag routes and override anything that was present.
func mergeRoutes(opts, flagOpts *Options) {
routeUrls := RoutesFromStr(flagOpts.RoutesStr)
if routeUrls == nil {
return
}
opts.Routes = routeUrls
opts.RoutesStr = flagOpts.RoutesStr
}
// RemoveSelfReference removes this server from an array of routes
func RemoveSelfReference(clusterPort int, routes []*url.URL) ([]*url.URL, error) {
var cleanRoutes []*url.URL
cport := strconv.Itoa(clusterPort)
selfIPs, err := getInterfaceIPs()
if err != nil {
return nil, err
}
for _, r := range routes {
host, port, err := net.SplitHostPort(r.Host)
if err != nil {
return nil, err
}
ipList, err := getURLIP(host)
if err != nil {
return nil, err
}
if cport == port && isIPInList(selfIPs, ipList) {
continue
}
cleanRoutes = append(cleanRoutes, r)
}
return cleanRoutes, nil
}
func isIPInList(list1 []net.IP, list2 []net.IP) bool {
for _, ip1 := range list1 {
for _, ip2 := range list2 {
if ip1.Equal(ip2) {
return true
}
}
}
return false
}
func getURLIP(ipStr string) ([]net.IP, error) {
ipList := []net.IP{}
ip := net.ParseIP(ipStr)
if ip != nil {
ipList = append(ipList, ip)
return ipList, nil
}
hostAddr, err := net.LookupHost(ipStr)
if err != nil {
return nil, fmt.Errorf("Error looking up host with route hostname: %v", err)
}
for _, addr := range hostAddr {
ip = net.ParseIP(addr)
if ip != nil {
ipList = append(ipList, ip)
}
}
return ipList, nil
}
func getInterfaceIPs() ([]net.IP, error) {
var localIPs []net.IP
interfaceAddr, err := net.InterfaceAddrs()
if err != nil {
return nil, fmt.Errorf("Error getting self referencing address: %v", err)
}
for i := 0; i < len(interfaceAddr); i++ {
interfaceIP, _, _ := net.ParseCIDR(interfaceAddr[i].String())
if net.ParseIP(interfaceIP.String()) != nil {
localIPs = append(localIPs, interfaceIP)
} else {
return nil, fmt.Errorf("Error parsing self referencing address: %v", err)
}
}
return localIPs, nil
}
func setBaselineOptions(opts *Options) {
// Setup non-standard Go defaults
if opts.Host == "" {
opts.Host = DEFAULT_HOST
}
if opts.HTTPHost == "" {
// Default to same bind from server if left undefined
opts.HTTPHost = opts.Host
}
if opts.Port == 0 {
opts.Port = DEFAULT_PORT
} else if opts.Port == RANDOM_PORT {
// Choose randomly inside of net.Listen
opts.Port = 0
}
if opts.MaxConn == 0 {
opts.MaxConn = DEFAULT_MAX_CONNECTIONS
}
if opts.PingInterval == 0 {
opts.PingInterval = DEFAULT_PING_INTERVAL
}
if opts.MaxPingsOut == 0 {
opts.MaxPingsOut = DEFAULT_PING_MAX_OUT
}
if opts.TLSTimeout == 0 {
opts.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
}
if opts.AuthTimeout == 0 {
opts.AuthTimeout = float64(AUTH_TIMEOUT) / float64(time.Second)
}
if opts.Cluster.Port != 0 {
if opts.Cluster.Host == "" {
opts.Cluster.Host = DEFAULT_HOST
}
if opts.Cluster.TLSTimeout == 0 {
opts.Cluster.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
}
if opts.Cluster.AuthTimeout == 0 {
opts.Cluster.AuthTimeout = float64(AUTH_TIMEOUT) / float64(time.Second)
}
}
if opts.LeafNode.Port != 0 {
if opts.LeafNode.Host == "" {
opts.LeafNode.Host = DEFAULT_HOST
}
if opts.LeafNode.TLSTimeout == 0 {
opts.LeafNode.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
}
if opts.LeafNode.AuthTimeout == 0 {
opts.LeafNode.AuthTimeout = float64(AUTH_TIMEOUT) / float64(time.Second)
}
}
// Set baseline connect port for remotes.
for _, r := range opts.LeafNode.Remotes {
if r != nil {
for _, u := range r.URLs {
if u.Port() == "" {
u.Host = net.JoinHostPort(u.Host, strconv.Itoa(DEFAULT_LEAFNODE_PORT))
}
}
}
}
// Set this regardless of opts.LeafNode.Port
if opts.LeafNode.ReconnectInterval == 0 {
opts.LeafNode.ReconnectInterval = DEFAULT_LEAF_NODE_RECONNECT
}
if opts.MaxControlLine == 0 {
opts.MaxControlLine = MAX_CONTROL_LINE_SIZE
}
if opts.MaxPayload == 0 {
opts.MaxPayload = MAX_PAYLOAD_SIZE
}
if opts.MaxPending == 0 {
opts.MaxPending = MAX_PENDING_SIZE
}
if opts.WriteDeadline == time.Duration(0) {
opts.WriteDeadline = DEFAULT_FLUSH_DEADLINE
}
if opts.MaxClosedClients == 0 {
opts.MaxClosedClients = DEFAULT_MAX_CLOSED_CLIENTS
}
if opts.LameDuckDuration == 0 {
opts.LameDuckDuration = DEFAULT_LAME_DUCK_DURATION
}
if opts.Gateway.Port != 0 {
if opts.Gateway.Host == "" {
opts.Gateway.Host = DEFAULT_HOST
}
if opts.Gateway.TLSTimeout == 0 {
opts.Gateway.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
}
if opts.Gateway.AuthTimeout == 0 {
opts.Gateway.AuthTimeout = float64(AUTH_TIMEOUT) / float64(time.Second)
}
}
if opts.ConnectErrorReports == 0 {
opts.ConnectErrorReports = DEFAULT_CONNECT_ERROR_REPORTS
}
if opts.ReconnectErrorReports == 0 {
opts.ReconnectErrorReports = DEFAULT_RECONNECT_ERROR_REPORTS
}
// JetStream
if opts.JetStreamMaxMemory == 0 {
opts.JetStreamMaxMemory = -1
}
if opts.JetStreamMaxStore == 0 {
opts.JetStreamMaxStore = -1
}
}
// ConfigureOptions accepts a flag set and augment it with NATS Server
// specific flags. On success, an options structure is returned configured
// based on the selected flags and/or configuration file.
// The command line options take precedence to the ones in the configuration file.
func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, printTLSHelp func()) (*Options, error) {
opts := &Options{}
var (
showVersion bool
showHelp bool
showTLSHelp bool
signal string
configFile string
dbgAndTrace bool
trcAndVerboseTrc bool
dbgAndTrcAndVerboseTrc bool
err error
)
fs.BoolVar(&showHelp, "h", false, "Show this message.")
fs.BoolVar(&showHelp, "help", false, "Show this message.")
fs.IntVar(&opts.Port, "port", 0, "Port to listen on.")
fs.IntVar(&opts.Port, "p", 0, "Port to listen on.")
fs.StringVar(&opts.Host, "addr", "", "Network host to listen on.")
fs.StringVar(&opts.Host, "a", "", "Network host to listen on.")
fs.StringVar(&opts.Host, "net", "", "Network host to listen on.")
fs.StringVar(&opts.ClientAdvertise, "client_advertise", "", "Client URL to advertise to other servers.")
fs.BoolVar(&opts.Debug, "D", false, "Enable Debug logging.")
fs.BoolVar(&opts.Debug, "debug", false, "Enable Debug logging.")
fs.BoolVar(&opts.Trace, "V", false, "Enable Trace logging.")
fs.BoolVar(&trcAndVerboseTrc, "VV", false, "Enable Verbose Trace logging. (Traces system account as well)")
fs.BoolVar(&opts.Trace, "trace", false, "Enable Trace logging.")
fs.BoolVar(&dbgAndTrace, "DV", false, "Enable Debug and Trace logging.")
fs.BoolVar(&dbgAndTrcAndVerboseTrc, "DVV", false, "Enable Debug and Verbose Trace logging. (Traces system account as well)")
fs.BoolVar(&opts.Logtime, "T", true, "Timestamp log entries.")
fs.BoolVar(&opts.Logtime, "logtime", true, "Timestamp log entries.")
fs.StringVar(&opts.Username, "user", "", "Username required for connection.")
fs.StringVar(&opts.Password, "pass", "", "Password required for connection.")
fs.StringVar(&opts.Authorization, "auth", "", "Authorization token required for connection.")
fs.IntVar(&opts.HTTPPort, "m", 0, "HTTP Port for /varz, /connz endpoints.")
fs.IntVar(&opts.HTTPPort, "http_port", 0, "HTTP Port for /varz, /connz endpoints.")
fs.IntVar(&opts.HTTPSPort, "ms", 0, "HTTPS Port for /varz, /connz endpoints.")
fs.IntVar(&opts.HTTPSPort, "https_port", 0, "HTTPS Port for /varz, /connz endpoints.")
fs.StringVar(&configFile, "c", "", "Configuration file.")
fs.StringVar(&configFile, "config", "", "Configuration file.")
fs.BoolVar(&opts.CheckConfig, "t", false, "Check configuration and exit.")
fs.StringVar(&signal, "sl", "", "Send signal to nats-server process (stop, quit, reopen, reload).")
fs.StringVar(&signal, "signal", "", "Send signal to nats-server process (stop, quit, reopen, reload).")
fs.StringVar(&opts.PidFile, "P", "", "File to store process pid.")
fs.StringVar(&opts.PidFile, "pid", "", "File to store process pid.")
fs.StringVar(&opts.PortsFileDir, "ports_file_dir", "", "Creates a ports file in the specified directory (<executable_name>_<pid>.ports).")
fs.StringVar(&opts.LogFile, "l", "", "File to store logging output.")
fs.StringVar(&opts.LogFile, "log", "", "File to store logging output.")
fs.Int64Var(&opts.LogSizeLimit, "log_size_limit", 0, "Logfile size limit being auto-rotated")
fs.BoolVar(&opts.Syslog, "s", false, "Enable syslog as log method.")
fs.BoolVar(&opts.Syslog, "syslog", false, "Enable syslog as log method.")
fs.StringVar(&opts.RemoteSyslog, "r", "", "Syslog server addr (udp://127.0.0.1:514).")
fs.StringVar(&opts.RemoteSyslog, "remote_syslog", "", "Syslog server addr (udp://127.0.0.1:514).")
fs.BoolVar(&showVersion, "version", false, "Print version information.")
fs.BoolVar(&showVersion, "v", false, "Print version information.")
fs.IntVar(&opts.ProfPort, "profile", 0, "Profiling HTTP port.")
fs.StringVar(&opts.RoutesStr, "routes", "", "Routes to actively solicit a connection.")
fs.StringVar(&opts.Cluster.ListenStr, "cluster", "", "Cluster url from which members can solicit routes.")
fs.StringVar(&opts.Cluster.ListenStr, "cluster_listen", "", "Cluster url from which members can solicit routes.")
fs.StringVar(&opts.Cluster.Advertise, "cluster_advertise", "", "Cluster URL to advertise to other servers.")
fs.BoolVar(&opts.Cluster.NoAdvertise, "no_advertise", false, "Advertise known cluster IPs to clients.")
fs.IntVar(&opts.Cluster.ConnectRetries, "connect_retries", 0, "For implicit routes, number of connect retries.")
fs.BoolVar(&showTLSHelp, "help_tls", false, "TLS help.")
fs.BoolVar(&opts.TLS, "tls", false, "Enable TLS.")
fs.BoolVar(&opts.TLSVerify, "tlsverify", false, "Enable TLS with client verification.")
fs.StringVar(&opts.TLSCert, "tlscert", "", "Server certificate file.")
fs.StringVar(&opts.TLSKey, "tlskey", "", "Private key for server certificate.")
fs.StringVar(&opts.TLSCaCert, "tlscacert", "", "Client certificate CA for verification.")
fs.IntVar(&opts.MaxTracedMsgLen, "max_traced_msg_len", 0, "Maximum printable length for traced messages. 0 for unlimited.")
fs.BoolVar(&opts.JetStream, "js", false, "Enable JetStream.")
fs.BoolVar(&opts.JetStream, "jetstream", false, "Enable JetStream.")
fs.StringVar(&opts.StoreDir, "sd", "", "Storage directory.")
fs.StringVar(&opts.StoreDir, "store_dir", "", "Storage directory.")
// The flags definition above set "default" values to some of the options.
// Calling Parse() here will override the default options with any value
// specified from the command line. This is ok. We will then update the
// options with the content of the configuration file (if present), and then,
// call Parse() again to override the default+config with command line values.
// Calling Parse() before processing config file is necessary since configFile
// itself is a command line argument, and also Parse() is required in order
// to know if user wants simply to show "help" or "version", etc...
if err := fs.Parse(args); err != nil {
return nil, err
}
if showVersion {
printVersion()
return nil, nil
}
if showHelp {
printHelp()
return nil, nil
}
if showTLSHelp {
printTLSHelp()
return nil, nil
}
// Process args looking for non-flag options,
// 'version' and 'help' only for now
showVersion, showHelp, err = ProcessCommandLineArgs(fs)
if err != nil {
return nil, err
} else if showVersion {
printVersion()
return nil, nil
} else if showHelp {
printHelp()
return nil, nil
}
// Snapshot flag options.
FlagSnapshot = opts.Clone()
// Keep track of the boolean flags that were explicitly set with their value.
fs.Visit(func(f *flag.Flag) {
switch f.Name {
case "DVV":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Debug", dbgAndTrcAndVerboseTrc)
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", dbgAndTrcAndVerboseTrc)
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "TraceVerbose", dbgAndTrcAndVerboseTrc)
case "DV":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Debug", dbgAndTrace)
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", dbgAndTrace)
case "D":
fallthrough
case "debug":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Debug", FlagSnapshot.Debug)
case "VV":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", trcAndVerboseTrc)
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "TraceVerbose", trcAndVerboseTrc)
case "V":
fallthrough
case "trace":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", FlagSnapshot.Trace)
case "T":
fallthrough
case "logtime":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Logtime", FlagSnapshot.Logtime)
case "s":
fallthrough
case "syslog":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Syslog", FlagSnapshot.Syslog)
case "no_advertise":
trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Cluster.NoAdvertise", FlagSnapshot.Cluster.NoAdvertise)
}
})
// Process signal control.
if signal != "" {
if err := processSignal(signal); err != nil {
return nil, err
}
}
// Parse config if given
if configFile != "" {
// This will update the options with values from the config file.
err := opts.ProcessConfigFile(configFile)
if err != nil {
if opts.CheckConfig {
return nil, err
}
if cerr, ok := err.(*processConfigErr); !ok || len(cerr.Errors()) != 0 {
return nil, err
}
// If we get here we only have warnings and can still continue
fmt.Fprint(os.Stderr, err)
} else if opts.CheckConfig {
// Report configuration file syntax test was successful and exit.
return opts, nil
}
// Call this again to override config file options with options from command line.
// Note: We don't need to check error here since if there was an error, it would
// have been caught the first time this function was called (after setting up the
// flags).
fs.Parse(args)
} else if opts.CheckConfig {
return nil, fmt.Errorf("must specify [-c, --config] option to check configuration file syntax")
}
// Special handling of some flags
var (
flagErr error
tlsDisabled bool
tlsOverride bool
)
fs.Visit(func(f *flag.Flag) {
// short-circuit if an error was encountered
if flagErr != nil {
return
}
if strings.HasPrefix(f.Name, "tls") {
if f.Name == "tls" {
if !opts.TLS {
// User has specified "-tls=false", we need to disable TLS
opts.TLSConfig = nil
tlsDisabled = true
tlsOverride = false
return
}
tlsOverride = true
} else if !tlsDisabled {
tlsOverride = true
}
} else {
switch f.Name {
case "VV":
opts.Trace, opts.TraceVerbose = trcAndVerboseTrc, trcAndVerboseTrc
case "DVV":
opts.Trace, opts.Debug, opts.TraceVerbose = dbgAndTrcAndVerboseTrc, dbgAndTrcAndVerboseTrc, dbgAndTrcAndVerboseTrc
case "DV":
// Check value to support -DV=false
opts.Trace, opts.Debug = dbgAndTrace, dbgAndTrace
case "cluster", "cluster_listen":
// Override cluster config if explicitly set via flags.
flagErr = overrideCluster(opts)
case "routes":
// Keep in mind that the flag has updated opts.RoutesStr at this point.
if opts.RoutesStr == "" {
// Set routes array to nil since routes string is empty
opts.Routes = nil
return
}
routeUrls := RoutesFromStr(opts.RoutesStr)
opts.Routes = routeUrls
}
}
})
if flagErr != nil {
return nil, flagErr
}
// This will be true if some of the `-tls` params have been set and
// `-tls=false` has not been set.
if tlsOverride {
if err := overrideTLS(opts); err != nil {
return nil, err
}
}
// If we don't have cluster defined in the configuration
// file and no cluster listen string override, but we do
// have a routes override, we need to report misconfiguration.
if opts.RoutesStr != "" && opts.Cluster.ListenStr == "" && opts.Cluster.Host == "" && opts.Cluster.Port == 0 {
return nil, errors.New("solicited routes require cluster capabilities, e.g. --cluster")
}
return opts, nil
}
// overrideTLS is called when at least "-tls=true" has been set.
func overrideTLS(opts *Options) error {
if opts.TLSCert == "" {
return errors.New("TLS Server certificate must be present and valid")
}
if opts.TLSKey == "" {
return errors.New("TLS Server private key must be present and valid")
}
tc := TLSConfigOpts{}
tc.CertFile = opts.TLSCert
tc.KeyFile = opts.TLSKey
tc.CaFile = opts.TLSCaCert
tc.Verify = opts.TLSVerify
var err error
opts.TLSConfig, err = GenTLSConfig(&tc)
return err
}
// overrideCluster updates Options.Cluster if that flag "cluster" (or "cluster_listen")
// has explicitly be set in the command line. If it is set to empty string, it will
// clear the Cluster options.
func overrideCluster(opts *Options) error {
if opts.Cluster.ListenStr == "" {
// This one is enough to disable clustering.
opts.Cluster.Port = 0
return nil
}
// -1 will fail url.Parse, so if we have -1, change it to
// 0, and then after parse, replace the port with -1 so we get
// automatic port allocation
wantsRandom := false
if strings.HasSuffix(opts.Cluster.ListenStr, ":-1") {
wantsRandom = true
cls := fmt.Sprintf("%s:0", opts.Cluster.ListenStr[0:len(opts.Cluster.ListenStr)-3])
opts.Cluster.ListenStr = cls
}
clusterURL, err := url.Parse(opts.Cluster.ListenStr)
if err != nil {
return err
}
h, p, err := net.SplitHostPort(clusterURL.Host)
if err != nil {
return err
}
if wantsRandom {
p = "-1"
}
opts.Cluster.Host = h
_, err = fmt.Sscan(p, &opts.Cluster.Port)
if err != nil {
return err
}
if clusterURL.User != nil {
pass, hasPassword := clusterURL.User.Password()
if !hasPassword {
return errors.New("expected cluster password to be set")
}
opts.Cluster.Password = pass
user := clusterURL.User.Username()
opts.Cluster.Username = user
} else {
// Since we override from flag and there is no user/pwd, make
// sure we clear what we may have gotten from config file.
opts.Cluster.Username = ""
opts.Cluster.Password = ""
}
return nil
}
func processSignal(signal string) error {
var (
pid string
commandAndPid = strings.Split(signal, "=")
)
if l := len(commandAndPid); l == 2 {
pid = maybeReadPidFile(commandAndPid[1])
} else if l > 2 {
return fmt.Errorf("invalid signal parameters: %v", commandAndPid[2:])
}
if err := ProcessSignal(Command(commandAndPid[0]), pid); err != nil {
return err
}
os.Exit(0)
return nil
}
// maybeReadPidFile returns a PID or Windows service name obtained via the following method:
// 1. Try to open a file with path "pidStr" (absolute or relative).
// 2. If such a file exists and can be read, return its contents.
// 3. Otherwise, return the original "pidStr" string.
func maybeReadPidFile(pidStr string) string {
if b, err := ioutil.ReadFile(pidStr); err == nil {
return string(b)
}
return pidStr
}
func homeDir() (string, error) {
if runtime.GOOS == "windows" {
homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
userProfile := os.Getenv("USERPROFILE")
home := filepath.Join(homeDrive, homePath)
if homeDrive == "" || homePath == "" {
if userProfile == "" {
return "", errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%")
}
home = userProfile
}
return home, nil
}
home := os.Getenv("HOME")
if home == "" {
return "", errors.New("failed to get home dir, require $HOME")
}
return home, nil
}
func expandPath(p string) (string, error) {
p = os.ExpandEnv(p)
if !strings.HasPrefix(p, "~") {
return p, nil
}
home, err := homeDir()
if err != nil {
return "", err
}
return filepath.Join(home, p[1:]), nil
}
| 1 | 10,422 | Do you envision "new" servers not supporting header, or is it more a way to test mix of old and new? If so, we could make it a "private" (non exported) option. | nats-io-nats-server | go |
@@ -51,7 +51,7 @@ type Connection struct {
func (c *Connection) Start(options connection.ConnectOptions) (err error) {
var config wg.ServiceConfig
if err := json.Unmarshal(options.SessionConfig, &config); err != nil {
- return err
+ return errors.Wrap(err, "failed to unmarshal connection config")
}
c.config.Provider = config.Provider
c.config.Consumer.IPAddress = config.Consumer.IPAddress | 1 | /*
* Copyright (C) 2018 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package connection
import (
"encoding/json"
"net"
"sync"
"time"
log "github.com/cihub/seelog"
"github.com/mysteriumnetwork/node/consumer"
"github.com/mysteriumnetwork/node/core/connection"
wg "github.com/mysteriumnetwork/node/services/wireguard"
endpoint "github.com/mysteriumnetwork/node/services/wireguard/endpoint"
"github.com/mysteriumnetwork/node/services/wireguard/key"
"github.com/mysteriumnetwork/node/services/wireguard/resources"
"github.com/pkg/errors"
)
const logPrefix = "[connection-wireguard] "
// Connection which does wireguard tunneling.
type Connection struct {
connection sync.WaitGroup
stopChannel chan struct{}
stateChannel connection.StateChannel
statisticsChannel connection.StatisticsChannel
config wg.ServiceConfig
connectionEndpoint wg.ConnectionEndpoint
}
// Start establish wireguard connection to the service provider.
func (c *Connection) Start(options connection.ConnectOptions) (err error) {
var config wg.ServiceConfig
if err := json.Unmarshal(options.SessionConfig, &config); err != nil {
return err
}
c.config.Provider = config.Provider
c.config.Consumer.IPAddress = config.Consumer.IPAddress
resourceAllocator := resources.NewAllocator()
c.connectionEndpoint, err = endpoint.NewConnectionEndpoint("", &resourceAllocator)
if err != nil {
return err
}
c.connection.Add(1)
c.stateChannel <- connection.Connecting
if err := c.connectionEndpoint.Start(&c.config); err != nil {
c.stateChannel <- connection.NotConnected
c.connection.Done()
return err
}
if err := c.connectionEndpoint.AddPeer(c.config.Provider.PublicKey, &c.config.Provider.Endpoint); err != nil {
c.stateChannel <- connection.NotConnected
c.connection.Done()
return err
}
if err := c.connectionEndpoint.ConfigureRoutes(c.config.Provider.Endpoint.IP); err != nil {
c.stateChannel <- connection.NotConnected
c.connection.Done()
return err
}
if err := c.waitHandshake(); err != nil {
c.stateChannel <- connection.NotConnected
c.connection.Done()
return errors.Wrap(err, "failed while waiting for a peer handshake")
}
go c.runPeriodically(time.Second)
c.stateChannel <- connection.Connected
return nil
}
// Wait blocks until wireguard connection not stopped.
func (c *Connection) Wait() error {
c.connection.Wait()
return nil
}
// GetConfig returns the consumer configuration for session creation
func (c *Connection) GetConfig() (connection.ConsumerConfig, error) {
publicKey, err := key.PrivateKeyToPublicKey(c.config.Consumer.PrivateKey)
if err != nil {
return nil, err
}
return wg.ConsumerConfig{
PublicKey: publicKey,
}, nil
}
// Stop stops wireguard connection and closes connection endpoint.
func (c *Connection) Stop() {
c.stateChannel <- connection.Disconnecting
if err := c.connectionEndpoint.Stop(); err != nil {
log.Error(logPrefix, "Failed to close wireguard connection: ", err)
}
c.stateChannel <- connection.NotConnected
c.connection.Done()
close(c.stopChannel)
close(c.stateChannel)
close(c.statisticsChannel)
}
func (c *Connection) runPeriodically(duration time.Duration) {
for {
select {
case <-time.After(duration):
stats, err := c.connectionEndpoint.PeerStats()
if err != nil {
log.Error(logPrefix, "failed to receive peer stats: ", err)
break
}
c.statisticsChannel <- consumer.SessionStatistics{
BytesSent: stats.BytesSent,
BytesReceived: stats.BytesReceived,
}
case <-c.stopChannel:
return
}
}
}
func (c *Connection) waitHandshake() error {
// We need to send any packet to initialize handshake process
_, _ = net.DialTimeout("tcp", "8.8.8.8:53", 100*time.Millisecond)
for {
select {
case <-time.After(100 * time.Millisecond):
stats, err := c.connectionEndpoint.PeerStats()
if err != nil {
return err
}
if !stats.LastHandshake.IsZero() {
return nil
}
case <-c.stopChannel:
return errors.New("stop received")
}
}
}
| 1 | 13,222 | For future reference. Try not to do refactoring in the same PR which solves some bug or implements some feature. Not to clutter reading. Do it in separate PR. | mysteriumnetwork-node | go |
@@ -110,7 +110,7 @@ func init() {
addTxnFlags(freezeAssetCmd)
infoAssetCmd.Flags().Uint64Var(&assetID, "assetid", 0, "ID of the asset to look up")
- infoAssetCmd.Flags().StringVar(&assetUnitName, "asset", "", "Unit name of the asset to look up")
+ infoAssetCmd.Flags().StringVar(&assetUnitName, "unit", "", "Unit name of the asset to look up")
infoAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address of the asset creator")
}
| 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 main
import (
"encoding/base64"
"fmt"
"github.com/spf13/cobra"
"github.com/algorand/go-algorand/libgoal"
)
var (
assetID uint64
assetCreator string
assetTotal uint64
assetDecimals uint32
assetFrozen bool
assetUnitName string
assetMetadataHashBase64 string
assetURL string
assetName string
assetManager string
assetClawback string
assetFreezer string
assetNewManager string
assetNewReserve string
assetNewFreezer string
assetNewClawback string
)
func init() {
assetCmd.AddCommand(createAssetCmd)
assetCmd.AddCommand(destroyAssetCmd)
assetCmd.AddCommand(configAssetCmd)
assetCmd.AddCommand(sendAssetCmd)
assetCmd.AddCommand(infoAssetCmd)
assetCmd.AddCommand(freezeAssetCmd)
assetCmd.PersistentFlags().StringVarP(&walletName, "wallet", "w", "", "Set the wallet to be used for the selected operation")
createAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address for creating an asset")
createAssetCmd.Flags().Uint64Var(&assetTotal, "total", 0, "Total amount of tokens for created asset")
createAssetCmd.Flags().Uint32Var(&assetDecimals, "decimals", 0, "The number of digits to use after the decimal point when displaying this asset. If set to 0, the asset is not divisible beyond its base unit. If set to 1, the base asset unit is tenths. If 2, the base asset unit is hundredths, and so on.")
createAssetCmd.Flags().BoolVar(&assetFrozen, "defaultfrozen", false, "Freeze or not freeze holdings by default")
createAssetCmd.Flags().StringVar(&assetUnitName, "unitname", "", "Name for the unit of asset")
createAssetCmd.Flags().StringVar(&assetName, "name", "", "Name for the entire asset")
createAssetCmd.Flags().StringVar(&assetURL, "asseturl", "", "URL where user can access more information about the asset (max 32 bytes)")
createAssetCmd.Flags().StringVar(&assetMetadataHashBase64, "assetmetadatab64", "", "base-64 encoded 32-byte commitment to asset metadata")
createAssetCmd.MarkFlagRequired("total")
createAssetCmd.MarkFlagRequired("creator")
destroyAssetCmd.Flags().StringVar(&assetManager, "manager", "", "Manager account to issue the destroy transaction (defaults to creator)")
destroyAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address for asset to destroy")
destroyAssetCmd.Flags().Uint64Var(&assetID, "assetid", 0, "Asset ID to destroy")
destroyAssetCmd.Flags().StringVar(&assetUnitName, "asset", "", "Unit name of asset to destroy")
configAssetCmd.Flags().StringVar(&assetManager, "manager", "", "Manager account to issue the config transaction (defaults to creator)")
configAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address for asset to configure")
configAssetCmd.Flags().Uint64Var(&assetID, "assetid", 0, "Asset ID to configure")
configAssetCmd.Flags().StringVar(&assetUnitName, "asset", "", "Unit name of asset to configure")
configAssetCmd.Flags().StringVar(&assetNewManager, "new-manager", "", "New manager address")
configAssetCmd.Flags().StringVar(&assetNewReserve, "new-reserve", "", "New reserve address")
configAssetCmd.Flags().StringVar(&assetNewFreezer, "new-freezer", "", "New freeze address")
configAssetCmd.Flags().StringVar(&assetNewClawback, "new-clawback", "", "New clawback address")
configAssetCmd.MarkFlagRequired("manager")
sendAssetCmd.Flags().StringVar(&assetClawback, "clawback", "", "Address to issue a clawback transaction from (defaults to no clawback)")
sendAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address for asset creator")
sendAssetCmd.Flags().Uint64Var(&assetID, "assetid", 0, "ID of the asset being transferred")
sendAssetCmd.Flags().StringVar(&assetUnitName, "asset", "", "Unit name of the asset being transferred")
sendAssetCmd.Flags().StringVarP(&account, "from", "f", "", "Account address to send the money from (if not specified, uses default account)")
sendAssetCmd.Flags().StringVarP(&toAddress, "to", "t", "", "Address to send to money to (required)")
sendAssetCmd.Flags().Uint64VarP(&amount, "amount", "a", 0, "The amount to be transferred (required), in base units of the asset.")
sendAssetCmd.Flags().StringVarP(&closeToAddress, "close-to", "c", "", "Close asset account and send remainder to this address")
sendAssetCmd.MarkFlagRequired("to")
sendAssetCmd.MarkFlagRequired("amount")
freezeAssetCmd.Flags().StringVar(&assetFreezer, "freezer", "", "Address to issue a freeze transaction from")
freezeAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address for asset creator")
freezeAssetCmd.Flags().Uint64Var(&assetID, "assetid", 0, "ID of the asset being frozen")
freezeAssetCmd.Flags().StringVar(&assetUnitName, "asset", "", "Unit name of the asset being frozen")
freezeAssetCmd.Flags().StringVar(&account, "account", "", "Account address to freeze/unfreeze")
freezeAssetCmd.Flags().BoolVar(&assetFrozen, "freeze", false, "Freeze or unfreeze")
freezeAssetCmd.MarkFlagRequired("freezer")
freezeAssetCmd.MarkFlagRequired("account")
freezeAssetCmd.MarkFlagRequired("freeze")
// Add common transaction flags to all txn-generating asset commands
addTxnFlags(createAssetCmd)
addTxnFlags(destroyAssetCmd)
addTxnFlags(configAssetCmd)
addTxnFlags(sendAssetCmd)
addTxnFlags(freezeAssetCmd)
infoAssetCmd.Flags().Uint64Var(&assetID, "assetid", 0, "ID of the asset to look up")
infoAssetCmd.Flags().StringVar(&assetUnitName, "asset", "", "Unit name of the asset to look up")
infoAssetCmd.Flags().StringVar(&assetCreator, "creator", "", "Account address of the asset creator")
}
var assetCmd = &cobra.Command{
Use: "asset",
Short: "Manage assets",
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
// If no arguments passed, we should fallback to help
cmd.HelpFunc()(cmd, args)
},
}
func lookupAssetID(cmd *cobra.Command, creator string, client libgoal.Client) {
if cmd.Flags().Changed("assetid") && cmd.Flags().Changed("asset") {
reportErrorf("Only one of [-assetid] or [-asset and -creator] can be specified")
}
if cmd.Flags().Changed("assetid") {
return
}
if !cmd.Flags().Changed("asset") {
reportErrorf("Either [-assetid] or [-asset and -creator] must be specified")
}
if !cmd.Flags().Changed("creator") {
reportErrorf("Asset creator must be specified if finding asset by name. " +
"Use the asset's integer identifier (-assetid) if the " +
"creator account is unknown.")
}
response, err := client.AccountInformation(creator)
if err != nil {
reportErrorf(errorRequestFail, err)
}
nmatch := 0
for id, params := range response.AssetParams {
if params.UnitName == assetUnitName {
assetID = id
nmatch++
}
}
if nmatch == 0 {
reportErrorf("No matches for asset unit name %s in creator %s", assetUnitName, creator)
}
if nmatch > 1 {
reportErrorf("Multiple matches for asset unit name %s in creator %s", assetUnitName, creator)
}
}
var createAssetCmd = &cobra.Command{
Use: "create",
Short: "Create an asset",
Long: "Post a transaction declaring and issuing a new layer-one asset on the network.",
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, _ []string) {
checkTxValidityPeriodCmdFlags(cmd)
dataDir := ensureSingleDataDir()
client := ensureFullClient(dataDir)
accountList := makeAccountsList(dataDir)
creator := accountList.getAddressByName(assetCreator)
var err error
var assetMetadataHash []byte
if assetMetadataHashBase64 != "" {
assetMetadataHash, err = base64.StdEncoding.DecodeString(assetMetadataHashBase64)
if err != nil {
reportErrorf(malformedMetadataHash, assetMetadataHashBase64, err)
}
}
tx, err := client.MakeUnsignedAssetCreateTx(assetTotal, assetFrozen, creator, creator, creator, creator, assetUnitName, assetName, assetURL, assetMetadataHash, assetDecimals)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
tx.Note = parseNoteField(cmd)
tx.Lease = parseLease(cmd)
fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
if err != nil {
reportErrorf("Cannot determine last valid round: %s", err)
}
tx, err = client.FillUnsignedTxTemplate(creator, fv, lv, fee, tx)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
if outFilename == "" {
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
if err != nil {
reportErrorf(errorSigningTX, err)
}
txid, err := client.BroadcastTransaction(signedTxn)
if err != nil {
reportErrorf(errorBroadcastingTX, err)
}
// Report tx details to user
reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)
if !noWaitAfterSend {
err = waitForCommit(client, txid)
if err != nil {
reportErrorf(err.Error())
}
// Check if we know about the transaction yet
txn, err := client.PendingTransactionInformation(txid)
if err != nil {
reportErrorf(err.Error())
}
if txn.TransactionResults != nil && txn.TransactionResults.CreatedAssetIndex != 0 {
reportInfof("Created asset with asset index %d", txn.TransactionResults.CreatedAssetIndex)
}
}
} else {
err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
if err != nil {
reportErrorf(err.Error())
}
}
},
}
var destroyAssetCmd = &cobra.Command{
Use: "destroy",
Short: "Destroy an asset",
Long: `Issue a transaction deleting an asset from the network. This transaction must be issued by the asset owner, who must hold all outstanding asset tokens.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, _ []string) {
checkTxValidityPeriodCmdFlags(cmd)
dataDir := ensureSingleDataDir()
client := ensureFullClient(dataDir)
accountList := makeAccountsList(dataDir)
if assetManager == "" {
assetManager = assetCreator
}
creator := accountList.getAddressByName(assetCreator)
manager := accountList.getAddressByName(assetManager)
lookupAssetID(cmd, creator, client)
tx, err := client.MakeUnsignedAssetDestroyTx(assetID)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
tx.Note = parseNoteField(cmd)
tx.Lease = parseLease(cmd)
firstValid, lastValid, err = client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
if err != nil {
reportErrorf("Cannot determine last valid round: %s", err)
}
tx, err = client.FillUnsignedTxTemplate(manager, firstValid, lastValid, fee, tx)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
if outFilename == "" {
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
if err != nil {
reportErrorf(errorSigningTX, err)
}
txid, err := client.BroadcastTransaction(signedTxn)
if err != nil {
reportErrorf(errorBroadcastingTX, err)
}
// Report tx details to user
reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)
if !noWaitAfterSend {
err = waitForCommit(client, txid)
if err != nil {
reportErrorf(err.Error())
}
}
} else {
err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
if err != nil {
reportErrorf(err.Error())
}
}
},
}
var configAssetCmd = &cobra.Command{
Use: "config",
Short: "Configure an asset",
Long: `Change an asset configuration. This transaction must be issued by the asset manager. This allows any management address to be changed: manager, freezer, reserve, or clawback.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, _ []string) {
checkTxValidityPeriodCmdFlags(cmd)
dataDir := ensureSingleDataDir()
client := ensureFullClient(dataDir)
accountList := makeAccountsList(dataDir)
if assetManager == "" {
assetManager = assetCreator
}
creator := accountList.getAddressByName(assetCreator)
manager := accountList.getAddressByName(assetManager)
lookupAssetID(cmd, creator, client)
var newManager, newReserve, newFreeze, newClawback *string
if cmd.Flags().Changed("new-manager") {
assetNewManager = accountList.getAddressByName(assetNewManager)
newManager = &assetNewManager
}
if cmd.Flags().Changed("new-reserve") {
assetNewReserve = accountList.getAddressByName(assetNewReserve)
newReserve = &assetNewReserve
}
if cmd.Flags().Changed("new-freezer") {
assetNewFreezer = accountList.getAddressByName(assetNewFreezer)
newFreeze = &assetNewFreezer
}
if cmd.Flags().Changed("new-clawback") {
assetNewClawback = accountList.getAddressByName(assetNewClawback)
newClawback = &assetNewClawback
}
tx, err := client.MakeUnsignedAssetConfigTx(creator, assetID, newManager, newReserve, newFreeze, newClawback)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
tx.Note = parseNoteField(cmd)
tx.Lease = parseLease(cmd)
firstValid, lastValid, err = client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
if err != nil {
reportErrorf("Cannot determine last valid round: %s", err)
}
tx, err = client.FillUnsignedTxTemplate(manager, firstValid, lastValid, fee, tx)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
if outFilename == "" {
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
if err != nil {
reportErrorf(errorSigningTX, err)
}
txid, err := client.BroadcastTransaction(signedTxn)
if err != nil {
reportErrorf(errorBroadcastingTX, err)
}
// Report tx details to user
reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)
if !noWaitAfterSend {
err = waitForCommit(client, txid)
if err != nil {
reportErrorf(err.Error())
}
}
} else {
err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
if err != nil {
reportErrorf(err.Error())
}
}
},
}
var sendAssetCmd = &cobra.Command{
Use: "send",
Short: "Transfer assets",
Long: "Transfer asset holdings. An account can begin accepting an asset by issuing a zero-amount asset transfer to itself.",
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, _ []string) {
checkTxValidityPeriodCmdFlags(cmd)
dataDir := ensureSingleDataDir()
client := ensureFullClient(dataDir)
accountList := makeAccountsList(dataDir)
// Check if from was specified, else use default
if account == "" {
account = accountList.getDefaultAccount()
}
sender := accountList.getAddressByName(account)
toAddressResolved := accountList.getAddressByName(toAddress)
creatorResolved := accountList.getAddressByName(assetCreator)
lookupAssetID(cmd, creatorResolved, client)
var senderForClawback string
if assetClawback != "" {
senderForClawback = sender
sender = accountList.getAddressByName(assetClawback)
}
var closeToAddressResolved string
if closeToAddress != "" {
closeToAddressResolved = accountList.getAddressByName(closeToAddress)
}
tx, err := client.MakeUnsignedAssetSendTx(assetID, amount, toAddressResolved, closeToAddressResolved, senderForClawback)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
tx.Note = parseNoteField(cmd)
tx.Lease = parseLease(cmd)
firstValid, lastValid, err = client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
if err != nil {
reportErrorf("Cannot determine last valid round: %s", err)
}
tx, err = client.FillUnsignedTxTemplate(sender, firstValid, lastValid, fee, tx)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
if outFilename == "" {
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
if err != nil {
reportErrorf(errorSigningTX, err)
}
txid, err := client.BroadcastTransaction(signedTxn)
if err != nil {
reportErrorf(errorBroadcastingTX, err)
}
// Report tx details to user
reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)
if !noWaitAfterSend {
err = waitForCommit(client, txid)
if err != nil {
reportErrorf(err.Error())
}
}
} else {
err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
if err != nil {
reportErrorf(err.Error())
}
}
},
}
var freezeAssetCmd = &cobra.Command{
Use: "freeze",
Short: "Freeze assets",
Long: `Freeze or unfreeze assets for a target account. The transaction must be issued by the freeze address for the asset in question.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, _ []string) {
checkTxValidityPeriodCmdFlags(cmd)
dataDir := ensureSingleDataDir()
client := ensureFullClient(dataDir)
accountList := makeAccountsList(dataDir)
freezer := accountList.getAddressByName(assetFreezer)
creatorResolved := accountList.getAddressByName(assetCreator)
accountResolved := accountList.getAddressByName(account)
lookupAssetID(cmd, creatorResolved, client)
tx, err := client.MakeUnsignedAssetFreezeTx(assetID, accountResolved, assetFrozen)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
tx.Note = parseNoteField(cmd)
tx.Lease = parseLease(cmd)
firstValid, lastValid, err = client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
if err != nil {
reportErrorf("Cannot determine last valid round: %s", err)
}
tx, err = client.FillUnsignedTxTemplate(freezer, firstValid, lastValid, fee, tx)
if err != nil {
reportErrorf("Cannot construct transaction: %s", err)
}
if outFilename == "" {
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
if err != nil {
reportErrorf(errorSigningTX, err)
}
txid, err := client.BroadcastTransaction(signedTxn)
if err != nil {
reportErrorf(errorBroadcastingTX, err)
}
// Report tx details to user
reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)
if !noWaitAfterSend {
err = waitForCommit(client, txid)
if err != nil {
reportErrorf(err.Error())
}
}
} else {
err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
if err != nil {
reportErrorf(err.Error())
}
}
},
}
func assetDecimalsFmt(amount uint64, decimals uint32) string {
// Just return the raw amount with no decimal if decimals is 0
if decimals == 0 {
return fmt.Sprintf("%d", amount)
}
// Otherwise, ensure there are decimals digits to the right of the decimal point
pow := uint64(1)
for i := uint32(0); i < decimals; i++ {
pow *= 10
}
return fmt.Sprintf("%d.%0*d", amount/pow, decimals, amount%pow)
}
var infoAssetCmd = &cobra.Command{
Use: "info",
Short: "Look up current parameters for an asset",
Long: `Look up asset information stored on the network, such as asset creator, management addresses, or asset name.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, _ []string) {
dataDir := ensureSingleDataDir()
client := ensureFullClient(dataDir)
accountList := makeAccountsList(dataDir)
creator := accountList.getAddressByName(assetCreator)
lookupAssetID(cmd, creator, client)
params, err := client.AssetInformation(assetID)
if err != nil {
reportErrorf(errorRequestFail, err)
}
reserveEmpty := false
if params.ReserveAddr == "" {
reserveEmpty = true
params.ReserveAddr = params.Creator
}
reserve, err := client.AccountInformation(params.ReserveAddr)
if err != nil {
reportErrorf(errorRequestFail, err)
}
res := reserve.Assets[assetID]
fmt.Printf("Asset ID: %d\n", assetID)
fmt.Printf("Creator: %s\n", params.Creator)
fmt.Printf("Asset name: %s\n", params.AssetName)
fmt.Printf("Unit name: %s\n", params.UnitName)
fmt.Printf("Maximum issue: %s %s\n", assetDecimalsFmt(params.Total, params.Decimals), params.UnitName)
fmt.Printf("Reserve amount: %s %s\n", assetDecimalsFmt(res.Amount, params.Decimals), params.UnitName)
fmt.Printf("Issued: %s %s\n", assetDecimalsFmt(params.Total-res.Amount, params.Decimals), params.UnitName)
fmt.Printf("Decimals: %d\n", params.Decimals)
fmt.Printf("Default frozen: %v\n", params.DefaultFrozen)
fmt.Printf("Manager address: %s\n", params.ManagerAddr)
if reserveEmpty {
fmt.Printf("Reserve address: %s (Empty. Defaulting to creator)\n", params.ReserveAddr)
} else {
fmt.Printf("Reserve address: %s\n", params.ReserveAddr)
}
fmt.Printf("Freeze address: %s\n", params.FreezeAddr)
fmt.Printf("Clawback address: %s\n", params.ClawbackAddr)
},
}
| 1 | 40,111 | I'm not sure about changing the flag name. unit is more accurate, but for I think for most people asset is also a fine name to use. | algorand-go-algorand | go |
@@ -0,0 +1,19 @@
+// +build windows
+
+package terminal
+
+import (
+ "syscall"
+)
+
+// HideConsole hides the console window and activates another window
+func HideConsole() {
+ getConsoleWindow := syscall.NewLazyDLL("kernel32.dll").NewProc("GetConsoleWindow")
+ showWindow := syscall.NewLazyDLL("user32.dll").NewProc("ShowWindow")
+ if getConsoleWindow.Find() == nil && showWindow.Find() == nil {
+ hwnd, _, _ := getConsoleWindow.Call()
+ if hwnd != 0 {
+ showWindow.Call(hwnd, 0)
+ }
+ }
+} | 1 | 1 | 12,763 | Which windows gets activated? A random other window? | rclone-rclone | go |
|
@@ -62,6 +62,11 @@ func (a *Publisher) Start(ctx context.Context) error {
}
func (a *Publisher) receive(ctx context.Context, event cloudevents.Event, resp *cloudevents.EventResponse) error {
+ // Upgrade to supported transport version.
+ if event.SpecVersion() != cloudevents.VersionV03 {
+ event.Context = event.Context.AsV03()
+ }
+
if _, r, err := a.outbound.Send(ctx, event); err != nil {
return err
} else if r != nil { | 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
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 publisher
import (
"fmt"
"context"
cloudevents "github.com/cloudevents/sdk-go"
cepubsub "github.com/cloudevents/sdk-go/pkg/cloudevents/transport/pubsub"
"github.com/google/knative-gcp/pkg/kncloudevents"
)
// Publisher implements the Pub/Sub adapter to deliver Pub/Sub messages from a
// pre-existing topic/subscription to a Sink.
type Publisher struct {
// ProjectID is the pre-existing eventing project id to use.
ProjectID string
// TopicID is the pre-existing eventing pub/sub topic id to use.
TopicID string
// inbound is the cloudevents client to use to receive events.
inbound cloudevents.Client
// outbound is the cloudevents client to use to send events.
outbound cloudevents.Client
}
func (a *Publisher) Start(ctx context.Context) error {
var err error
// Receive events on HTTP.
if a.inbound == nil {
if a.inbound, err = kncloudevents.NewDefaultClient(); err != nil {
return fmt.Errorf("failed to create inbound cloudevent client: %s", err.Error())
}
}
// Send Events on Pub/Sub.
if a.outbound == nil {
if a.outbound, err = a.newPubSubClient(ctx); err != nil {
return fmt.Errorf("failed to create outbound cloudevent client: %s", err.Error())
}
}
return a.inbound.StartReceiver(ctx, a.receive)
}
func (a *Publisher) receive(ctx context.Context, event cloudevents.Event, resp *cloudevents.EventResponse) error {
if _, r, err := a.outbound.Send(ctx, event); err != nil {
return err
} else if r != nil {
resp.RespondWith(200, r)
}
return nil
}
func (a *Publisher) newPubSubClient(ctx context.Context) (cloudevents.Client, error) {
tOpts := []cepubsub.Option{
cepubsub.WithBinaryEncoding(),
cepubsub.WithProjectID(a.ProjectID),
cepubsub.WithTopicID(a.TopicID),
}
// Make a pubsub transport for the CloudEvents client.
t, err := cepubsub.New(ctx, tOpts...)
if err != nil {
return nil, err
}
// Use the transport to make a new CloudEvents client.
return cloudevents.NewClient(t,
cloudevents.WithUUIDs(),
cloudevents.WithTimeNow(),
)
}
| 1 | 9,318 | Just to make sure, this is totally lossless? If I put a v2 there, then it gets upgraded to v3, but my function expects v2, then this is fine and nothing is lost? | google-knative-gcp | go |
@@ -228,4 +228,10 @@ public class TableProperties {
public static final String MERGE_CARDINALITY_CHECK_ENABLED = "write.merge.cardinality-check.enabled";
public static final boolean MERGE_CARDINALITY_CHECK_ENABLED_DEFAULT = true;
+
+ public static final String WATERMARK_FIELD_NAME = "write.watermark.field";
+ public static final String WATERMARK_FIELD_NAME_DEFAULT = "";
+
+ public static final String WATERMARK_VALUE = "write.watermark";
+ public static final long WATERMARK_VALUE_DEFAULT = -1;
} | 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.util.Set;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
public class TableProperties {
private TableProperties() {
}
/**
* Reserved table property for table format version.
* <p>
* Iceberg will default a new table's format version to the latest stable and recommended version.
* This reserved property keyword allows users to override the Iceberg format version of the table metadata.
* <p>
* If this table property exists when creating a table, the table will use the specified format version.
* If a table updates this property, it will try to upgrade to the specified format version.
* <p>
* Note: incomplete or unstable versions cannot be selected using this property.
*/
public static final String FORMAT_VERSION = "format-version";
/**
* Reserved Iceberg table properties list.
* <p>
* Reserved table properties are only used to control behaviors when creating or updating a table.
* The value of these properties are not persisted as a part of the table metadata.
*/
public static final Set<String> RESERVED_PROPERTIES = ImmutableSet.of(
FORMAT_VERSION
);
public static final String COMMIT_NUM_RETRIES = "commit.retry.num-retries";
public static final int COMMIT_NUM_RETRIES_DEFAULT = 4;
public static final String COMMIT_MIN_RETRY_WAIT_MS = "commit.retry.min-wait-ms";
public static final int COMMIT_MIN_RETRY_WAIT_MS_DEFAULT = 100;
public static final String COMMIT_MAX_RETRY_WAIT_MS = "commit.retry.max-wait-ms";
public static final int COMMIT_MAX_RETRY_WAIT_MS_DEFAULT = 60000; // 1 minute
public static final String COMMIT_TOTAL_RETRY_TIME_MS = "commit.retry.total-timeout-ms";
public static final int COMMIT_TOTAL_RETRY_TIME_MS_DEFAULT = 1800000; // 30 minutes
public static final String COMMIT_NUM_STATUS_CHECKS = "commit.status-check.num-retries";
public static final int COMMIT_NUM_STATUS_CHECKS_DEFAULT = 3;
public static final String COMMIT_STATUS_CHECKS_MIN_WAIT_MS = "commit.status-check.min-wait-ms";
public static final long COMMIT_STATUS_CHECKS_MIN_WAIT_MS_DEFAULT = 1000L; // 1s
public static final String COMMIT_STATUS_CHECKS_MAX_WAIT_MS = "commit.status-check.max-wait-ms";
public static final long COMMIT_STATUS_CHECKS_MAX_WAIT_MS_DEFAULT = 60000L; // 1 minute
public static final String COMMIT_STATUS_CHECKS_TOTAL_WAIT_MS = "commit.status-check.total-timeout-ms";
public static final long COMMIT_STATUS_CHECKS_TOTAL_WAIT_MS_DEFAULT = 1800000; // 30 minutes
public static final String MANIFEST_TARGET_SIZE_BYTES = "commit.manifest.target-size-bytes";
public static final long MANIFEST_TARGET_SIZE_BYTES_DEFAULT = 8388608; // 8 MB
public static final String MANIFEST_MIN_MERGE_COUNT = "commit.manifest.min-count-to-merge";
public static final int MANIFEST_MIN_MERGE_COUNT_DEFAULT = 100;
public static final String MANIFEST_MERGE_ENABLED = "commit.manifest-merge.enabled";
public static final boolean MANIFEST_MERGE_ENABLED_DEFAULT = true;
public static final String DEFAULT_FILE_FORMAT = "write.format.default";
public static final String DELETE_DEFAULT_FILE_FORMAT = "write.delete.format.default";
public static final String DEFAULT_FILE_FORMAT_DEFAULT = "parquet";
public static final String PARQUET_ROW_GROUP_SIZE_BYTES = "write.parquet.row-group-size-bytes";
public static final String DELETE_PARQUET_ROW_GROUP_SIZE_BYTES = "write.delete.parquet.row-group-size-bytes";
public static final String PARQUET_ROW_GROUP_SIZE_BYTES_DEFAULT = "134217728"; // 128 MB
public static final String PARQUET_PAGE_SIZE_BYTES = "write.parquet.page-size-bytes";
public static final String DELETE_PARQUET_PAGE_SIZE_BYTES = "write.delete.parquet.page-size-bytes";
public static final String PARQUET_PAGE_SIZE_BYTES_DEFAULT = "1048576"; // 1 MB
public static final String PARQUET_DICT_SIZE_BYTES = "write.parquet.dict-size-bytes";
public static final String DELETE_PARQUET_DICT_SIZE_BYTES = "write.delete.parquet.dict-size-bytes";
public static final String PARQUET_DICT_SIZE_BYTES_DEFAULT = "2097152"; // 2 MB
public static final String PARQUET_COMPRESSION = "write.parquet.compression-codec";
public static final String DELETE_PARQUET_COMPRESSION = "write.delete.parquet.compression-codec";
public static final String PARQUET_COMPRESSION_DEFAULT = "gzip";
public static final String PARQUET_COMPRESSION_LEVEL = "write.parquet.compression-level";
public static final String DELETE_PARQUET_COMPRESSION_LEVEL = "write.delete.parquet.compression-level";
public static final String PARQUET_COMPRESSION_LEVEL_DEFAULT = null;
public static final String AVRO_COMPRESSION = "write.avro.compression-codec";
public static final String DELETE_AVRO_COMPRESSION = "write.delete.avro.compression-codec";
public static final String AVRO_COMPRESSION_DEFAULT = "gzip";
public static final String SPLIT_SIZE = "read.split.target-size";
public static final long SPLIT_SIZE_DEFAULT = 134217728; // 128 MB
public static final String METADATA_SPLIT_SIZE = "read.split.metadata-target-size";
public static final long METADATA_SPLIT_SIZE_DEFAULT = 32 * 1024 * 1024; // 32 MB
public static final String SPLIT_LOOKBACK = "read.split.planning-lookback";
public static final int SPLIT_LOOKBACK_DEFAULT = 10;
public static final String SPLIT_OPEN_FILE_COST = "read.split.open-file-cost";
public static final long SPLIT_OPEN_FILE_COST_DEFAULT = 4 * 1024 * 1024; // 4MB
public static final String PARQUET_VECTORIZATION_ENABLED = "read.parquet.vectorization.enabled";
public static final boolean PARQUET_VECTORIZATION_ENABLED_DEFAULT = false;
public static final String PARQUET_BATCH_SIZE = "read.parquet.vectorization.batch-size";
public static final int PARQUET_BATCH_SIZE_DEFAULT = 5000;
public static final String ORC_VECTORIZATION_ENABLED = "read.orc.vectorization.enabled";
public static final boolean ORC_VECTORIZATION_ENABLED_DEFAULT = false;
public static final String OBJECT_STORE_ENABLED = "write.object-storage.enabled";
public static final boolean OBJECT_STORE_ENABLED_DEFAULT = false;
public static final String OBJECT_STORE_PATH = "write.object-storage.path";
public static final String WRITE_LOCATION_PROVIDER_IMPL = "write.location-provider.impl";
// This only applies to files written after this property is set. Files previously written aren't
// relocated to reflect this parameter.
// If not set, defaults to a "data" folder underneath the root path of the table.
public static final String WRITE_FOLDER_STORAGE_LOCATION = "write.folder-storage.path";
/**
* @deprecated will be removed in 0.14.0, use {@link #WRITE_FOLDER_STORAGE_LOCATION} instead
*/
@Deprecated
public static final String WRITE_NEW_DATA_LOCATION = "write.folder-storage.path";
// This only applies to files written after this property is set. Files previously written aren't
// relocated to reflect this parameter.
// If not set, defaults to a "metadata" folder underneath the root path of the table.
public static final String WRITE_METADATA_LOCATION = "write.metadata.path";
public static final String WRITE_PARTITION_SUMMARY_LIMIT = "write.summary.partition-limit";
public static final int WRITE_PARTITION_SUMMARY_LIMIT_DEFAULT = 0;
public static final String MANIFEST_LISTS_ENABLED = "write.manifest-lists.enabled";
public static final boolean MANIFEST_LISTS_ENABLED_DEFAULT = true;
public static final String METADATA_COMPRESSION = "write.metadata.compression-codec";
public static final String METADATA_COMPRESSION_DEFAULT = "none";
public static final String METADATA_PREVIOUS_VERSIONS_MAX = "write.metadata.previous-versions-max";
public static final int METADATA_PREVIOUS_VERSIONS_MAX_DEFAULT = 100;
// This enables to delete the oldest metadata file after commit.
public static final String METADATA_DELETE_AFTER_COMMIT_ENABLED = "write.metadata.delete-after-commit.enabled";
public static final boolean METADATA_DELETE_AFTER_COMMIT_ENABLED_DEFAULT = false;
public static final String METRICS_MODE_COLUMN_CONF_PREFIX = "write.metadata.metrics.column.";
public static final String DEFAULT_WRITE_METRICS_MODE = "write.metadata.metrics.default";
public static final String DEFAULT_WRITE_METRICS_MODE_DEFAULT = "truncate(16)";
public static final String DEFAULT_NAME_MAPPING = "schema.name-mapping.default";
public static final String WRITE_AUDIT_PUBLISH_ENABLED = "write.wap.enabled";
public static final String WRITE_AUDIT_PUBLISH_ENABLED_DEFAULT = "false";
public static final String WRITE_TARGET_FILE_SIZE_BYTES = "write.target-file-size-bytes";
public static final String DELETE_TARGET_FILE_SIZE_BYTES = "write.delete.target-file-size-bytes";
public static final long WRITE_TARGET_FILE_SIZE_BYTES_DEFAULT = 536870912; // 512 MB
public static final String SPARK_WRITE_PARTITIONED_FANOUT_ENABLED = "write.spark.fanout.enabled";
public static final boolean SPARK_WRITE_PARTITIONED_FANOUT_ENABLED_DEFAULT = false;
public static final String SNAPSHOT_ID_INHERITANCE_ENABLED = "compatibility.snapshot-id-inheritance.enabled";
public static final boolean SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT = false;
public static final String ENGINE_HIVE_ENABLED = "engine.hive.enabled";
public static final boolean ENGINE_HIVE_ENABLED_DEFAULT = false;
public static final String WRITE_DISTRIBUTION_MODE = "write.distribution-mode";
public static final String WRITE_DISTRIBUTION_MODE_NONE = "none";
public static final String WRITE_DISTRIBUTION_MODE_HASH = "hash";
public static final String WRITE_DISTRIBUTION_MODE_RANGE = "range";
public static final String WRITE_DISTRIBUTION_MODE_DEFAULT = WRITE_DISTRIBUTION_MODE_NONE;
public static final String GC_ENABLED = "gc.enabled";
public static final boolean GC_ENABLED_DEFAULT = true;
public static final String MAX_SNAPSHOT_AGE_MS = "history.expire.max-snapshot-age-ms";
public static final long MAX_SNAPSHOT_AGE_MS_DEFAULT = 5 * 24 * 60 * 60 * 1000; // 5 days
public static final String MIN_SNAPSHOTS_TO_KEEP = "history.expire.min-snapshots-to-keep";
public static final int MIN_SNAPSHOTS_TO_KEEP_DEFAULT = 1;
public static final String DELETE_ISOLATION_LEVEL = "write.delete.isolation-level";
public static final String DELETE_ISOLATION_LEVEL_DEFAULT = "serializable";
public static final String DELETE_MODE = "write.delete.mode";
public static final String DELETE_MODE_DEFAULT = "copy-on-write";
public static final String UPDATE_ISOLATION_LEVEL = "write.update.isolation-level";
public static final String UPDATE_ISOLATION_LEVEL_DEFAULT = "serializable";
public static final String UPDATE_MODE = "write.update.mode";
public static final String UPDATE_MODE_DEFAULT = "copy-on-write";
public static final String MERGE_ISOLATION_LEVEL = "write.merge.isolation-level";
public static final String MERGE_ISOLATION_LEVEL_DEFAULT = "serializable";
public static final String MERGE_MODE = "write.merge.mode";
public static final String MERGE_MODE_DEFAULT = "copy-on-write";
public static final String MERGE_CARDINALITY_CHECK_ENABLED = "write.merge.cardinality-check.enabled";
public static final boolean MERGE_CARDINALITY_CHECK_ENABLED_DEFAULT = true;
}
| 1 | 42,052 | In the past, we have 3 Flink streaming jobs (1 for each AWS region) writing to the same table. We need to write to 3 different watermark table properties (1 for each region). Watermark consumer then use the min value to determine the overall table watermark. A provider pattern similar to `WRITE_LOCATION_PROVIDER_IMPL` can work. A default impl could be a single property name. not sure if there is a simpler way to achieve this. | apache-iceberg | java |
@@ -67,6 +67,16 @@ func (h TlfHandle) IsReader(user keybase1.UID) bool {
return ok
}
+// ResolvedReadersMap returns a map of resolved readers from uid to usernames.
+func (h TlfHandle) ResolvedReadersMap() map[keybase1.UID]libkb.NormalizedUsername {
+ return h.resolvedReaders
+}
+
+// ResolvedWritersMap returns a map of resolved writers from uid to usernames.
+func (h TlfHandle) ResolvedWritersMap() map[keybase1.UID]libkb.NormalizedUsername {
+ return h.resolvedWriters
+}
+
func (h TlfHandle) unsortedResolvedWriters() []keybase1.UID {
if len(h.resolvedWriters) == 0 {
return nil | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
// This file has the type for TlfHandles and offline functionality.
import (
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/keybase/client/go/externals"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfscodec"
"github.com/keybase/kbfs/tlf"
"golang.org/x/net/context"
)
// CanonicalTlfName is a string containing the canonical name of a TLF.
type CanonicalTlfName string
// TlfHandle contains all the info in a tlf.Handle as well as
// additional info. This doesn't embed tlf.Handle to avoid having to
// keep track of data in multiple places.
type TlfHandle struct {
// If this is true, resolvedReaders and unresolvedReaders
// should both be nil.
public bool
resolvedWriters map[keybase1.UID]libkb.NormalizedUsername
resolvedReaders map[keybase1.UID]libkb.NormalizedUsername
// Both unresolvedWriters and unresolvedReaders are stored in
// sorted order.
unresolvedWriters []keybase1.SocialAssertion
unresolvedReaders []keybase1.SocialAssertion
conflictInfo *tlf.HandleExtension
finalizedInfo *tlf.HandleExtension
// name can be computed from the other fields, but is cached
// for speed.
name CanonicalTlfName
}
// IsPublic returns whether or not this TlfHandle represents a public
// top-level folder.
func (h TlfHandle) IsPublic() bool {
return h.public
}
// IsWriter returns whether or not the given user is a writer for the
// top-level folder represented by this TlfHandle.
func (h TlfHandle) IsWriter(user keybase1.UID) bool {
_, ok := h.resolvedWriters[user]
return ok
}
// IsReader returns whether or not the given user is a reader for the
// top-level folder represented by this TlfHandle.
func (h TlfHandle) IsReader(user keybase1.UID) bool {
if h.public || h.IsWriter(user) {
return true
}
_, ok := h.resolvedReaders[user]
return ok
}
func (h TlfHandle) unsortedResolvedWriters() []keybase1.UID {
if len(h.resolvedWriters) == 0 {
return nil
}
writers := make([]keybase1.UID, 0, len(h.resolvedWriters))
for r := range h.resolvedWriters {
writers = append(writers, r)
}
return writers
}
// ResolvedWriters returns the handle's resolved writer UIDs in sorted
// order.
func (h TlfHandle) ResolvedWriters() []keybase1.UID {
writers := h.unsortedResolvedWriters()
sort.Sort(tlf.UIDList(writers))
return writers
}
// FirstResolvedWriter returns the handle's first resolved writer UID
// (when sorted). This is used mostly for tests.
func (h TlfHandle) FirstResolvedWriter() keybase1.UID {
return h.ResolvedWriters()[0]
}
func (h TlfHandle) unsortedResolvedReaders() []keybase1.UID {
if len(h.resolvedReaders) == 0 {
return nil
}
readers := make([]keybase1.UID, 0, len(h.resolvedReaders))
for r := range h.resolvedReaders {
readers = append(readers, r)
}
return readers
}
// ResolvedReaders returns the handle's resolved reader UIDs in sorted
// order. If the handle is public, nil will be returned.
func (h TlfHandle) ResolvedReaders() []keybase1.UID {
readers := h.unsortedResolvedReaders()
sort.Sort(tlf.UIDList(readers))
return readers
}
// UnresolvedWriters returns the handle's unresolved writers in sorted
// order.
func (h TlfHandle) UnresolvedWriters() []keybase1.SocialAssertion {
if len(h.unresolvedWriters) == 0 {
return nil
}
unresolvedWriters := make([]keybase1.SocialAssertion, len(h.unresolvedWriters))
copy(unresolvedWriters, h.unresolvedWriters)
return unresolvedWriters
}
// UnresolvedReaders returns the handle's unresolved readers in sorted
// order. If the handle is public, nil will be returned.
func (h TlfHandle) UnresolvedReaders() []keybase1.SocialAssertion {
if len(h.unresolvedReaders) == 0 {
return nil
}
unresolvedReaders := make([]keybase1.SocialAssertion, len(h.unresolvedReaders))
copy(unresolvedReaders, h.unresolvedReaders)
return unresolvedReaders
}
// ConflictInfo returns the handle's conflict info, if any.
func (h TlfHandle) ConflictInfo() *tlf.HandleExtension {
if h.conflictInfo == nil {
return nil
}
conflictInfoCopy := *h.conflictInfo
return &conflictInfoCopy
}
func (h TlfHandle) recomputeNameWithExtensions() CanonicalTlfName {
components := strings.Split(string(h.name), tlf.HandleExtensionSep)
newName := components[0]
extensionList := tlf.HandleExtensionList(h.Extensions())
sort.Sort(extensionList)
newName += extensionList.Suffix()
return CanonicalTlfName(newName)
}
// WithUpdatedConflictInfo returns a new handle with the conflict info set to
// the given one, if the existing one is nil. (In this case, the given one may
// also be nil.) Otherwise, the given conflict info must match the existing
// one.
func (h TlfHandle) WithUpdatedConflictInfo(
codec kbfscodec.Codec, info *tlf.HandleExtension) (*TlfHandle, error) {
newHandle := h.deepCopy()
if newHandle.conflictInfo == nil {
if info == nil {
// Nothing to do.
return newHandle, nil
}
conflictInfoCopy := *info
newHandle.conflictInfo = &conflictInfoCopy
newHandle.name = newHandle.recomputeNameWithExtensions()
return newHandle, nil
}
// Make sure conflict info is the same; the conflict info for
// a TLF, once set, is immutable and should never change.
equal, err := kbfscodec.Equal(codec, newHandle.conflictInfo, info)
if err != nil {
return newHandle, err
}
if !equal {
return newHandle, tlf.HandleExtensionMismatchError{
Expected: *newHandle.ConflictInfo(),
Actual: info,
}
}
return newHandle, nil
}
// FinalizedInfo returns the handle's finalized info, if any.
func (h TlfHandle) FinalizedInfo() *tlf.HandleExtension {
if h.finalizedInfo == nil {
return nil
}
finalizedInfoCopy := *h.finalizedInfo
return &finalizedInfoCopy
}
// SetFinalizedInfo sets the handle's finalized info to the given one,
// which may be nil.
// TODO: remove this to make TlfHandle fully immutable
func (h *TlfHandle) SetFinalizedInfo(info *tlf.HandleExtension) {
if info == nil {
h.finalizedInfo = nil
} else {
finalizedInfoCopy := *info
h.finalizedInfo = &finalizedInfoCopy
}
h.name = h.recomputeNameWithExtensions()
}
// Extensions returns a list of extensions for the given handle.
func (h TlfHandle) Extensions() (extensions []tlf.HandleExtension) {
if h.ConflictInfo() != nil {
extensions = append(extensions, *h.ConflictInfo())
}
if h.FinalizedInfo() != nil {
extensions = append(extensions, *h.FinalizedInfo())
}
return extensions
}
func init() {
if reflect.ValueOf(TlfHandle{}).NumField() != 8 {
panic(errors.New(
"Unexpected number of fields in TlfHandle; " +
"please update TlfHandle.Equals() for your " +
"new or removed field"))
}
}
// EqualsIgnoreName returns whether h and other contain the same info ignoring the name.
func (h TlfHandle) EqualsIgnoreName(
codec kbfscodec.Codec, other TlfHandle) (bool, error) {
if h.public != other.public {
return false, nil
}
if !reflect.DeepEqual(h.resolvedWriters, other.resolvedWriters) {
return false, nil
}
if !reflect.DeepEqual(h.resolvedReaders, other.resolvedReaders) {
return false, nil
}
if !reflect.DeepEqual(h.unresolvedWriters, other.unresolvedWriters) {
return false, nil
}
if !reflect.DeepEqual(h.unresolvedReaders, other.unresolvedReaders) {
return false, nil
}
eq, err := kbfscodec.Equal(codec, h.conflictInfo, other.conflictInfo)
if err != nil {
return false, err
}
if !eq {
return false, nil
}
eq, err = kbfscodec.Equal(codec, h.finalizedInfo, other.finalizedInfo)
if err != nil {
return false, err
}
return eq, nil
}
// Equals returns whether h and other contain the same info.
func (h TlfHandle) Equals(
codec kbfscodec.Codec, other TlfHandle) (bool, error) {
eq, err := h.EqualsIgnoreName(codec, other)
if err != nil {
return false, err
}
if eq && h.name != other.name {
panic(fmt.Errorf(
"%+v equals %+v in everything but name", h, other))
}
return eq, nil
}
// ToBareHandle returns a tlf.Handle corresponding to this handle.
func (h TlfHandle) ToBareHandle() (tlf.Handle, error) {
var readers []keybase1.UID
if h.public {
readers = []keybase1.UID{keybase1.PUBLIC_UID}
} else {
readers = h.unsortedResolvedReaders()
}
return tlf.MakeHandle(
h.unsortedResolvedWriters(), readers,
h.unresolvedWriters, h.unresolvedReaders,
h.Extensions())
}
// ToBareHandleOrBust returns a tlf.Handle corresponding to this
// handle, and panics if there's an error. Used by tests.
func (h TlfHandle) ToBareHandleOrBust() tlf.Handle {
bh, err := h.ToBareHandle()
if err != nil {
panic(err)
}
return bh
}
func (h TlfHandle) deepCopy() *TlfHandle {
hCopy := TlfHandle{
public: h.public,
name: h.name,
unresolvedWriters: h.UnresolvedWriters(),
unresolvedReaders: h.UnresolvedReaders(),
conflictInfo: h.ConflictInfo(),
finalizedInfo: h.FinalizedInfo(),
}
hCopy.resolvedWriters = make(map[keybase1.UID]libkb.NormalizedUsername, len(h.resolvedWriters))
for k, v := range h.resolvedWriters {
hCopy.resolvedWriters[k] = v
}
hCopy.resolvedReaders = make(map[keybase1.UID]libkb.NormalizedUsername, len(h.resolvedReaders))
for k, v := range h.resolvedReaders {
hCopy.resolvedReaders[k] = v
}
return &hCopy
}
func getSortedNames(
uidToName map[keybase1.UID]libkb.NormalizedUsername,
unresolved []keybase1.SocialAssertion) []string {
var names []string
for _, name := range uidToName {
names = append(names, name.String())
}
for _, sa := range unresolved {
names = append(names, sa.String())
}
sort.Sort(sort.StringSlice(names))
return names
}
// GetCanonicalName returns the canonical name of this TLF.
func (h *TlfHandle) GetCanonicalName() CanonicalTlfName {
if h.name == "" {
panic(fmt.Sprintf("TlfHandle %v with no name", h))
}
return h.name
}
// GetCanonicalPath returns the full canonical path of this TLF.
func (h *TlfHandle) GetCanonicalPath() string {
return buildCanonicalPathForTlfName(h.IsPublic(), h.GetCanonicalName())
}
// ToFavorite converts a TlfHandle into a Favorite, suitable for
// Favorites calls.
func (h *TlfHandle) ToFavorite() Favorite {
return Favorite{
Name: string(h.GetCanonicalName()),
Public: h.IsPublic(),
}
}
// ToFavorite converts a TlfHandle into a Favorite, and sets internal
// state about whether the corresponding folder was just created or
// not.
func (h *TlfHandle) toFavToAdd(created bool) favToAdd {
return favToAdd{
Favorite: h.ToFavorite(),
created: created,
}
}
func getSortedUnresolved(unresolved map[keybase1.SocialAssertion]bool) []keybase1.SocialAssertion {
var assertions []keybase1.SocialAssertion
for sa := range unresolved {
assertions = append(assertions, sa)
}
sort.Sort(tlf.SocialAssertionList(assertions))
return assertions
}
// splitTLFName splits a TLF name into components.
func splitTLFName(name string) (writerNames, readerNames []string,
extensionSuffix string, err error) {
names := strings.SplitN(name, tlf.HandleExtensionSep, 2)
if len(names) > 2 {
return nil, nil, "", BadTLFNameError{name}
}
if len(names) > 1 {
extensionSuffix = names[1]
}
splitNames := strings.SplitN(names[0], ReaderSep, 3)
if len(splitNames) > 2 {
return nil, nil, "", BadTLFNameError{name}
}
writerNames = strings.Split(splitNames[0], ",")
if len(splitNames) > 1 {
readerNames = strings.Split(splitNames[1], ",")
}
return writerNames, readerNames, extensionSuffix, nil
}
// splitAndNormalizeTLFName takes a tlf name as a string
// and tries to normalize it offline. In addition to other
// checks it returns TlfNameNotCanonical if it does not
// look canonical.
// Note that ordering differences do not result in TlfNameNotCanonical
// being returned.
func splitAndNormalizeTLFName(name string, public bool) (
writerNames, readerNames []string,
extensionSuffix string, err error) {
writerNames, readerNames, extensionSuffix, err = splitTLFName(name)
if err != nil {
return nil, nil, "", err
}
hasPublic := len(readerNames) == 0
if public && !hasPublic {
// No public folder exists for this folder.
return nil, nil, "", NoSuchNameError{Name: name}
}
normalizedName, changes, err := normalizeNamesInTLF(
writerNames, readerNames, extensionSuffix)
if err != nil {
return nil, nil, "", err
}
// Check for changes - not just ordering differences here.
if changes {
return nil, nil, "", TlfNameNotCanonical{name, normalizedName}
}
return writerNames, readerNames, strings.ToLower(extensionSuffix), nil
}
// TODO: this function can likely be replaced with a call to
// AssertionParseAndOnly when CORE-2967 and CORE-2968 are fixed.
func normalizeAssertionOrName(s string) (string, error) {
if libkb.CheckUsername.F(s) {
return libkb.NewNormalizedUsername(s).String(), nil
}
// TODO: this fails for http and https right now (see CORE-2968).
socialAssertion, isSocialAssertion := externals.NormalizeSocialAssertion(s)
if isSocialAssertion {
return socialAssertion.String(), nil
}
if expr, err := externals.AssertionParseAndOnly(s); err == nil {
// If the expression only contains a single url, make sure
// it's not a just considered a single keybase username. If
// it is, then some non-username slipped into the default
// "keybase" case and should be considered an error.
urls := expr.CollectUrls(nil)
if len(urls) == 1 && urls[0].IsKeybase() {
return "", NoSuchUserError{s}
}
// Normalize and return. Ideally `AssertionParseAndOnly`
// would normalize for us, but that doesn't work yet, so for
// now we'll just lower-case. This will incorrectly lower
// case http/https/web assertions, as well as case-sensitive
// social assertions in AND expressions. TODO: see CORE-2967.
return strings.ToLower(s), nil
}
return "", BadTLFNameError{s}
}
// normalizeNames normalizes a slice of names and returns
// whether any of them changed.
func normalizeNames(names []string) (changesMade bool, err error) {
for i, name := range names {
x, err := normalizeAssertionOrName(name)
if err != nil {
return false, err
}
if x != name {
names[i] = x
changesMade = true
}
}
return changesMade, nil
}
// normalizeNamesInTLF takes a split TLF name and, without doing any
// resolutions or identify calls, normalizes all elements of the
// name. It then returns the normalized name and a boolean flag
// whether any names were modified.
// This modifies the slices passed as arguments.
func normalizeNamesInTLF(writerNames, readerNames []string,
extensionSuffix string) (normalizedName string,
changesMade bool, err error) {
changesMade, err = normalizeNames(writerNames)
if err != nil {
return "", false, err
}
sort.Strings(writerNames)
normalizedName = strings.Join(writerNames, ",")
if len(readerNames) > 0 {
rchanges, err := normalizeNames(readerNames)
if err != nil {
return "", false, err
}
changesMade = changesMade || rchanges
sort.Strings(readerNames)
normalizedName += ReaderSep + strings.Join(readerNames, ",")
}
if len(extensionSuffix) != 0 {
// This *should* be normalized already but make sure. I can see not
// doing so might surprise a caller.
nExt := strings.ToLower(extensionSuffix)
normalizedName += tlf.HandleExtensionSep + nExt
changesMade = changesMade || nExt != extensionSuffix
}
return normalizedName, changesMade, nil
}
// CheckTlfHandleOffline does light checks whether a TLF handle looks ok,
// it avoids all network calls.
func CheckTlfHandleOffline(
ctx context.Context, name string, public bool) error {
_, _, _, err := splitAndNormalizeTLFName(name, public)
return err
}
// IsFinal returns whether or not this TlfHandle represents a finalized
// top-level folder.
func (h TlfHandle) IsFinal() bool {
return h.finalizedInfo != nil
}
// IsConflict returns whether or not this TlfHandle represents a conflicted
// top-level folder.
func (h TlfHandle) IsConflict() bool {
return h.conflictInfo != nil
}
// PreferredTlfName is a preferred Tlf name.
type PreferredTlfName string
// GetPreferredFormat returns a TLF name formatted with the username given
// as the parameter first.
// This calls FavoriteNameToPreferredTLFNameFormatAs with the canonical
// tlf name which will be reordered into the preferred format.
// An empty username is allowed here and results in the canonical ordering.
func (h TlfHandle) GetPreferredFormat(
username libkb.NormalizedUsername) PreferredTlfName {
s, err := FavoriteNameToPreferredTLFNameFormatAs(
username, h.GetCanonicalName())
if err != nil {
panic("TlfHandle.GetPreferredFormat: Parsing canonical username failed!")
}
return s
}
// FavoriteNameToPreferredTLFNameFormatAs formats a favorite names for display with the
// username given.
// An empty username is allowed here and results in tlfname being returned unmodified.
func FavoriteNameToPreferredTLFNameFormatAs(username libkb.NormalizedUsername,
canon CanonicalTlfName) (PreferredTlfName, error) {
tlfname := string(canon)
if len(username) == 0 {
return PreferredTlfName(tlfname), nil
}
ws, rs, ext, err := splitTLFName(tlfname)
if err != nil {
return "", err
}
if len(ws) == 0 {
return "", fmt.Errorf("TLF name %q with no writers", tlfname)
}
uname := username.String()
for i, w := range ws {
if w == uname {
if i != 0 {
copy(ws[1:i+1], ws[0:i])
ws[0] = w
tlfname = strings.Join(ws, ",")
if len(rs) > 0 {
tlfname += ReaderSep + strings.Join(rs, ",")
}
if len(ext) > 0 {
tlfname += tlf.HandleExtensionSep + ext
}
}
break
}
}
return PreferredTlfName(tlfname), nil
}
| 1 | 16,082 | Can you change this to `ResolvedUsersMap` and build a new map with both readers/writers? That way, we get the nice side effect of not exposing the internal map of the handle, and simplifying the callers a bit. | keybase-kbfs | go |
@@ -439,10 +439,12 @@ function createTopology(mongoClient, topologyType, options, callback) {
}
const MongoClient = loadClient();
- const connectionString =
- os.platform() === 'win32'
- ? 'mongodb://localhost:27020/?serverSelectionTimeoutMS=1000'
- : 'mongodb://%2Ftmp%2Fmongocryptd.sock/?serverSelectionTimeoutMS=1000';
+ let connectionString =
+ mongoClient.s.options.cryptdConnectionString != null
+ ? mongoClient.s.options.cryptdConnectionString
+ : os.platform() === 'win32'
+ ? 'mongodb://localhost:27020/?serverSelectionTimeoutMS=1000'
+ : 'mongodb://%2Ftmp%2Fmongocryptd.sock/?serverSelectionTimeoutMS=1000';
const mongocryptdClient = new MongoClient(connectionString, { useUnifiedTopology: true });
mongocryptdClient.connect(err => { | 1 | 'use strict';
const deprecate = require('util').deprecate;
const Logger = require('../core').Logger;
const MongoError = require('../core').MongoError;
const Mongos = require('../topologies/mongos');
const parse = require('../core').parseConnectionString;
const ReadPreference = require('../core').ReadPreference;
const ReplSet = require('../topologies/replset');
const Server = require('../topologies/server');
const ServerSessionPool = require('../core').Sessions.ServerSessionPool;
const NativeTopology = require('../topologies/native_topology');
const MongoCredentials = require('../core').MongoCredentials;
const ReadConcern = require('../read_concern');
const os = require('os');
let client;
function loadClient() {
if (!client) {
client = require('../mongo_client');
}
return client;
}
const monitoringEvents = [
'timeout',
'close',
'serverOpening',
'serverDescriptionChanged',
'serverHeartbeatStarted',
'serverHeartbeatSucceeded',
'serverHeartbeatFailed',
'serverClosed',
'topologyOpening',
'topologyClosed',
'topologyDescriptionChanged',
'commandStarted',
'commandSucceeded',
'commandFailed',
'joined',
'left',
'ping',
'ha',
'all',
'fullsetup',
'open'
];
const ignoreOptionNames = ['native_parser'];
const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db'];
const legacyParse = deprecate(
require('../url_parser'),
'current URL string parser is deprecated, and will be removed in a future version. ' +
'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.'
);
const validOptionNames = [
'poolSize',
'ssl',
'sslValidate',
'sslCA',
'sslCert',
'sslKey',
'sslPass',
'sslCRL',
'autoReconnect',
'noDelay',
'keepAlive',
'keepAliveInitialDelay',
'connectTimeoutMS',
'family',
'socketTimeoutMS',
'reconnectTries',
'reconnectInterval',
'ha',
'haInterval',
'replicaSet',
'secondaryAcceptableLatencyMS',
'acceptableLatencyMS',
'connectWithNoPrimary',
'authSource',
'w',
'wtimeout',
'j',
'forceServerObjectId',
'serializeFunctions',
'ignoreUndefined',
'raw',
'bufferMaxEntries',
'readPreference',
'pkFactory',
'promiseLibrary',
'readConcern',
'maxStalenessSeconds',
'loggerLevel',
'logger',
'promoteValues',
'promoteBuffers',
'promoteLongs',
'domainsEnabled',
'checkServerIdentity',
'validateOptions',
'appname',
'auth',
'user',
'password',
'authMechanism',
'compression',
'fsync',
'readPreferenceTags',
'numberOfRetries',
'auto_reconnect',
'minSize',
'monitorCommands',
'retryWrites',
'useNewUrlParser',
'useUnifiedTopology',
'serverSelectionTimeoutMS',
'useRecoveryToken',
'autoEncryption'
];
function addListeners(mongoClient, topology) {
topology.on('authenticated', createListener(mongoClient, 'authenticated'));
topology.on('error', createListener(mongoClient, 'error'));
topology.on('timeout', createListener(mongoClient, 'timeout'));
topology.on('close', createListener(mongoClient, 'close'));
topology.on('parseError', createListener(mongoClient, 'parseError'));
topology.once('open', createListener(mongoClient, 'open'));
topology.once('fullsetup', createListener(mongoClient, 'fullsetup'));
topology.once('all', createListener(mongoClient, 'all'));
topology.on('reconnect', createListener(mongoClient, 'reconnect'));
}
function assignTopology(client, topology) {
client.topology = topology;
topology.s.sessionPool =
topology instanceof NativeTopology
? new ServerSessionPool(topology)
: new ServerSessionPool(topology.s.coreTopology);
}
// Clear out all events
function clearAllEvents(topology) {
monitoringEvents.forEach(event => topology.removeAllListeners(event));
}
// Collect all events in order from SDAM
function collectEvents(mongoClient, topology) {
let MongoClient = loadClient();
const collectedEvents = [];
if (mongoClient instanceof MongoClient) {
monitoringEvents.forEach(event => {
topology.on(event, (object1, object2) => {
if (event === 'open') {
collectedEvents.push({ event: event, object1: mongoClient });
} else {
collectedEvents.push({ event: event, object1: object1, object2: object2 });
}
});
});
}
return collectedEvents;
}
/**
* Connect to MongoDB using a url as documented at
*
* docs.mongodb.org/manual/reference/connection-string/
*
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
*
* @method
* @param {MongoClient} mongoClient The MongoClient instance with which to connect.
* @param {string} url The connection URI string
* @param {object} [options] Optional settings. See MongoClient.prototype.connect for a list of options.
* @param {MongoClient~connectCallback} [callback] The command result callback
*/
function connect(mongoClient, url, options, callback) {
options = Object.assign({}, options);
// If callback is null throw an exception
if (callback == null) {
throw new Error('no callback function provided');
}
let didRequestAuthentication = false;
const logger = Logger('MongoClient', options);
// Did we pass in a Server/ReplSet/Mongos
if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) {
return connectWithUrl(mongoClient, url, options, connectCallback);
}
const parseFn = options.useNewUrlParser ? parse : legacyParse;
const transform = options.useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions;
parseFn(url, options, (err, _object) => {
// Do not attempt to connect if parsing error
if (err) return callback(err);
// Flatten
const object = transform(_object);
// Parse the string
const _finalOptions = createUnifiedOptions(object, options);
// Check if we have connection and socket timeout set
if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000;
if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000;
if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true;
if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true;
if (_finalOptions.db_options && _finalOptions.db_options.auth) {
delete _finalOptions.db_options.auth;
}
// Store the merged options object
mongoClient.s.options = _finalOptions;
// Failure modes
if (object.servers.length === 0) {
return callback(new Error('connection string must contain at least one seed host'));
}
if (_finalOptions.auth && !_finalOptions.credentials) {
try {
didRequestAuthentication = true;
_finalOptions.credentials = generateCredentials(
mongoClient,
_finalOptions.auth.user,
_finalOptions.auth.password,
_finalOptions
);
} catch (err) {
return callback(err);
}
}
if (_finalOptions.useUnifiedTopology) {
return createTopology(mongoClient, 'unified', _finalOptions, connectCallback);
}
// Do we have a replicaset then skip discovery and go straight to connectivity
if (_finalOptions.replicaSet || _finalOptions.rs_name) {
return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback);
} else if (object.servers.length > 1) {
return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback);
} else {
return createServer(mongoClient, _finalOptions, connectCallback);
}
});
function connectCallback(err, topology) {
const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`;
if (err && err.message === 'no mongos proxies found in seed list') {
if (logger.isWarn()) {
logger.warn(warningMessage);
}
// Return a more specific error message for MongoClient.connect
return callback(new MongoError(warningMessage));
}
if (didRequestAuthentication) {
mongoClient.emit('authenticated', null, true);
}
// Return the error and db instance
callback(err, topology);
}
}
/**
* Connect to MongoDB using a url as documented at
*
* docs.mongodb.org/manual/reference/connection-string/
*
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
*
* @method
* @param {MongoClient} mongoClient The MongoClient instance with which to connect.
* @param {MongoClient~connectCallback} [callback] The command result callback
*/
function connectOp(mongoClient, err, callback) {
// Did we have a validation error
if (err) return callback(err);
// Fallback to callback based connect
connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => {
if (err) return callback(err);
callback(null, mongoClient);
});
}
function connectWithUrl(mongoClient, url, options, connectCallback) {
// Set the topology
assignTopology(mongoClient, url);
// Add listeners
addListeners(mongoClient, url);
// Propagate the events to the client
relayEvents(mongoClient, url);
let finalOptions = Object.assign({}, options);
// If we have a readPreference passed in by the db options, convert it from a string
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
finalOptions.readPreference = new ReadPreference(
options.readPreference || options.read_preference
);
}
const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism;
if (isDoingAuth && !finalOptions.credentials) {
try {
finalOptions.credentials = generateCredentials(
mongoClient,
finalOptions.user,
finalOptions.password,
finalOptions
);
} catch (err) {
return connectCallback(err, url);
}
}
return url.connect(finalOptions, connectCallback);
}
function createListener(mongoClient, event) {
const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']);
return (v1, v2) => {
if (eventSet.has(event)) {
return mongoClient.emit(event, mongoClient);
}
mongoClient.emit(event, v1, v2);
};
}
function createServer(mongoClient, options, callback) {
// Pass in the promise library
options.promiseLibrary = mongoClient.s.promiseLibrary;
// Set default options
const servers = translateOptions(options);
const server = servers[0];
// Propagate the events to the client
const collectedEvents = collectEvents(mongoClient, server);
// Connect to topology
server.connect(options, (err, topology) => {
if (err) {
server.close(true);
return callback(err);
}
// Clear out all the collected event listeners
clearAllEvents(server);
// Relay all the events
relayEvents(mongoClient, server);
// Add listeners
addListeners(mongoClient, server);
// Check if we are really speaking to a mongos
const ismaster = topology.lastIsMaster();
// Set the topology
assignTopology(mongoClient, topology);
// Do we actually have a mongos
if (ismaster && ismaster.msg === 'isdbgrid') {
// Destroy the current connection
topology.close();
// Create mongos connection instead
return createTopology(mongoClient, 'mongos', options, callback);
}
// Fire all the events
replayEvents(mongoClient, collectedEvents);
// Otherwise callback
callback(err, topology);
});
}
function createTopology(mongoClient, topologyType, options, callback) {
// Pass in the promise library
options.promiseLibrary = mongoClient.s.promiseLibrary;
const translationOptions = {};
if (topologyType === 'unified') translationOptions.createServers = false;
// Set default options
const servers = translateOptions(options, translationOptions);
// Create the topology
let topology;
if (topologyType === 'mongos') {
topology = new Mongos(servers, options);
} else if (topologyType === 'replicaset') {
topology = new ReplSet(servers, options);
} else if (topologyType === 'unified') {
topology = new NativeTopology(options.servers, options);
}
// Add listeners
addListeners(mongoClient, topology);
// Propagate the events to the client
relayEvents(mongoClient, topology);
// Open the connection
topology.connect(options, (err, newTopology) => {
if (err) {
topology.close(true);
return callback(err);
}
assignTopology(mongoClient, newTopology);
if (options.autoEncryption == null) {
callback(null, newTopology);
return;
}
// setup for client side encryption
let AutoEncrypter;
try {
AutoEncrypter = require('mongodb-client-encryption').AutoEncrypter;
} catch (err) {
callback(
new MongoError(
'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project'
)
);
return;
}
const MongoClient = loadClient();
const connectionString =
os.platform() === 'win32'
? 'mongodb://localhost:27020/?serverSelectionTimeoutMS=1000'
: 'mongodb://%2Ftmp%2Fmongocryptd.sock/?serverSelectionTimeoutMS=1000';
const mongocryptdClient = new MongoClient(connectionString, { useUnifiedTopology: true });
mongocryptdClient.connect(err => {
if (err) return callback(err, null);
const mongoCryptOptions = Object.assign({}, options.autoEncryption, {
mongocryptdClient
});
topology.s.options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions);
callback(null, newTopology);
});
});
}
function createUnifiedOptions(finalOptions, options) {
const childOptions = [
'mongos',
'server',
'db',
'replset',
'db_options',
'server_options',
'rs_options',
'mongos_options'
];
const noMerge = ['readconcern', 'compression'];
for (const name in options) {
if (noMerge.indexOf(name.toLowerCase()) !== -1) {
finalOptions[name] = options[name];
} else if (childOptions.indexOf(name.toLowerCase()) !== -1) {
finalOptions = mergeOptions(finalOptions, options[name], false);
} else {
if (
options[name] &&
typeof options[name] === 'object' &&
!Buffer.isBuffer(options[name]) &&
!Array.isArray(options[name])
) {
finalOptions = mergeOptions(finalOptions, options[name], true);
} else {
finalOptions[name] = options[name];
}
}
}
return finalOptions;
}
function legacyTransformUrlOptions(object) {
return mergeOptions(createUnifiedOptions({}, object), object, false);
}
function mergeOptions(target, source, flatten) {
for (const name in source) {
if (source[name] && typeof source[name] === 'object' && flatten) {
target = mergeOptions(target, source[name], flatten);
} else {
target[name] = source[name];
}
}
return target;
}
function relayEvents(mongoClient, topology) {
const serverOrCommandEvents = [
'serverOpening',
'serverDescriptionChanged',
'serverHeartbeatStarted',
'serverHeartbeatSucceeded',
'serverHeartbeatFailed',
'serverClosed',
'topologyOpening',
'topologyClosed',
'topologyDescriptionChanged',
'commandStarted',
'commandSucceeded',
'commandFailed',
'joined',
'left',
'ping',
'ha'
];
serverOrCommandEvents.forEach(event => {
topology.on(event, (object1, object2) => {
mongoClient.emit(event, object1, object2);
});
});
}
//
// Replay any events due to single server connection switching to Mongos
//
function replayEvents(mongoClient, events) {
for (let i = 0; i < events.length; i++) {
mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
}
}
const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => {
obj[name.toLowerCase()] = name;
return obj;
}, {});
function transformUrlOptions(_object) {
let object = Object.assign({ servers: _object.hosts }, _object.options);
for (let name in object) {
const camelCaseName = LEGACY_OPTIONS_MAP[name];
if (camelCaseName) {
object[camelCaseName] = object[name];
}
}
const hasUsername = _object.auth && _object.auth.username;
const hasAuthMechanism = _object.options && _object.options.authMechanism;
if (hasUsername || hasAuthMechanism) {
object.auth = Object.assign({}, _object.auth);
if (object.auth.db) {
object.authSource = object.authSource || object.auth.db;
}
if (object.auth.username) {
object.auth.user = object.auth.username;
}
}
if (_object.defaultDatabase) {
object.dbName = _object.defaultDatabase;
}
if (object.maxpoolsize) {
object.poolSize = object.maxpoolsize;
}
if (object.readconcernlevel) {
object.readConcern = new ReadConcern(object.readconcernlevel);
}
if (object.wtimeoutms) {
object.wtimeout = object.wtimeoutms;
}
if (_object.srvHost) {
object.srvHost = _object.srvHost;
}
return object;
}
function translateOptions(options, translationOptions) {
translationOptions = Object.assign({}, { createServers: true }, translationOptions);
// If we have a readPreference passed in by the db options
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
options.readPreference = new ReadPreference(options.readPreference || options.read_preference);
}
// Do we have readPreference tags, add them
if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) {
options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags;
}
// Do we have maxStalenessSeconds
if (options.maxStalenessSeconds) {
options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds;
}
// Set the socket and connection timeouts
if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000;
if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000;
if (!translationOptions.createServers) {
return;
}
// Create server instances
return options.servers.map(serverObj => {
return serverObj.domain_socket
? new Server(serverObj.domain_socket, 27017, options)
: new Server(serverObj.host, serverObj.port, options);
});
}
// Validate options object
function validOptions(options) {
const _validOptions = validOptionNames.concat(legacyOptionNames);
for (const name in options) {
if (ignoreOptionNames.indexOf(name) !== -1) {
continue;
}
if (_validOptions.indexOf(name) === -1) {
if (options.validateOptions) {
return new MongoError(`option ${name} is not supported`);
} else {
console.warn(`the options [${name}] is not supported`);
}
}
if (legacyOptionNames.indexOf(name) !== -1) {
console.warn(
`the server/replset/mongos/db options are deprecated, ` +
`all their options are supported at the top level of the options object [${validOptionNames}]`
);
}
}
}
const VALID_AUTH_MECHANISMS = new Set([
'DEFAULT',
'MONGODB-CR',
'PLAIN',
'MONGODB-X509',
'SCRAM-SHA-1',
'SCRAM-SHA-256',
'GSSAPI'
]);
const AUTH_MECHANISM_INTERNAL_MAP = {
DEFAULT: 'default',
'MONGODB-CR': 'mongocr',
PLAIN: 'plain',
'MONGODB-X509': 'x509',
'SCRAM-SHA-1': 'scram-sha-1',
'SCRAM-SHA-256': 'scram-sha-256'
};
function generateCredentials(client, username, password, options) {
options = Object.assign({}, options);
// the default db to authenticate against is 'self'
// if authenticate is called from a retry context, it may be another one, like admin
const source = options.authSource || options.authdb || options.dbName;
// authMechanism
const authMechanismRaw = options.authMechanism || 'DEFAULT';
const authMechanism = authMechanismRaw.toUpperCase();
if (!VALID_AUTH_MECHANISMS.has(authMechanism)) {
throw MongoError.create({
message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`,
driver: true
});
}
if (authMechanism === 'GSSAPI') {
return new MongoCredentials({
mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi',
mechanismProperties: options,
source,
username,
password
});
}
return new MongoCredentials({
mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism],
source,
username,
password
});
}
function closeOperation(client, force, callback) {
const completeClose = err => {
client.emit('close', client);
for (const name in client.s.dbCache) {
client.s.dbCache[name].emit('close', client);
}
client.removeAllListeners('close');
callback(err, null);
};
if (client.topology == null) {
completeClose();
return;
}
client.topology.close(force, completeClose);
}
module.exports = { connectOp, validOptions, closeOperation };
| 1 | 15,912 | I typically try to avoid nested ternary expressions. Can we rewrite this as if statements? Worst case, can we break it out into its own function? | mongodb-node-mongodb-native | js |
@@ -427,7 +427,8 @@ if __name__ == "__main__": # pragma: no cover
tls_start.ssl_conn.set_accept_state()
else:
tls_start.ssl_conn.set_connect_state()
- tls_start.ssl_conn.set_tlsext_host_name(tls_start.context.client.sni)
+ if tls_start.context.client.sni is not None:
+ tls_start.ssl_conn.set_tlsext_host_name(tls_start.context.client.sni.encode())
await SimpleConnectionHandler(reader, writer, opts, {
"next_layer": next_layer, | 1 | """
Proxy Server Implementation using asyncio.
The very high level overview is as follows:
- Spawn one coroutine per client connection and create a reverse proxy layer to example.com
- Process any commands from layer (such as opening a server connection)
- Wait for any IO and send it as events to top layer.
"""
import abc
import asyncio
import collections
import time
import traceback
import typing
from contextlib import contextmanager
from dataclasses import dataclass
from OpenSSL import SSL
from mitmproxy import http, options as moptions
from mitmproxy.proxy.layers.http import HTTPMode
from mitmproxy.proxy import commands, events, layer, layers, server_hooks
from mitmproxy.proxy.context import Address, Client, Connection, ConnectionState, Context
from mitmproxy.proxy.layers import tls
from mitmproxy.utils import asyncio_utils
from mitmproxy.utils import human
from mitmproxy.utils.data import pkg_data
class TimeoutWatchdog:
last_activity: float
CONNECTION_TIMEOUT = 10 * 60
can_timeout: asyncio.Event
blocker: int
def __init__(self, callback: typing.Callable[[], typing.Any]):
self.callback = callback
self.last_activity = time.time()
self.can_timeout = asyncio.Event()
self.can_timeout.set()
self.blocker = 0
def register_activity(self):
self.last_activity = time.time()
async def watch(self):
while True:
await self.can_timeout.wait()
await asyncio.sleep(self.CONNECTION_TIMEOUT - (time.time() - self.last_activity))
if self.last_activity + self.CONNECTION_TIMEOUT < time.time():
await self.callback()
return
@contextmanager
def disarm(self):
self.can_timeout.clear()
self.blocker += 1
try:
yield
finally:
self.blocker -= 1
if self.blocker == 0:
self.register_activity()
self.can_timeout.set()
@dataclass
class ConnectionIO:
handler: typing.Optional[asyncio.Task] = None
reader: typing.Optional[asyncio.StreamReader] = None
writer: typing.Optional[asyncio.StreamWriter] = None
class ConnectionHandler(metaclass=abc.ABCMeta):
transports: typing.MutableMapping[Connection, ConnectionIO]
timeout_watchdog: TimeoutWatchdog
client: Client
max_conns: typing.DefaultDict[Address, asyncio.Semaphore]
layer: layer.Layer
def __init__(self, context: Context) -> None:
self.client = context.client
self.transports = {}
self.max_conns = collections.defaultdict(lambda: asyncio.Semaphore(5))
# Ask for the first layer right away.
# In a reverse proxy scenario, this is necessary as we would otherwise hang
# on protocols that start with a server greeting.
self.layer = layer.NextLayer(context, ask_on_start=True)
self.timeout_watchdog = TimeoutWatchdog(self.on_timeout)
async def handle_client(self) -> None:
watch = asyncio_utils.create_task(
self.timeout_watchdog.watch(),
name="timeout watchdog",
client=self.client.peername,
)
if not watch:
return # this should not be needed, see asyncio_utils.create_task
self.log("client connect")
await self.handle_hook(server_hooks.ClientConnectedHook(self.client))
if self.client.error:
self.log("client kill connection")
writer = self.transports.pop(self.client).writer
assert writer
writer.close()
else:
handler = asyncio_utils.create_task(
self.handle_connection(self.client),
name=f"client connection handler",
client=self.client.peername,
)
if not handler:
return # this should not be needed, see asyncio_utils.create_task
self.transports[self.client].handler = handler
self.server_event(events.Start())
await asyncio.wait([handler])
watch.cancel()
self.log("client disconnect")
self.client.timestamp_end = time.time()
await self.handle_hook(server_hooks.ClientClosedHook(self.client))
if self.transports:
self.log("closing transports...", "debug")
for io in self.transports.values():
if io.handler:
asyncio_utils.cancel_task(io.handler, "client disconnected")
await asyncio.wait([x.handler for x in self.transports.values() if x.handler])
self.log("transports closed!", "debug")
async def open_connection(self, command: commands.OpenConnection) -> None:
if not command.connection.address:
self.log(f"Cannot open connection, no hostname given.")
self.server_event(events.OpenConnectionReply(command, f"Cannot open connection, no hostname given."))
return
hook_data = server_hooks.ServerConnectionHookData(
client=self.client,
server=command.connection
)
await self.handle_hook(server_hooks.ServerConnectHook(hook_data))
if command.connection.error:
self.log(f"server connection to {human.format_address(command.connection.address)} killed before connect.")
self.server_event(events.OpenConnectionReply(command, "Connection killed."))
return
async with self.max_conns[command.connection.address]:
try:
command.connection.timestamp_start = time.time()
reader, writer = await asyncio.open_connection(*command.connection.address)
except (IOError, asyncio.CancelledError) as e:
err = str(e)
if not err: # str(CancelledError()) returns empty string.
err = "connection cancelled"
self.log(f"error establishing server connection: {err}")
command.connection.error = err
self.server_event(events.OpenConnectionReply(command, err))
if isinstance(e, asyncio.CancelledError):
# From https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.CancelledError:
# > In almost all situations the exception must be re-raised.
# It is not really defined what almost means here, but we play safe.
raise
else:
command.connection.timestamp_tcp_setup = time.time()
command.connection.state = ConnectionState.OPEN
command.connection.peername = writer.get_extra_info('peername')
command.connection.sockname = writer.get_extra_info('sockname')
self.transports[command.connection].reader = reader
self.transports[command.connection].writer = writer
assert command.connection.peername
if command.connection.address[0] != command.connection.peername[0]:
addr = f"{command.connection.address[0]} ({human.format_address(command.connection.peername)})"
else:
addr = human.format_address(command.connection.address)
self.log(f"server connect {addr}")
connected_hook = asyncio_utils.create_task(
self.handle_hook(server_hooks.ServerConnectedHook(hook_data)),
name=f"handle_hook(server_connected) {addr}",
client=self.client.peername,
)
if not connected_hook:
return # this should not be needed, see asyncio_utils.create_task
self.server_event(events.OpenConnectionReply(command, None))
# during connection opening, this function is the designated handler that can be cancelled.
# once we have a connection, we do want the teardown here to happen in any case, so we
# reassign the handler to .handle_connection and then clean up here once that is done.
new_handler = asyncio_utils.create_task(
self.handle_connection(command.connection),
name=f"server connection handler for {addr}",
client=self.client.peername,
)
if not new_handler:
return # this should not be needed, see asyncio_utils.create_task
self.transports[command.connection].handler = new_handler
await asyncio.wait([new_handler])
self.log(f"server disconnect {addr}")
command.connection.timestamp_end = time.time()
await connected_hook # wait here for this so that closed always comes after connected.
await self.handle_hook(server_hooks.ServerClosedHook(hook_data))
async def handle_connection(self, connection: Connection) -> None:
"""
Handle a connection for its entire lifetime.
This means we read until EOF,
but then possibly also keep on waiting for our side of the connection to be closed.
"""
cancelled = None
reader = self.transports[connection].reader
assert reader
while True:
try:
data = await reader.read(65535)
if not data:
raise OSError("Connection closed by peer.")
except OSError:
break
except asyncio.CancelledError as e:
cancelled = e
break
else:
self.server_event(events.DataReceived(connection, data))
if cancelled is None:
connection.state &= ~ConnectionState.CAN_READ
else:
connection.state = ConnectionState.CLOSED
self.server_event(events.ConnectionClosed(connection))
if cancelled is None and connection.state is ConnectionState.CAN_WRITE:
# we may still use this connection to *send* stuff,
# even though the remote has closed their side of the connection.
# to make this work we keep this task running and wait for cancellation.
await asyncio.Event().wait()
try:
writer = self.transports[connection].writer
assert writer
writer.close()
except OSError:
pass
self.transports.pop(connection)
if cancelled:
raise cancelled
async def on_timeout(self) -> None:
self.log(f"Closing connection due to inactivity: {self.client}")
handler = self.transports[self.client].handler
assert handler
asyncio_utils.cancel_task(handler, "timeout")
async def hook_task(self, hook: commands.Hook) -> None:
await self.handle_hook(hook)
if hook.blocking:
self.server_event(events.HookReply(hook))
@abc.abstractmethod
async def handle_hook(self, hook: commands.Hook) -> None:
pass
def log(self, message: str, level: str = "info") -> None:
print(message)
def server_event(self, event: events.Event) -> None:
self.timeout_watchdog.register_activity()
try:
layer_commands = self.layer.handle_event(event)
for command in layer_commands:
if isinstance(command, commands.OpenConnection):
assert command.connection not in self.transports
handler = asyncio_utils.create_task(
self.open_connection(command),
name=f"server connection manager {command.connection.address}",
client=self.client.peername,
)
self.transports[command.connection] = ConnectionIO(handler=handler)
elif isinstance(command, commands.ConnectionCommand) and command.connection not in self.transports:
return # The connection has already been closed.
elif isinstance(command, commands.SendData):
writer = self.transports[command.connection].writer
assert writer
writer.write(command.data)
elif isinstance(command, commands.CloseConnection):
self.close_connection(command.connection, command.half_close)
elif isinstance(command, commands.GetSocket):
writer = self.transports[command.connection].writer
assert writer
socket = writer.get_extra_info("socket")
self.server_event(events.GetSocketReply(command, socket))
elif isinstance(command, commands.Hook):
asyncio_utils.create_task(
self.hook_task(command),
name=f"handle_hook({command.name})",
client=self.client.peername,
)
elif isinstance(command, commands.Log):
self.log(command.message, command.level)
else:
raise RuntimeError(f"Unexpected command: {command}")
except Exception:
self.log(f"mitmproxy has crashed!\n{traceback.format_exc()}", level="error")
def close_connection(self, connection: Connection, half_close: bool = False) -> None:
if half_close:
if not connection.state & ConnectionState.CAN_WRITE:
return
self.log(f"half-closing {connection}", "debug")
try:
writer = self.transports[connection].writer
assert writer
writer.write_eof()
except OSError:
# if we can't write to the socket anymore we presume it completely dead.
connection.state = ConnectionState.CLOSED
else:
connection.state &= ~ConnectionState.CAN_WRITE
else:
connection.state = ConnectionState.CLOSED
if connection.state is ConnectionState.CLOSED:
handler = self.transports[connection].handler
assert handler
asyncio_utils.cancel_task(handler, "closed by command")
class StreamConnectionHandler(ConnectionHandler, metaclass=abc.ABCMeta):
def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, options: moptions.Options) -> None:
client = Client(
writer.get_extra_info('peername'),
writer.get_extra_info('sockname'),
time.time(),
)
context = Context(client, options)
super().__init__(context)
self.transports[client] = ConnectionIO(handler=None, reader=reader, writer=writer)
class SimpleConnectionHandler(StreamConnectionHandler): # pragma: no cover
"""Simple handler that does not really process any hooks."""
hook_handlers: typing.Dict[str, typing.Callable]
def __init__(self, reader, writer, options, hooks):
super().__init__(reader, writer, options)
self.hook_handlers = hooks
async def handle_hook(
self,
hook: commands.Hook
) -> None:
if hook.name in self.hook_handlers:
self.hook_handlers[hook.name](*hook.args())
def log(self, message: str, level: str = "info"):
if "Hook" not in message:
pass # print(message, file=sys.stderr if level in ("error", "warn") else sys.stdout)
if __name__ == "__main__": # pragma: no cover
# simple standalone implementation for testing.
loop = asyncio.get_event_loop()
opts = moptions.Options()
# options duplicated here to simplify testing setup
opts.add_option(
"connection_strategy", str, "lazy",
"Determine when server connections should be established.",
choices=("eager", "lazy")
)
opts.add_option(
"keep_host_header", bool, False,
"""
Reverse Proxy: Keep the original host header instead of rewriting it
to the reverse proxy target.
"""
)
opts.mode = "reverse:http://127.0.0.1:3000/"
async def handle(reader, writer):
layer_stack = [
# lambda ctx: layers.ServerTLSLayer(ctx),
# lambda ctx: layers.HttpLayer(ctx, HTTPMode.regular),
# lambda ctx: setattr(ctx.server, "tls", True) or layers.ServerTLSLayer(ctx),
# lambda ctx: layers.ClientTLSLayer(ctx),
lambda ctx: layers.modes.ReverseProxy(ctx),
lambda ctx: layers.HttpLayer(ctx, HTTPMode.transparent)
]
def next_layer(nl: layer.NextLayer):
l = layer_stack.pop(0)(nl.context)
l.debug = " " * len(nl.context.layers)
nl.layer = l
def request(flow: http.HTTPFlow):
if "cached" in flow.request.path:
flow.response = http.HTTPResponse.make(418, f"(cached) {flow.request.text}")
if "toggle-tls" in flow.request.path:
if flow.request.url.startswith("https://"):
flow.request.url = flow.request.url.replace("https://", "http://")
else:
flow.request.url = flow.request.url.replace("http://", "https://")
if "redirect" in flow.request.path:
flow.request.host = "httpbin.org"
def tls_start(tls_start: tls.TlsStartData):
# INSECURE
ssl_context = SSL.Context(SSL.SSLv23_METHOD)
if tls_start.conn == tls_start.context.client:
ssl_context.use_privatekey_file(
pkg_data.path("../test/mitmproxy/data/verificationcerts/trusted-leaf.key")
)
ssl_context.use_certificate_chain_file(
pkg_data.path("../test/mitmproxy/data/verificationcerts/trusted-leaf.crt")
)
tls_start.ssl_conn = SSL.Connection(ssl_context)
if tls_start.conn == tls_start.context.client:
tls_start.ssl_conn.set_accept_state()
else:
tls_start.ssl_conn.set_connect_state()
tls_start.ssl_conn.set_tlsext_host_name(tls_start.context.client.sni)
await SimpleConnectionHandler(reader, writer, opts, {
"next_layer": next_layer,
"request": request,
"tls_start": tls_start,
}).handle_client()
coro = asyncio.start_server(handle, '127.0.0.1', 8080, loop=loop)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
assert server.sockets
print(f"Serving on {human.format_address(server.sockets[0].getsockname())}")
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
| 1 | 15,350 | Do we still support handshakes without SNI present? | mitmproxy-mitmproxy | py |
@@ -131,7 +131,7 @@ module Substitutors
when :post_replacements
text = sub_post_replacements text
else
- warn %(asciidoctor: WARNING: unknown substitution type #{type})
+ logger.warn %(unknown substitution type #{type})
end
end
text = restore_passthroughs text if has_passthroughs | 1 | # encoding: UTF-8
module Asciidoctor
# Public: Methods to perform substitutions on lines of AsciiDoc text. This module
# is intented to be mixed-in to Section and Block to provide operations for performing
# the necessary substitutions.
module Substitutors
SpecialCharsRx = /[<&>]/
SpecialCharsTr = { '>' => '>', '<' => '<', '&' => '&' }
# Detects if text is a possible candidate for the quotes substitution.
QuotedTextSniffRx = { false => /[*_`#^~]/, true => /[*'_+#^~]/ }
(BASIC_SUBS = [:specialcharacters]).freeze
(HEADER_SUBS = [:specialcharacters, :attributes]).freeze
(NORMAL_SUBS = [:specialcharacters, :quotes, :attributes, :replacements, :macros, :post_replacements]).freeze
(NONE_SUBS = []).freeze
(TITLE_SUBS = [:specialcharacters, :quotes, :replacements, :macros, :attributes, :post_replacements]).freeze
(REFTEXT_SUBS = [:specialcharacters, :quotes, :replacements]).freeze
(VERBATIM_SUBS = [:specialcharacters, :callouts]).freeze
SUB_GROUPS = {
:none => NONE_SUBS,
:normal => NORMAL_SUBS,
:verbatim => VERBATIM_SUBS,
:specialchars => BASIC_SUBS
}
SUB_HINTS = {
:a => :attributes,
:m => :macros,
:n => :normal,
:p => :post_replacements,
:q => :quotes,
:r => :replacements,
:c => :specialcharacters,
:v => :verbatim
}
SUB_OPTIONS = {
:block => SUB_GROUPS.keys + NORMAL_SUBS + [:callouts],
:inline => SUB_GROUPS.keys + NORMAL_SUBS
}
SUB_HIGHLIGHT = ['coderay', 'pygments']
# Delimiters and matchers for the passthrough placeholder
# See http://www.aivosto.com/vbtips/control-characters.html#listabout for characters to use
# SPA, start of guarded protected area (\u0096)
PASS_START = %(\u0096)
# EPA, end of guarded protected area (\u0097)
PASS_END = %(\u0097)
# match passthrough slot
PassSlotRx = /#{PASS_START}(\d+)#{PASS_END}/
# fix passthrough slot after syntax highlighting
HighlightedPassSlotRx = %r(<span\b[^>]*>#{PASS_START}</span>[^\d]*(\d+)[^\d]*<span\b[^>]*>#{PASS_END}</span>)
RS = '\\'
R_SB = ']'
ESC_R_SB = '\]'
PLUS = '+'
PygmentsWrapperDivRx = %r(<div class="pyhl">(.*)</div>)m
# NOTE handles all permutations of <pre> wrapper
# NOTE trailing whitespace appears when pygments-linenums-mode=table; <pre> has style attribute when pygments-css=inline
PygmentsWrapperPreRx = %r(<pre\b[^>]*?>(.*?)</pre>\s*)m
# Internal: A String Array of passthough (unprocessed) text captured from this block
attr_reader :passthroughs
# Public: Apply the specified substitutions to the source.
#
# source - The String or String Array of text to process; must not be nil.
# subs - The substitutions to perform; can be a Symbol, Symbol Array or nil (default: NORMAL_SUBS).
# expand - A Boolean (or nil) to control whether substitution aliases are expanded (default: nil).
#
# Returns a String or String Array with substitutions applied, matching the type of source argument.
def apply_subs source, subs = NORMAL_SUBS, expand = nil
if source.empty? || !subs
return source
elsif expand
if ::Symbol === subs
subs = SUB_GROUPS[subs] || [subs]
else
effective_subs = []
subs.each do |key|
if (sub_group = SUB_GROUPS[key])
effective_subs += sub_group unless sub_group.empty?
else
effective_subs << key
end
end
if (subs = effective_subs).empty?
return source
end
end
elsif subs.empty?
return source
end
text = (multiline = ::Array === source) ? source * LF : source
if (has_passthroughs = subs.include? :macros)
text = extract_passthroughs text
has_passthroughs = false if @passthroughs.empty?
end
subs.each do |type|
case type
when :specialcharacters
text = sub_specialchars text
when :quotes
text = sub_quotes text
when :attributes
text = sub_attributes(text.split LF, -1) * LF if text.include? ATTR_REF_HEAD
when :replacements
text = sub_replacements text
when :macros
text = sub_macros text
when :highlight
text = highlight_source text, (subs.include? :callouts)
when :callouts
text = sub_callouts text unless subs.include? :highlight
when :post_replacements
text = sub_post_replacements text
else
warn %(asciidoctor: WARNING: unknown substitution type #{type})
end
end
text = restore_passthroughs text if has_passthroughs
multiline ? (text.split LF, -1) : text
end
# Public: Apply normal substitutions.
#
# An alias for apply_subs with default remaining arguments.
#
# text - The String text to which to apply normal substitutions
#
# Returns the String with normal substitutions applied.
def apply_normal_subs text
apply_subs text
end
# Public: Apply substitutions for titles.
#
# title - The String title to process
#
# returns - A String with title substitutions performed
def apply_title_subs(title)
apply_subs title, TITLE_SUBS
end
# Public: Apply substitutions for reftext.
#
# text - The String to process
#
# Returns a String with all substitutions from the reftext substitution group applied
def apply_reftext_subs text
apply_subs text, REFTEXT_SUBS
end
# Public: Apply substitutions for header metadata and attribute assignments
#
# text - String containing the text process
#
# returns - A String with header substitutions performed
def apply_header_subs(text)
apply_subs text, HEADER_SUBS
end
# Internal: Extract the passthrough text from the document for reinsertion after processing.
#
# text - The String from which to extract passthrough fragements
#
# returns - The text with the passthrough region substituted with placeholders
def extract_passthroughs(text)
compat_mode = @document.compat_mode
text = text.gsub(InlinePassMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
preceding = nil
if (boundary = m[4]) # $$, ++, or +++
# skip ++ in compat mode, handled as normal quoted text
if compat_mode && boundary == '++'
next m[2] ?
%(#{m[1]}[#{m[2]}]#{m[3]}++#{extract_passthroughs m[5]}++) :
%(#{m[1]}#{m[3]}++#{extract_passthroughs m[5]}++)
end
attributes = m[2]
escape_count = m[3].length
content = m[5]
old_behavior = false
if attributes
if escape_count > 0
# NOTE we don't look for nested unconstrained pass macros
next %(#{m[1]}[#{attributes}]#{RS * (escape_count - 1)}#{boundary}#{m[5]}#{boundary})
elsif m[1] == RS
preceding = %([#{attributes}])
attributes = nil
else
if boundary == '++' && (attributes.end_with? 'x-')
old_behavior = true
attributes = attributes[0...-2]
end
attributes = parse_attributes attributes
end
elsif escape_count > 0
# NOTE we don't look for nested unconstrained pass macros
next %(#{RS * (escape_count - 1)}#{boundary}#{m[5]}#{boundary})
end
subs = (boundary == '+++' ? [] : BASIC_SUBS)
pass_key = @passthroughs.size
if attributes
if old_behavior
@passthroughs[pass_key] = {:text => content, :subs => NORMAL_SUBS, :type => :monospaced, :attributes => attributes}
else
@passthroughs[pass_key] = {:text => content, :subs => subs, :type => :unquoted, :attributes => attributes}
end
else
@passthroughs[pass_key] = {:text => content, :subs => subs}
end
else # pass:[]
if m[6] == RS
# NOTE we don't look for nested pass:[] macros
next m[0][1..-1]
end
@passthroughs[pass_key = @passthroughs.size] = {:text => (unescape_brackets m[8]), :subs => (m[7] ? (resolve_pass_subs m[7]) : nil)}
end
%(#{preceding}#{PASS_START}#{pass_key}#{PASS_END})
} if (text.include? '++') || (text.include? '$$') || (text.include? 'ss:')
pass_inline_char1, pass_inline_char2, pass_inline_rx = InlinePassRx[compat_mode]
text = text.gsub(pass_inline_rx) {
# alias match for Ruby 1.8.7 compat
m = $~
preceding = m[1]
attributes = m[2]
escape_mark = RS if m[3].start_with? RS
format_mark = m[4]
content = m[5]
if compat_mode
old_behavior = true
else
if (old_behavior = (attributes && (attributes.end_with? 'x-')))
attributes = attributes[0...-2]
end
end
if attributes
if format_mark == '`' && !old_behavior
# extract nested single-plus passthrough; otherwise return unprocessed
next (extract_inner_passthrough content, %(#{preceding}[#{attributes}]#{escape_mark}), attributes)
end
if escape_mark
# honor the escape of the formatting mark
next %(#{preceding}[#{attributes}]#{m[3][1..-1]})
elsif preceding == RS
# honor the escape of the attributes
preceding = %([#{attributes}])
attributes = nil
else
attributes = parse_attributes attributes
end
elsif format_mark == '`' && !old_behavior
# extract nested single-plus passthrough; otherwise return unprocessed
next (extract_inner_passthrough content, %(#{preceding}#{escape_mark}))
elsif escape_mark
# honor the escape of the formatting mark
next %(#{preceding}#{m[3][1..-1]})
end
pass_key = @passthroughs.size
if compat_mode
@passthroughs[pass_key] = {:text => content, :subs => BASIC_SUBS, :attributes => attributes, :type => :monospaced}
elsif attributes
if old_behavior
subs = (format_mark == '`' ? BASIC_SUBS : NORMAL_SUBS)
@passthroughs[pass_key] = {:text => content, :subs => subs, :attributes => attributes, :type => :monospaced}
else
@passthroughs[pass_key] = {:text => content, :subs => BASIC_SUBS, :attributes => attributes, :type => :unquoted}
end
else
@passthroughs[pass_key] = {:text => content, :subs => BASIC_SUBS}
end
%(#{preceding}#{PASS_START}#{pass_key}#{PASS_END})
} if (text.include? pass_inline_char1) || (pass_inline_char2 && (text.include? pass_inline_char2))
# NOTE we need to do the stem in a subsequent step to allow it to be escaped by the former
text = text.gsub(InlineStemMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[0].start_with? RS
next m[0][1..-1]
end
if (type = m[1].to_sym) == :stem
type = ((default_stem_type = @document.attributes['stem']).nil_or_empty? ? 'asciimath' : default_stem_type).to_sym
end
content = unescape_brackets m[3]
subs = m[2] ? (resolve_pass_subs m[2]) : ((@document.basebackend? 'html') ? BASIC_SUBS : nil)
@passthroughs[pass_key = @passthroughs.size] = {:text => content, :subs => subs, :type => type}
%(#{PASS_START}#{pass_key}#{PASS_END})
} if (text.include? ':') && ((text.include? 'stem:') || (text.include? 'math:'))
text
end
def extract_inner_passthrough text, pre, attributes = nil
if (text.end_with? '+') && (text.start_with? '+', '\+') && SinglePlusInlinePassRx =~ text
if $1
%(#{pre}`+#{$2}+`)
else
@passthroughs[pass_key = @passthroughs.size] = attributes ?
{ :text => $2, :subs => BASIC_SUBS, :attributes => attributes, :type => :unquoted } :
{ :text => $2, :subs => BASIC_SUBS }
%(#{pre}`#{PASS_START}#{pass_key}#{PASS_END}`)
end
else
%(#{pre}`#{text}`)
end
end
# Internal: Restore the passthrough text by reinserting into the placeholder positions
#
# text - The String text into which to restore the passthrough text
# outer - A Boolean indicating whether we are in the outer call (default: true)
#
# returns The String text with the passthrough text restored
def restore_passthroughs text, outer = true
if outer && (@passthroughs.empty? || !text.include?(PASS_START))
return text
end
text.gsub(PassSlotRx) {
# NOTE we can't remove entry from map because placeholder may have been duplicated by other substitutions
pass = @passthroughs[$1.to_i]
subbed_text = apply_subs(pass[:text], pass[:subs])
if (type = pass[:type])
subbed_text = Inline.new(self, :quoted, subbed_text, :type => type, :attributes => pass[:attributes]).convert
end
subbed_text.include?(PASS_START) ? restore_passthroughs(subbed_text, false) : subbed_text
}
ensure
# free memory if in outer call...we don't need these anymore
@passthroughs.clear if outer
end
if RUBY_ENGINE == 'opal'
def sub_quotes text
if QuotedTextSniffRx[compat = @document.compat_mode].match? text
QUOTE_SUBS[compat].each do |type, scope, pattern|
text = text.gsub(pattern) { convert_quoted_text $~, type, scope }
end
end
text
end
def sub_replacements text
if ReplaceableTextRx.match? text
REPLACEMENTS.each do |pattern, replacement, restore|
text = text.gsub(pattern) { do_replacement $~, replacement, restore }
end
end
text
end
else
# Public: Substitute quoted text (includes emphasis, strong, monospaced, etc)
#
# text - The String text to process
#
# returns The converted String text
def sub_quotes text
if QuotedTextSniffRx[compat = @document.compat_mode].match? text
# NOTE interpolation is faster than String#dup
text = %(#{text})
QUOTE_SUBS[compat].each do |type, scope, pattern|
# NOTE using gsub! here as an MRI Ruby optimization
text.gsub!(pattern) { convert_quoted_text $~, type, scope }
end
end
text
end
# Public: Substitute replacement characters (e.g., copyright, trademark, etc)
#
# text - The String text to process
#
# returns The String text with the replacement characters substituted
def sub_replacements text
if ReplaceableTextRx.match? text
# NOTE interpolation is faster than String#dup
text = %(#{text})
REPLACEMENTS.each do |pattern, replacement, restore|
# NOTE Using gsub! as optimization
text.gsub!(pattern) { do_replacement $~, replacement, restore }
end
end
text
end
end
# Public: Substitute special characters (i.e., encode XML)
#
# The special characters <, &, and > get replaced with <,
# &, and >, respectively.
#
# text - The String text to process.
#
# returns The String text with special characters replaced.
if ::RUBY_MIN_VERSION_1_9
def sub_specialchars text
(text.include? '<') || (text.include? '&') || (text.include? '>') ? (text.gsub SpecialCharsRx, SpecialCharsTr) : text
end
else
def sub_specialchars text
(text.include? '<') || (text.include? '&') || (text.include? '>') ? (text.gsub(SpecialCharsRx) { SpecialCharsTr[$&] }) : text
end
end
alias sub_specialcharacters sub_specialchars
# Internal: Substitute replacement text for matched location
#
# returns The String text with the replacement characters substituted
def do_replacement m, replacement, restore
if (captured = m[0]).include? RS
# we have to use sub since we aren't sure it's the first char
captured.sub RS, ''
else
case restore
when :none
replacement
when :bounding
%(#{m[1]}#{replacement}#{m[2]})
else # :leading
%(#{m[1]}#{replacement})
end
end
end
# Public: Substitute attribute references
#
# Attribute references are in the format +{name}+.
#
# If an attribute referenced in the line is missing, the line is dropped.
#
# text - The String text to process
#
# returns The String text with the attribute references replaced with attribute values
#--
# NOTE it's necessary to perform this substitution line-by-line
# so that a missing key doesn't wipe out the whole block of data
# when attribute-undefined and/or attribute-missing is drop-line
def sub_attributes data, opts = {}
# normalizes data type to an array (string becomes single-element array)
data = [data] if (input_is_string = ::String === data)
doc_attrs, result = @document.attributes, []
data.each do |line|
reject = reject_if_empty = false
line = line.gsub(AttributeReferenceRx) {
# escaped attribute, return unescaped
if $1 == RS || $4 == RS
%({#{$2}})
elsif $3
case (args = $2.split ':', 3).shift
when 'set'
_, value = Parser.store_attribute args[0], args[1] || '', @document
# since this is an assignment, only drop-line applies here (skip and drop imply the same result)
if (doc_attrs.fetch 'attribute-undefined', Compliance.attribute_undefined) == 'drop-line'
reject = true
break ''
end unless value
reject_if_empty = true
''
when 'counter2'
@document.counter(*args)
reject_if_empty = true
''
else # 'counter'
@document.counter(*args)
end
elsif doc_attrs.key?(key = $2.downcase)
doc_attrs[key]
elsif INTRINSIC_ATTRIBUTES.key? key
INTRINSIC_ATTRIBUTES[key]
else
case (attribute_missing ||= opts[:attribute_missing] || (doc_attrs.fetch 'attribute-missing', Compliance.attribute_missing))
when 'drop'
# QUESTION should we warn in this case?
reject_if_empty = true
''
when 'drop-line'
warn %(asciidoctor: WARNING: dropping line containing reference to missing attribute: #{key})
reject = true
break ''
when 'warn'
warn %(asciidoctor: WARNING: skipping reference to missing attribute: #{key})
$&
else # 'skip'
$&
end
end
} if line.include? ATTR_REF_HEAD
result << line unless reject || (reject_if_empty && line.empty?)
end
input_is_string ? result * LF : result
end
# Public: Substitute inline macros (e.g., links, images, etc)
#
# Replace inline macros, which may span multiple lines, in the provided text
#
# source - The String text to process
#
# returns The converted String text
def sub_macros(source)
#return source if source.nil_or_empty?
# some look ahead assertions to cut unnecessary regex calls
found = {}
found_square_bracket = found[:square_bracket] = (source.include? '[')
found_colon = source.include? ':'
found_macroish = found[:macroish] = found_square_bracket && found_colon
found_macroish_short = found_macroish && (source.include? ':[')
result = source
if (doc_attrs = @document.attributes).key? 'experimental'
if found_macroish_short && ((result.include? 'kbd:') || (result.include? 'btn:'))
result = result.gsub(InlineKbdBtnMacroRx) {
# honor the escape
if $1
$&.slice 1, $&.length
elsif $2 == 'kbd'
if (keys = $3.strip).include? R_SB
keys = keys.gsub ESC_R_SB, R_SB
end
if keys.length > 1 && (delim_idx = (delim_idx = keys.index ',', 1) ?
[delim_idx, (keys.index '+', 1)].compact.min : (keys.index '+', 1))
delim = keys.slice delim_idx, 1
# NOTE handle special case where keys ends with delimiter (e.g., Ctrl++ or Ctrl,,)
if keys.end_with? delim
keys = (keys.chop.split delim, -1).map {|key| key.strip }
keys[-1] = %(#{keys[-1]}#{delim})
else
keys = keys.split(delim).map {|key| key.strip }
end
else
keys = [keys]
end
(Inline.new self, :kbd, nil, :attributes => { 'keys' => keys }).convert
else # $2 == 'btn'
(Inline.new self, :button, (unescape_bracketed_text $3)).convert
end
}
end
if found_macroish && (result.include? 'menu:')
result = result.gsub(InlineMenuMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if (captured = m[0]).start_with? RS
next captured[1..-1]
end
menu, items = m[1], m[2]
if items
items = items.gsub ESC_R_SB, R_SB if items.include? R_SB
if (delim = items.include?('>') ? '>' : (items.include?(',') ? ',' : nil))
submenus = items.split(delim).map {|it| it.strip }
menuitem = submenus.pop
else
submenus, menuitem = [], items.rstrip
end
else
submenus, menuitem = [], nil
end
Inline.new(self, :menu, nil, :attributes => {'menu' => menu, 'submenus' => submenus, 'menuitem' => menuitem}).convert
}
end
if (result.include? '"') && (result.include? '>')
result = result.gsub(InlineMenuRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if (captured = m[0]).start_with? RS
next captured[1..-1]
end
input = m[1]
menu, *submenus = input.split('>').map {|it| it.strip }
menuitem = submenus.pop
Inline.new(self, :menu, nil, :attributes => {'menu' => menu, 'submenus' => submenus, 'menuitem' => menuitem}).convert
}
end
end
# FIXME this location is somewhat arbitrary, probably need to be able to control ordering
# TODO this handling needs some cleanup
if (extensions = @document.extensions) && extensions.inline_macros? # && found_macroish
extensions.inline_macros.each do |extension|
result = result.gsub(extension.instance.regexp) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[0].start_with? RS
next m[0][1..-1]
end
if (m.names rescue []).empty?
target, content, extconf = m[1], m[2], extension.config
else
target, content, extconf = (m[:target] rescue nil), (m[:content] rescue nil), extension.config
end
attributes = (attributes = extconf[:default_attrs]) ? attributes.dup : {}
if content.nil_or_empty?
attributes['text'] = content if content && extconf[:content_model] != :attributes
else
content = unescape_bracketed_text content
if extconf[:content_model] == :attributes
# QUESTION should we store the text in the _text key?
# QUESTION why is the sub_result option false? why isn't the unescape_input option true?
parse_attributes content, extconf[:pos_attrs] || [], :sub_result => false, :into => attributes
else
attributes['text'] = content
end
end
# NOTE use content if target is not set (short form only); deprecated - remove in 1.6.0
replacement = extension.process_method[self, target || content, attributes]
Inline === replacement ? replacement.convert : replacement
}
end
end
if found_macroish && ((result.include? 'image:') || (result.include? 'icon:'))
# image:filename.png[Alt Text]
result = result.gsub(InlineImageMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if (captured = $&).start_with? RS
next captured[1..-1]
end
if captured.start_with? 'icon:'
type, posattrs = 'icon', ['size']
else
type, posattrs = 'image', ['alt', 'width', 'height']
end
if (target = m[1]).include? ATTR_REF_HEAD
# TODO remove this special case once titles use normal substitution order
target = sub_attributes target
end
@document.register(:images, target) unless type == 'icon'
attrs = parse_attributes(m[2], posattrs, :unescape_input => true)
attrs['alt'] ||= (attrs['default-alt'] = Helpers.basename(target, true).tr('_-', ' '))
Inline.new(self, :image, nil, :type => type, :target => target, :attributes => attrs).convert
}
end
if ((result.include? '((') && (result.include? '))')) || (found_macroish_short && (result.include? 'dexterm'))
# (((Tigers,Big cats)))
# indexterm:[Tigers,Big cats]
# ((Tigers))
# indexterm2:[Tigers]
result = result.gsub(InlineIndextermMacroRx) {
case $1
when 'indexterm'
text = $2
# honor the escape
if (m0 = $&).start_with? RS
next m0.slice 1, m0.length
end
# indexterm:[Tigers,Big cats]
terms = split_simple_csv normalize_string text, true
@document.register :indexterms, terms
(Inline.new self, :indexterm, nil, :attributes => { 'terms' => terms }).convert
when 'indexterm2'
text = $2
# honor the escape
if (m0 = $&).start_with? RS
next m0.slice 1, m0.length
end
# indexterm2:[Tigers]
term = normalize_string text, true
@document.register :indexterms, [term]
(Inline.new self, :indexterm, term, :type => :visible).convert
else
text = $3
# honor the escape
if (m0 = $&).start_with? RS
# escape concealed index term, but process nested flow index term
if (text.start_with? '(') && (text.end_with? ')')
text = text.slice 1, text.length - 2
visible, before, after = true, '(', ')'
else
next m0.slice 1, m0.length
end
else
visible = true
if text.start_with? '('
if text.end_with? ')'
text, visible = (text.slice 1, text.length - 2), false
else
text, before, after = (text.slice 1, text.length - 1), '(', ''
end
elsif text.end_with? ')'
text, before, after = (text.slice 0, text.length - 1), '', ')'
end
end
if visible
# ((Tigers))
term = normalize_string text
@document.register :indexterms, [term]
result = (Inline.new self, :indexterm, term, :type => :visible).convert
else
# (((Tigers,Big cats)))
terms = split_simple_csv(normalize_string text)
@document.register :indexterms, terms
result = (Inline.new self, :indexterm, nil, :attributes => { 'terms' => terms }).convert
end
before ? %(#{before}#{result}#{after}) : result
end
}
end
if found_colon && (result.include? '://')
# inline urls, target[text] (optionally prefixed with link: and optionally surrounded by <>)
result = result.gsub(InlineLinkRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[2].start_with? RS
next %(#{m[1]}#{m[2][1..-1]}#{m[3]})
end
# NOTE if text is non-nil, then we've matched a formal macro (i.e., trailing square brackets)
prefix, target, text, suffix = m[1], m[2], (macro = m[3]) || '', ''
if prefix == 'link:'
if macro
prefix = ''
else
# invalid macro syntax (link: prefix w/o trailing square brackets)
# we probably shouldn't even get here...our regex is doing too much
next m[0]
end
end
unless macro || UriTerminatorRx !~ target
case $&
when ')'
# strip trailing )
target = target.chop
suffix = ')'
when ';'
# strip <> around URI
if prefix.start_with?('<') && target.end_with?('>')
prefix = prefix[4..-1]
target = target[0...-4]
# strip trailing ;
# check for trailing );
elsif (target = target.chop).end_with?(')')
target = target.chop
suffix = ');'
else
suffix = ';'
end
when ':'
# strip trailing :
# check for trailing ):
if (target = target.chop).end_with?(')')
target = target.chop
suffix = '):'
else
suffix = ':'
end
end
# NOTE handle case when remaining target is a URI scheme (e.g., http://)
return m[0] if target.end_with? '://'
end
attrs, link_opts = nil, { :type => :link }
unless text.empty?
text = text.gsub ESC_R_SB, R_SB if text.include? R_SB
if (doc_attrs.key? 'linkattrs') && ((text.start_with? '"') || ((text.include? ',') && (text.include? '=')))
attrs = parse_attributes text, []
link_opts[:id] = attrs.delete 'id' if attrs.key? 'id'
text = attrs[1] || ''
end
# TODO enable in Asciidoctor 1.6.x
# support pipe-separated text and title
#unless attrs && (attrs.key? 'title')
# if text.include? '|'
# attrs ||= {}
# text, attrs['title'] = text.split '|', 2
# end
#end
if text.end_with? '^'
text = text.chop
if attrs
attrs['window'] ||= '_blank'
else
attrs = { 'window' => '_blank' }
end
end
end
if text.empty?
text = (doc_attrs.key? 'hide-uri-scheme') ? (target.sub UriSniffRx, '') : target
if attrs
attrs['role'] = (attrs.key? 'role') ? %(bare #{attrs['role']}) : 'bare'
else
attrs = { 'role' => 'bare' }
end
end
@document.register :links, (link_opts[:target] = target)
link_opts[:attributes] = attrs if attrs
%(#{prefix}#{Inline.new(self, :anchor, text, link_opts).convert}#{suffix})
}
end
if found_macroish && ((result.include? 'link:') || (result.include? 'mailto:'))
# inline link macros, link:target[text]
result = result.gsub(InlineLinkMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[0].start_with? RS
next m[0][1..-1]
end
target = (mailto = m[1]) ? %(mailto:#{m[2]}) : m[2]
attrs, link_opts = nil, { :type => :link }
unless (text = m[3]).empty?
text = text.gsub ESC_R_SB, R_SB if text.include? R_SB
if (doc_attrs.key? 'linkattrs') && ((text.start_with? '"') || ((text.include? ',') && (mailto || (text.include? '='))))
attrs = parse_attributes text, []
link_opts[:id] = attrs.delete 'id' if attrs.key? 'id'
if mailto
if attrs.key? 2
if attrs.key? 3
target = %(#{target}?subject=#{Helpers.uri_encode attrs[2]}&body=#{Helpers.uri_encode attrs[3]})
else
target = %(#{target}?subject=#{Helpers.uri_encode attrs[2]})
end
end
end
text = attrs[1] || ''
end
# TODO enable in Asciidoctor 1.6.x
# support pipe-separated text and title
#unless attrs && (attrs.key? 'title')
# if text.include? '|'
# attrs ||= {}
# text, attrs['title'] = text.split '|', 2
# end
#end
if text.end_with? '^'
text = text.chop
if attrs
attrs['window'] ||= '_blank'
else
attrs = { 'window' => '_blank' }
end
end
end
if text.empty?
# mailto is a special case, already processed
if mailto
text = m[2]
else
text = (doc_attrs.key? 'hide-uri-scheme') ? (target.sub UriSniffRx, '') : target
if attrs
attrs['role'] = (attrs.key? 'role') ? %(bare #{attrs['role']}) : 'bare'
else
attrs = { 'role' => 'bare' }
end
end
end
# QUESTION should a mailto be registered as an e-mail address?
@document.register :links, (link_opts[:target] = target)
link_opts[:attributes] = attrs if attrs
Inline.new(self, :anchor, text, link_opts).convert
}
end
if result.include? '@'
result = result.gsub(InlineEmailRx) {
address, tip = $&, $1
if tip
next (tip == RS ? address[1..-1] : address)
end
target = %(mailto:#{address})
# QUESTION should this be registered as an e-mail address?
@document.register(:links, target)
Inline.new(self, :anchor, address, :type => :link, :target => target).convert
}
end
if found_macroish && (result.include? 'tnote')
result = result.gsub(InlineFootnoteMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[0].start_with? RS
next m[0][1..-1]
end
if m[1] # footnoteref (legacy)
id, text = (m[3] || '').split(',', 2)
else
id, text = m[2], m[3]
end
if id
if text
# REVIEW it's a dirty job, but somebody's gotta do it
text = restore_passthroughs(sub_inline_xrefs(sub_inline_anchors(normalize_string text, true)), false)
index = @document.counter('footnote-number')
@document.register(:footnotes, Document::Footnote.new(index, id, text))
type, target = :ref, nil
else
if (footnote = @document.footnotes.find {|candidate| candidate.id == id })
index, text = footnote.index, footnote.text
else
index, text = nil, id
end
type, target, id = :xref, id, nil
end
elsif text
# REVIEW it's a dirty job, but somebody's gotta do it
text = restore_passthroughs(sub_inline_xrefs(sub_inline_anchors(normalize_string text, true)), false)
index = @document.counter('footnote-number')
@document.register(:footnotes, Document::Footnote.new(index, id, text))
type = target = nil
else
next m[0]
end
Inline.new(self, :footnote, text, :attributes => {'index' => index}, :id => id, :target => target, :type => type).convert
}
end
sub_inline_xrefs(sub_inline_anchors(result, found), found)
end
# Internal: Substitute normal and bibliographic anchors
def sub_inline_anchors(text, found = nil)
if @context == :list_item && @parent.style == 'bibliography'
text = text.sub(InlineBiblioAnchorRx) {
# NOTE target property on :bibref is deprecated
Inline.new(self, :anchor, %([#{$2 || $1}]), :type => :bibref, :id => $1, :target => $1).convert
}
end
if ((!found || found[:square_bracket]) && text.include?('[[')) ||
((!found || found[:macroish]) && text.include?('or:'))
text = text.gsub(InlineAnchorRx) {
# honor the escape
next $&.slice 1, $&.length if $1
# NOTE reftext is only relevant for DocBook output; used as value of xreflabel attribute
if (id = $2)
reftext = $3
else
id = $4
if (reftext = $5) && (reftext.include? R_SB)
reftext = reftext.gsub ESC_R_SB, R_SB
end
end
# NOTE target property on :ref is deprecated
Inline.new(self, :anchor, reftext, :type => :ref, :id => id, :target => id).convert
}
end
text
end
# Internal: Substitute cross reference links
def sub_inline_xrefs(text, found = nil)
if ((found ? found[:macroish] : (text.include? '[')) && (text.include? 'xref:')) ||
((text.include? '&') && (text.include? '<<'))
text = text.gsub(InlineXrefMacroRx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[0].start_with? RS
next m[0][1..-1]
end
if (id = m[1])
id, reftext = id.split ',', 2
reftext = reftext.lstrip if reftext
else
id = m[2]
if (reftext = m[3]) && (reftext.include? R_SB)
reftext = reftext.gsub ESC_R_SB, R_SB
end
end
if (hash_idx = id.index '#')
if hash_idx > 0
if (fragment_len = id.length - hash_idx - 1) > 0
path, fragment = (id.slice 0, hash_idx), (id.slice hash_idx + 1, fragment_len)
else
path = id.slice 0, hash_idx
end
if (ext_idx = path.rindex '.') && ASCIIDOC_EXTENSIONS[path.slice ext_idx, path.length]
path = path.slice 0, ext_idx
end
else
target, fragment = id, (id.slice 1, id.length)
end
elsif (ext_idx = id.rindex '.') && ASCIIDOC_EXTENSIONS[id.slice ext_idx, id.length]
path = id.slice 0, ext_idx
else
fragment = id
end
# handles: #id
if target
refid = fragment
# handles: path#, path.adoc#, path#id, path.adoc#id, or path (from path.adoc)
elsif path
# the referenced path is this document, or its contents has been included in this document
if @document.attributes['docname'] == path || @document.catalog[:includes].include?(path)
if fragment
refid, path, target = fragment, nil, %(##{fragment})
if $VERBOSE
warn %(asciidoctor: WARNING: invalid reference: #{fragment}) unless @document.catalog[:ids].key? fragment
end
else
refid, path, target = nil, nil, '#'
end
else
refid = fragment ? %(#{path}##{fragment}) : path
path = %(#{@document.attributes['relfileprefix']}#{path}#{@document.attributes.fetch 'outfilesuffix', '.html'})
target = fragment ? %(#{path}##{fragment}) : path
end
# handles: id or Section Title
else
# resolve fragment as reftext if it's not a known ID and resembles reftext (includes space or has uppercase char)
unless @document.catalog[:ids].key? fragment
if Compliance.natural_xrefs && [email protected]_mode &&
((fragment.include? ' ') || fragment.downcase != fragment) &&
(resolved_id = @document.catalog[:ids].key fragment)
fragment = resolved_id
elsif $VERBOSE
warn %(asciidoctor: WARNING: invalid reference: #{fragment})
end
end
refid, target = fragment, %(##{fragment})
end
Inline.new(self, :anchor, reftext, :type => :xref, :target => target, :attributes => {'path' => path, 'fragment' => fragment, 'refid' => refid}).convert
}
end
text
end
# Public: Substitute callout source references
#
# text - The String text to process
#
# Returns the converted String text
def sub_callouts(text)
# FIXME cache this dynamic regex
callout_rx = (attr? 'line-comment') ? /(?:#{::Regexp.escape(attr 'line-comment')} )?#{CalloutSourceRxt}/ : CalloutSourceRx
text.gsub(callout_rx) {
if $1
# we have to use sub since we aren't sure it's the first char
next $&.sub(RS, '')
end
Inline.new(self, :callout, $3, :id => @document.callouts.read_next_id).convert
}
end
# Public: Substitute post replacements
#
# text - The String text to process
#
# Returns the converted String text
def sub_post_replacements(text)
if (@document.attributes.key? 'hardbreaks') || (@attributes.key? 'hardbreaks-option')
lines = text.split LF, -1
return text if lines.size < 2
last = lines.pop
(lines.map {|line|
Inline.new(self, :break, (line.end_with? HARD_LINE_BREAK) ? (line.slice 0, line.length - 2) : line, :type => :line).convert
} << last) * LF
elsif (text.include? PLUS) && (text.include? HARD_LINE_BREAK)
text.gsub(HardLineBreakRx) { Inline.new(self, :break, $1, :type => :line).convert }
else
text
end
end
# Internal: Convert a quoted text region
#
# match - The MatchData for the quoted text region
# type - The quoting type (single, double, strong, emphasis, monospaced, etc)
# scope - The scope of the quoting (constrained or unconstrained)
#
# Returns The converted String text for the quoted text region
def convert_quoted_text(match, type, scope)
if match[0].start_with? RS
if scope == :constrained && (attrs = match[2])
unescaped_attrs = %([#{attrs}])
else
return match[0][1..-1]
end
end
if scope == :constrained
if unescaped_attrs
%(#{unescaped_attrs}#{Inline.new(self, :quoted, match[3], :type => type).convert})
else
if (attrlist = match[2])
id = (attributes = parse_quoted_text_attributes attrlist).delete 'id'
type = :unquoted if type == :mark
end
%(#{match[1]}#{Inline.new(self, :quoted, match[3], :type => type, :id => id, :attributes => attributes).convert})
end
else
if (attrlist = match[1])
id = (attributes = parse_quoted_text_attributes attrlist).delete 'id'
type = :unquoted if type == :mark
end
Inline.new(self, :quoted, match[2], :type => type, :id => id, :attributes => attributes).convert
end
end
# Internal: Parse the attributes that are defined on quoted (aka formatted) text
#
# str - A non-nil String of unprocessed attributes;
# space-separated roles (e.g., role1 role2) or the id/role shorthand syntax (e.g., #idname.role)
#
# Returns a Hash of attributes (role and id only)
def parse_quoted_text_attributes str
# NOTE attributes are typically resolved after quoted text, so substitute eagerly
str = sub_attributes str if str.include? ATTR_REF_HEAD
# for compliance, only consider first positional attribute
str = str.slice 0, (str.index ',') if str.include? ','
if (str = str.strip).empty?
{}
elsif (str.start_with? '.', '#') && Compliance.shorthand_property_syntax
segments = str.split('#', 2)
if segments.size > 1
id, *more_roles = segments[1].split('.')
else
id = nil
more_roles = []
end
roles = segments[0].empty? ? [] : segments[0].split('.')
if roles.size > 1
roles.shift
end
if more_roles.size > 0
roles.concat more_roles
end
attrs = {}
attrs['id'] = id if id
attrs['role'] = roles * ' ' unless roles.empty?
attrs
else
{'role' => str}
end
end
# Internal: Parse the attributes in the attribute line
#
# attrline - A String of unprocessed attributes (key/value pairs)
# posattrs - The keys for positional attributes
#
# returns nil if attrline is nil, an empty Hash if attrline is empty, otherwise a Hash of parsed attributes
def parse_attributes(attrline, posattrs = ['role'], opts = {})
return unless attrline
return {} if attrline.empty?
attrline = @document.sub_attributes(attrline) if opts[:sub_input] && (attrline.include? ATTR_REF_HEAD)
attrline = unescape_bracketed_text(attrline) if opts[:unescape_input]
# substitutions are only performed on attribute values if block is not nil
block = opts.fetch(:sub_result, true) ? self : nil
if (into = opts[:into])
AttributeList.new(attrline, block).parse_into(into, posattrs)
else
AttributeList.new(attrline, block).parse(posattrs)
end
end
# Internal: Strip bounding whitespace, fold endlines and unescaped closing
# square brackets from text extracted from brackets
def unescape_bracketed_text text
if (text = text.strip.tr LF, ' ').include? R_SB
text = text.gsub ESC_R_SB, R_SB
end unless text.empty?
text
end
# Internal: Strip bounding whitespace and fold endlines
def normalize_string str, unescape_brackets = false
unless str.empty?
str = str.strip.tr LF, ' '
str = str.gsub ESC_R_SB, R_SB if unescape_brackets && (str.include? R_SB)
end
str
end
# Internal: Unescape closing square brackets.
# Intended for text extracted from square brackets.
def unescape_brackets str
if str.include? RS
str = str.gsub ESC_R_SB, R_SB
end unless str.empty?
str
end
# Internal: Split text formatted as CSV with support
# for double-quoted values (in which commas are ignored)
def split_simple_csv str
if str.empty?
values = []
elsif str.include? '"'
values = []
current = []
quote_open = false
str.each_char do |c|
case c
when ','
if quote_open
current << c
else
values << current.join.strip
current = []
end
when '"'
quote_open = !quote_open
else
current << c
end
end
values << current.join.strip
else
values = str.split(',').map {|it| it.strip }
end
values
end
# Internal: Resolve the list of comma-delimited subs against the possible options.
#
# subs - A comma-delimited String of substitution aliases
#
# returns An Array of Symbols representing the substitution operation or nothing if no subs are found.
def resolve_subs subs, type = :block, defaults = nil, subject = nil
return if subs.nil_or_empty?
# QUESTION should we store candidates as a Set instead of an Array?
candidates = nil
subs = subs.delete ' ' if subs.include? ' '
modifiers_present = SubModifierSniffRx.match? subs
subs.split(',').each do |key|
modifier_operation = nil
if modifiers_present
if (first = key.chr) == '+'
modifier_operation = :append
key = key[1..-1]
elsif first == '-'
modifier_operation = :remove
key = key[1..-1]
elsif key.end_with? '+'
modifier_operation = :prepend
key = key.chop
end
end
key = key.to_sym
# special case to disable callouts for inline subs
if type == :inline && (key == :verbatim || key == :v)
resolved_keys = BASIC_SUBS
elsif SUB_GROUPS.key? key
resolved_keys = SUB_GROUPS[key]
elsif type == :inline && key.length == 1 && (SUB_HINTS.key? key)
resolved_key = SUB_HINTS[key]
if (candidate = SUB_GROUPS[resolved_key])
resolved_keys = candidate
else
resolved_keys = [resolved_key]
end
else
resolved_keys = [key]
end
if modifier_operation
candidates ||= (defaults ? defaults.dup : [])
case modifier_operation
when :append
candidates += resolved_keys
when :prepend
candidates = resolved_keys + candidates
when :remove
candidates -= resolved_keys
end
else
candidates ||= []
candidates += resolved_keys
end
end
return unless candidates
# weed out invalid options and remove duplicates (order is preserved; first occurence wins)
resolved = candidates & SUB_OPTIONS[type]
unless (candidates - resolved).empty?
invalid = candidates - resolved
warn %(asciidoctor: WARNING: invalid substitution type#{invalid.size > 1 ? 's' : ''}#{subject ? ' for ' : nil}#{subject}: #{invalid * ', '})
end
resolved
end
def resolve_block_subs subs, defaults, subject
resolve_subs subs, :block, defaults, subject
end
def resolve_pass_subs subs
resolve_subs subs, :inline, nil, 'passthrough macro'
end
# Public: Highlight the source code if a source highlighter is defined
# on the document, otherwise return the text unprocessed
#
# Callout marks are stripped from the source prior to passing it to the
# highlighter, then later restored in converted form, so they are not
# incorrectly processed by the source highlighter.
#
# source - the source code String to highlight
# process_callouts - a Boolean flag indicating whether callout marks should be substituted
#
# returns the highlighted source code, if a source highlighter is defined
# on the document, otherwise the source with verbatim substituions applied
def highlight_source source, process_callouts, highlighter = nil
case (highlighter ||= @document.attributes['source-highlighter'])
when 'coderay'
unless (highlighter_loaded = defined? ::CodeRay) ||
(defined? @@coderay_unavailable) || @document.attributes['coderay-unavailable']
if (Helpers.require_library 'coderay', true, :warn).nil?
# prevent further attempts to load CodeRay in this process
@@coderay_unavailable = true
else
highlighter_loaded = true
end
end
when 'pygments'
unless (highlighter_loaded = defined? ::Pygments) ||
(defined? @@pygments_unavailable) || @document.attributes['pygments-unavailable']
if (Helpers.require_library 'pygments', 'pygments.rb', :warn).nil?
# prevent further attempts to load Pygments in this process
@@pygments_unavailable = true
else
highlighter_loaded = true
end
end
else
# unknown highlighting library (something is misconfigured if we arrive here)
highlighter_loaded = false
end
return sub_source source, process_callouts unless highlighter_loaded
lineno = 0
callout_on_last = false
if process_callouts
callout_marks = {}
last = -1
# FIXME cache this dynamic regex
callout_rx = (attr? 'line-comment') ? /(?:#{::Regexp.escape(attr 'line-comment')} )?#{CalloutExtractRxt}/ : CalloutExtractRx
# extract callout marks, indexed by line number
source = source.split(LF, -1).map {|line|
lineno = lineno + 1
line.gsub(callout_rx) {
# alias match for Ruby 1.8.7 compat
m = $~
# honor the escape
if m[1] == RS
# we have to use sub since we aren't sure it's the first char
m[0].sub RS, ''
else
(callout_marks[lineno] ||= []) << m[3]
last = lineno
nil
end
}
} * LF
callout_on_last = (last == lineno)
callout_marks = nil if callout_marks.empty?
else
callout_marks = nil
end
linenums_mode = nil
highlight_lines = nil
case highlighter
when 'coderay'
if (linenums_mode = (attr? 'linenums', nil, false) ? (@document.attributes['coderay-linenums-mode'] || :table).to_sym : nil)
if attr? 'highlight', nil, false
highlight_lines = resolve_highlight_lines(attr 'highlight', nil, false)
end
end
result = ::CodeRay::Duo[attr('language', :text, false).to_sym, :html, {
:css => (@document.attributes['coderay-css'] || :class).to_sym,
:line_numbers => linenums_mode,
:line_number_anchors => false,
:highlight_lines => highlight_lines,
:bold_every => false}].highlight source
when 'pygments'
lexer = ::Pygments::Lexer.find_by_alias(attr 'language', 'text', false) || ::Pygments::Lexer.find_by_mimetype('text/plain')
opts = { :cssclass => 'pyhl', :classprefix => 'tok-', :nobackground => true, :stripnl => false }
opts[:startinline] = !(option? 'mixed') if lexer.name == 'PHP'
unless (@document.attributes['pygments-css'] || 'class') == 'class'
opts[:noclasses] = true
opts[:style] = (@document.attributes['pygments-style'] || Stylesheets::DEFAULT_PYGMENTS_STYLE)
end
if attr? 'highlight', nil, false
unless (highlight_lines = resolve_highlight_lines(attr 'highlight', nil, false)).empty?
opts[:hl_lines] = highlight_lines * ' '
end
end
# NOTE highlight can return nil if something goes wrong; fallback to source if this happens
# TODO we could add the line numbers in ourselves instead of having to strip out the junk
if (attr? 'linenums', nil, false) && (opts[:linenos] = @document.attributes['pygments-linenums-mode'] || 'table') == 'table'
linenums_mode = :table
if (result = lexer.highlight source, :options => opts)
result = (result.sub PygmentsWrapperDivRx, '\1').gsub PygmentsWrapperPreRx, '\1'
else
result = sub_specialchars source
end
elsif (result = lexer.highlight source, :options => opts)
if PygmentsWrapperPreRx =~ result
result = $1
end
else
result = sub_specialchars source
end
end
# fix passthrough placeholders that got caught up in syntax highlighting
result = result.gsub HighlightedPassSlotRx, %(#{PASS_START}\\1#{PASS_END}) unless @passthroughs.empty?
if process_callouts && callout_marks
lineno = 0
reached_code = linenums_mode != :table
result.split(LF, -1).map {|line|
unless reached_code
next line unless line.include?('<td class="code">')
reached_code = true
end
lineno += 1
if (conums = callout_marks.delete(lineno))
tail = nil
if callout_on_last && callout_marks.empty? && linenums_mode == :table
if highlighter == 'coderay' && (pos = line.index '</pre>')
line, tail = (line.slice 0, pos), (line.slice pos, line.length)
elsif highlighter == 'pygments' && (pos = line.start_with? '</td>')
line, tail = '', line
end
end
if conums.size == 1
%(#{line}#{Inline.new(self, :callout, conums[0], :id => @document.callouts.read_next_id).convert}#{tail})
else
conums_markup = conums.map {|conum| Inline.new(self, :callout, conum, :id => @document.callouts.read_next_id).convert } * ' '
%(#{line}#{conums_markup}#{tail})
end
else
line
end
} * LF
else
result
end
end
# e.g., highlight="1-5, !2, 10" or highlight=1-5;!2,10
def resolve_highlight_lines spec
lines = []
((spec.include? ' ') ? (spec.delete ' ') : spec).split(DataDelimiterRx).map do |entry|
negate = false
if entry.start_with? '!'
entry = entry[1..-1]
negate = true
end
if entry.include? '-'
s, e = entry.split '-', 2
line_nums = (s.to_i..e.to_i).to_a
if negate
lines -= line_nums
else
lines.concat line_nums
end
else
if negate
lines.delete entry.to_i
else
lines << entry.to_i
end
end
end
lines.sort.uniq
end
# Public: Apply verbatim substitutions on source (for use when highlighting is disabled).
#
# source - the source code String on which to apply verbatim substitutions
# process_callouts - a Boolean flag indicating whether callout marks should be substituted
#
# returns the substituted source
def sub_source source, process_callouts
process_callouts ? sub_callouts(sub_specialchars source) : (sub_specialchars source)
end
# Internal: Lock-in the substitutions for this block
#
# Looks for an attribute named "subs". If present, resolves substitutions
# from the value of that attribute and assigns them to the subs property on
# this block. Otherwise, uses the substitutions assigned to the default_subs
# property, if specified, or selects a default set of substitutions based on
# the content model of the block.
#
# Returns The Array of resolved substitutions now assigned to this block
def lock_in_subs
unless (default_subs = @default_subs)
case @content_model
when :simple
default_subs = NORMAL_SUBS
when :verbatim
if @context == :listing || (@context == :literal && !(option? 'listparagraph'))
default_subs = VERBATIM_SUBS
elsif @context == :verse
default_subs = NORMAL_SUBS
else
default_subs = BASIC_SUBS
end
when :raw
# TODO make pass subs a compliance setting; AsciiDoc Python performs :attributes and :macros on a pass block
default_subs = @context == :stem ? BASIC_SUBS : NONE_SUBS
else
return @subs
end
end
if (custom_subs = @attributes['subs'])
@subs = (resolve_block_subs custom_subs, default_subs, @context) || []
else
@subs = default_subs.dup
end
# QUESION delegate this logic to a method?
if @context == :listing && @style == 'source' && (@attributes.key? 'language') && (@document.basebackend? 'html') &&
(SUB_HIGHLIGHT.include? @document.attributes['source-highlighter']) && (idx = @subs.index :specialcharacters)
@subs[idx] = :highlight
end
@subs
end
end
end
| 1 | 5,818 | Maybe it's because I work too much on a centralized logging system but it could be great to add a "category" like "attribute", "substitution", "include directive", "macro", "extension"... | asciidoctor-asciidoctor | rb |
@@ -45,7 +45,7 @@ def normalizeName(name):
"""Normalize the class name to remove ambiguity
This function removes the white spaces in the name, and also
- remove the pointer declaration "*" (it have no sense in python) """
+ remove the pointer declaration "*" (it have no sense in python)"""
name = name.replace(" ", "")
name = name.replace("*", "") | 1 | # ==========================================================================
#
# Copyright NumFOCUS
#
# 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.txt
#
# 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 inspect
import os
import re
import sys
import types
import collections
import importlib
import warnings
import itkConfig
import itkBase
import itkLazy
from itkTypes import itkCType
import math
def registerNoTpl(name, cl):
"""Register a class without template
It can seem not useful to register classes without template (and it wasn't
useful until the SmartPointer template was generated), but those classes
can be used as template argument of classes with template.
"""
itkTemplate.__templates__[normalizeName(name)] = cl
def normalizeName(name):
"""Normalize the class name to remove ambiguity
This function removes the white spaces in the name, and also
remove the pointer declaration "*" (it have no sense in python) """
name = name.replace(" ", "")
name = name.replace("*", "")
return name
class TemplateTypeError(TypeError):
def __init__(self, template_type, input_type):
def tuple_to_string_type(t):
if type(t) == tuple:
return ", ".join(itk.python_type(x) for x in t)
else:
itk.python_type(t)
import itk
# Special case for ITK readers: Add extra information.
extra_eg = ""
if template_type in [
itk.ImageFileReader,
itk.ImageSeriesReader,
itk.MeshFileReader,
]:
extra_eg = """
or
e.g.: image = itk.imread(my_input_filename, itk.F)
"""
python_template_type = itk.python_type(template_type)
python_input_type = tuple_to_string_type(input_type)
type_list = "\n".join([itk.python_type(x[0]) for x in template_type.keys()])
eg_type = ", ".join([itk.python_type(x) for x in list(template_type.keys())[0]])
msg = """{template_type} is not wrapped for input type `{input_type}`.
To limit the size of the package, only a limited number of
types are available in ITK Python. To print the supported
types, run the following command in your python environment:
{template_type}.GetTypes()
Possible solutions:
* If you are an application user:
** Convert your input image into a supported format (see below).
** Contact developer to report the issue.
* If you are an application developer, force input images to be
loaded in a supported pixel type.
e.g.: instance = {template_type}[{eg_type}].New(my_input){extra_eg}
* (Advanced) If you are an application developer, build ITK Python yourself and
turned to `ON` the corresponding CMake option to wrap the pixel type or image
dimension you need. When configuring ITK with CMake, you can set
`ITK_WRAP_${{type}}` (replace ${{type}} with appropriate pixel type such as
`double`). If you need to support images with 4 or 5 dimensions, you can add
these dimensions to the list of dimensions in the CMake variable
`ITK_WRAP_IMAGE_DIMS`.
Supported input types:
{type_list}
""".format(
template_type=python_template_type,
input_type=python_input_type,
type_list=type_list,
eg_type=eg_type,
extra_eg=extra_eg,
)
TypeError.__init__(self, msg)
class itkTemplate(object):
"""This class manages access to available template arguments of a C++ class.
This class is generic and does not give help on the methods available in
the instantiated class. To get help on a specific ITK class, instantiate an
object of that class.
e.g.: median = itk.MedianImageFilter[ImageType, ImageType].New()
help(median)
There are two ways to access types:
1. With a dict interface. The user can manipulate template parameters
similarly to C++, with the exception that the available parameters sets are
chosen at compile time. It is also possible, with the dict interface, to
explore the available parameters sets.
2. With object attributes. The user can easily find the available parameters
sets by pressing tab in interperter like ipython
"""
__templates__ = collections.OrderedDict()
__class_to_template__ = {}
__named_templates__ = {}
__doxygen_root__ = itkConfig.doxygen_root
def __new__(cls, name):
# Singleton pattern: we only make a single instance of any Template of
# a given name. If we have already made the instance, just return it
# as-is.
if name not in cls.__named_templates__:
new_instance = object.__new__(cls)
new_instance.__name__ = name
new_instance.__template__ = collections.OrderedDict()
cls.__named_templates__[name] = new_instance
return cls.__named_templates__[name]
def __getnewargs_ex__(self):
"""Return arguments for __new__.
Required by the Pickle protocol.
"""
return (self.__name__,), {}
def __add__(self, paramSetString, cl):
"""Add a new argument set and the resulting class to the template.
paramSetString is the C++ string which defines the parameters set.
cl is the class which corresponds to the couple template-argument set.
"""
# recreate the full name and normalize it to avoid ambiguity
normFullName = normalizeName(self.__name__ + "<" + paramSetString + ">")
# the full class should not be already registered. If it is, there is a
# problem somewhere so warn the user so he can fix the problem
if normFullName in itkTemplate.__templates__:
message = (
"Template %s\n already defined as %s\n is redefined " "as %s"
) % (normFullName, self.__templates__[normFullName], cl)
warnings.warn(message)
# register the class
itkTemplate.__templates__[normFullName] = cl
# __find_param__ will parse the paramSetString and produce a list of
# the same parameters transformed in corresponding python classes.
# we transform this list in tuple to make it usable as key of the dict
param = tuple(self.__find_param__(paramSetString))
# once again, warn the user if the tuple of parameter is already
# defined so he can fix the problem
if param in self.__template__:
message = "Warning: template already defined '%s'" % normFullName
warnings.warn(message)
# and register the parameter tuple
self.__template__[param] = cl
# add in __class_to_template__ dictionary
itkTemplate.__class_to_template__[cl] = (self, param)
# now populate the template
# 2 cases:
# - the template is a SmartPointer. In that case, the attribute name
# will be the full real name of the class without the itk prefix and
# _Pointer suffix
# - the template is not a SmartPointer. In that case, we keep only the
# end of the real class name which is a short string describing the
# template arguments (for example IUC2)
if cl.__name__.startswith("itk"):
if cl.__name__.endswith("_Pointer"):
# it's a SmartPointer
attributeName = cl.__name__[len("itk") : -len("_Pointer")]
else:
# it's not a SmartPointer
# we need to now the size of the name to keep only the suffix
# short name does not contain :: and nested namespace
# itk::Numerics::Sample -> itkSample
shortNameSize = len(re.sub(r":.*:", "", self.__name__))
attributeName = cl.__name__[shortNameSize:]
else:
shortName = re.sub(r":.*:", "", self.__name__)
if not cl.__name__.startswith(shortName):
shortName = re.sub(r".*::", "", self.__name__)
attributeName = cl.__name__[len(shortName) :]
if attributeName[0].isdigit():
# the attribute name can't start with a number
# add a single x before it to build a valid name.
# Adding an underscore would hide the attributeName in IPython
attributeName = "x" + attributeName
# add the attribute to this object
self.__dict__[attributeName] = cl
def __instancecheck__(self, instance):
"""Overloads `isinstance()` when called on an `itkTemplate` object.
This function allows to compare an object to a filter without
specifying the actual template arguments of the class. It will
test all available template parameters that have been wrapped
and return `True` if one that corresponds to the object is found.
"""
for k in self.keys():
if isinstance(instance, self[k]):
return True
return False
def __find_param__(self, paramSetString):
"""Find the parameters of the template.
paramSetString is the C++ string which defines the parameters set.
__find_param__ returns a list of itk classes, itkCType, and/or numbers
which correspond to the parameters described in paramSetString.
The parameters MUST have been registered before calling this method,
or __find_param__ will return a string and not the wanted object, and
will display a warning. Registration order is important.
This method is not static only to be able to display the template name
in the warning.
"""
# split the string in a list of parameters
paramStrings = []
inner = 0
part = paramSetString.split(",")
for elt in part:
if inner == 0:
paramStrings.append(elt)
else:
paramStrings[-1] += "," + elt
inner += elt.count("<") - elt.count(">")
# convert all string parameters into classes (if possible)
parameters = []
for param in paramStrings:
# the parameter need to be normalized several time below
# do it once here
param = param.strip()
paramNorm = normalizeName(param)
if paramNorm in itkTemplate.__templates__:
# the parameter is registered.
# just get the really class form the dictionary
param = itkTemplate.__templates__[paramNorm]
elif itkCType.GetCType(param):
# the parameter is a c type
# just get the itkCtype instance
param = itkCType.GetCType(param)
elif paramNorm.isdigit():
# the parameter is a number
# convert the string to a number !
param = int(param)
elif paramNorm == "true":
param = True
elif paramNorm == "false":
param = False
else:
# unable to convert the parameter
# use it without changes, but display a warning message, to
# incite developer to fix the problem
message = "Warning: Unknown parameter '%s' in " "template '%s'" % (
param,
self.__name__,
)
warnings.warn(message)
parameters.append(param)
return parameters
def __getitem__(self, parameters):
"""Return the class which corresponds to the given template parameters.
parameters can be:
- a single parameter (Ex: itk.Index[2])
- a list of elements (Ex: itk.Image[itk.UC, 2])
"""
parameters_type = type(parameters)
if (parameters_type is not tuple) and (parameters_type is not list):
# parameters is a single element.
# include it in a list to manage the 2 cases in the same way
parameters = [parameters]
cleanParameters = []
for param in parameters:
# In the case of itk class instance, get the class
name = param.__class__.__name__
isclass = inspect.isclass(param)
if not isclass and name[:3] == "itk" and name != "itkCType":
param = param.__class__
# append the parameter to the list. If it's not a supported type,
# it is not in the dictionary and we will raise an exception below
cleanParameters.append(param)
try:
return self.__template__[tuple(cleanParameters)]
except KeyError:
self._LoadModules()
try:
return self.__template__[tuple(cleanParameters)]
except KeyError:
raise TemplateTypeError(self, tuple(cleanParameters))
def __repr__(self):
return "<itkTemplate %s>" % self.__name__
def __getattr__(self, attr):
"""Support for lazy loading."""
self._LoadModules()
return object.__getattribute__(self, attr)
def _LoadModules(self):
"""Loads all the module that may have not been loaded by the lazy loading system.
If multiple modules use the same object, the lazy loading system is only going to
load the module in which the object belongs. The other modules will be loaded only when necessary.
"""
name = self.__name__.split("::")[-1] # Remove 'itk::' or 'itk::Function::'
modules = itkBase.itk_base_global_lazy_attributes[name]
for module in modules:
# find the module's name in sys.modules, or create a new module so named
swig_module_name = "itk." + module + "Python"
this_module = sys.modules.setdefault(
swig_module_name, itkBase.create_itk_module(module)
)
namespace = {}
if not hasattr(this_module, "__templates_loaded"):
itkBase.itk_load_swig_module(module, namespace)
def __dir__(self):
"""Returns the list of the attributes available in the current template.
This loads all the modules that might be required by this template first,
and then returns the list of attributes. It is used when dir() is called
or when it tries to autocomplete attribute names.
"""
self._LoadModules()
def get_attrs(obj):
if not hasattr(obj, "__dict__"):
return [] # slots only
dict_types = (dict, types.MappingProxyType)
if not isinstance(obj.__dict__, dict_types):
raise TypeError("%s.__dict__ is not a dictionary" "" % obj.__name__)
return obj.__dict__.keys()
def dir2(obj):
attrs = set()
if not hasattr(obj, "__bases__"):
# obj is an instance
if not hasattr(obj, "__class__"):
# slots
return sorted(get_attrs(obj))
klass = obj.__class__
attrs.update(get_attrs(klass))
else:
# obj is a class
klass = obj
for cls in klass.__bases__:
attrs.update(get_attrs(cls))
attrs.update(dir2(cls))
attrs.update(get_attrs(obj))
return list(attrs)
return dir2(self)
def __call__(self, *args, **kwargs):
"""Deprecated procedural interface function.
Use snake case function instead. This function is now
merely a wrapper around the snake case function (more
specifically around `__internal_call__()` to avoid
creating a new instance twice).
Create a process object, update with the inputs and
attributes, and return the result.
The syntax is the same as the one used in New().
UpdateLargestPossibleRegion() is execute and the current output,
or tuple of outputs if there is more than one, is returned.
For example,
outputImage = itk.MedianImageFilter(inputImage, Radius=(1,2))
"""
import itkHelpers
short_name = re.sub(r".*::", "", self.__name__)
snake = itkHelpers.camel_to_snake_case(short_name)
warnings.warn(
"WrapITK warning: itk.%s() is deprecated for procedural"
" interface. Use snake case function itk.%s() instead."
% (short_name, snake),
DeprecationWarning,
)
filter = self.New(*args, **kwargs)
return filter.__internal_call__()
def New(self, *args, **kwargs):
"""Instantiate the template with a type implied from its input.
Template type specification can be avoided by assuming that the type's
first template argument should have the same type as its primary input.
This is generally true. If it is not true, then specify the types
explicitly.
For example, instead of the explicit type specification::
median = itk.MedianImageFilter[ImageType, ImageType].New()
median.SetInput(reader.GetOutput())
call::
median = itk.MedianImageFilter.New(Input=reader.GetOutput())
or, the shortened::
median = itk.MedianImageFilter.New(reader.GetOutput())
or:
median = itk.MedianImageFilter.New(reader)"""
import itk
keys = self.keys()
cur = itk.auto_pipeline.current
if self.__name__ == "itk::ImageFileReader":
return self._NewImageReader(
itk.ImageFileReader, False, "FileName", *args, **kwargs
)
elif self.__name__ == "itk::ImageSeriesReader":
# Only support `FileNames`, not `FileName`, to simplify the logic and avoid having
# to deal with checking if both keyword arguments are given.
return self._NewImageReader(
itk.ImageSeriesReader, True, "FileNames", *args, **kwargs
)
elif self.__name__ == "itk::MeshFileReader":
return self._NewMeshReader(itk.MeshFileReader, *args, **kwargs)
primary_input_methods = ("Input", "InputImage", "Input1")
def ttype_for_input_type(keys_l, input_type_l):
keys_first = list(filter(lambda k: k[0] == input_type_l, keys_l))
# If there is more than one match, prefer the filter where the
# second template argument, typically the second input or the
# output, has the same type as the input
keys_second = list(
filter(lambda k: len(k) > 1 and k[1] == input_type_l, keys_first)
)
if len(keys_second):
return keys_second
return keys_first
input_type = None
if "ttype" in kwargs and keys:
# Convert `ttype` argument to `tuple` as filter keys are tuples.
# Note that the function `itk.template()` which returns the template
# arguments of an object returns tuples and its returned value
# should be usable in this context.
# However, it is easy for a user to pass a list (e.g. [ImageType, ImageType]) and
# this needs to work too.
ttype = tuple(kwargs.pop("ttype"))
# If there is not the correct number of template parameters, throw an error.
if len(ttype) != len(list(keys)[0]):
raise RuntimeError(
"Expected %d template parameters. %d parameters given."
% (len(list(keys)[0]), len(ttype))
)
keys = [k for k in keys if k == ttype]
elif len(args) != 0:
# try to find a type suitable for the primary input provided
input_type = output(args[0]).__class__
keys = ttype_for_input_type(keys, input_type)
elif set(primary_input_methods).intersection(kwargs.keys()):
for method in primary_input_methods:
if method in kwargs:
input_type = output(kwargs[method]).__class__
keys = ttype_for_input_type(keys, input_type)
break
elif cur is not None and len(cur) != 0:
# try to find a type suitable for the input provided
input_type = output(cur).__class__
keys = ttype_for_input_type(keys, input_type)
if len(keys) == 0:
if not input_type:
raise RuntimeError(
"""No suitable template parameter can be found.
Please specify an input via the first argument, the 'ttype' keyword parameter,
or via one of the following keyword arguments: %s"""
% ", ".join(primary_input_methods)
)
else:
raise TemplateTypeError(self, input_type)
return self[list(keys)[0]].New(*args, **kwargs)
@staticmethod
def _NewImageReader(
TemplateReaderType, increase_dimension, primaryInputMethod, *args, **kwargs
):
def firstIfList(arg):
if type(arg) in [list, tuple]:
return arg[0]
else:
return arg
inputFileName = ""
if len(args) != 0:
# try to find a type suitable for the primary input provided
inputFileName = firstIfList(args[0])
elif primaryInputMethod in kwargs:
inputFileName = firstIfList(kwargs[primaryInputMethod])
if not inputFileName:
raise RuntimeError("No FileName specified.")
import itk
if "ImageIO" in kwargs:
imageIO = kwargs["ImageIO"]
else:
imageIO = itk.ImageIOFactory.CreateImageIO(
inputFileName, itk.CommonEnums.IOFileMode_ReadMode
)
if not imageIO:
msg = ""
if not os.path.isfile(inputFileName):
msg += "\nThe file doesn't exist. \n" + "Filename = %s" % inputFileName
raise RuntimeError(
"Could not create IO object for reading file %s" % inputFileName + msg
)
# Read the metadata from the image file.
imageIO.SetFileName(inputFileName)
imageIO.ReadImageInformation()
dimension = imageIO.GetNumberOfDimensions()
# For image series, increase dimension if last dimension is not of size one.
if increase_dimension and imageIO.GetDimensions(dimension - 1) != 1:
dimension += 1
componentAsString = imageIO.GetComponentTypeAsString(imageIO.GetComponentType())
_io_component_type_dict = {
"float": itk.F,
"double": itk.D,
"unsigned_char": itk.UC,
"unsigned_short": itk.US,
"unsigned_int": itk.UI,
"unsigned_long": itk.UL,
"unsigned_long_long": itk.ULL,
"char": itk.SC,
"short": itk.SS,
"int": itk.SI,
"long": itk.SL,
"long_long": itk.SLL,
}
component = _io_component_type_dict[componentAsString]
pixel = imageIO.GetPixelTypeAsString(imageIO.GetPixelType())
numberOfComponents = imageIO.GetNumberOfComponents()
PixelType = itkTemplate._pixelTypeFromIO(pixel, component, numberOfComponents)
ImageType = itk.Image[PixelType, dimension]
ReaderType = TemplateReaderType[ImageType]
return ReaderType.New(*args, **kwargs)
@staticmethod
def _NewMeshReader(TemplateReaderType, *args, **kwargs):
def firstIfList(arg):
if type(arg) in [list, tuple]:
return arg[0]
else:
return arg
inputFileName = ""
if len(args) != 0:
# try to find a type suitable for the primary input provided
inputFileName = firstIfList(args[0])
elif "FileName" in kwargs:
inputFileName = firstIfList(kwargs["FileName"])
if not inputFileName:
raise RuntimeError("No FileName specified.")
import itk
if "MeshIO" in kwargs:
meshIO = kwargs["MeshIO"]
else:
meshIO = itk.MeshIOFactory.CreateMeshIO(
inputFileName, itk.CommonEnums.IOFileMode_ReadMode
)
if not meshIO:
msg = ""
if not os.path.isfile(inputFileName):
msg += "\nThe file doesn't exist. \n" + "Filename = %s" % inputFileName
raise RuntimeError(
"Could not create IO object for reading file %s" % inputFileName + msg
)
# Read the metadata from the mesh file.
meshIO.SetFileName(inputFileName)
meshIO.ReadMeshInformation()
dimension = meshIO.GetPointDimension()
componentAsString = meshIO.GetComponentTypeAsString(
meshIO.GetPointPixelComponentType()
)
# For meshes with unknown pixel type, a common case, we assign the pixel
# type to be float, which is well supported in the wrapping and handles
# most use cases.
_io_component_type_dict = {
"unknown": itk.F,
"float": itk.F,
"double": itk.D,
"unsigned_char": itk.UC,
"unsigned_short": itk.US,
"unsigned_int": itk.UI,
"unsigned_long": itk.UL,
"unsigned_long_long": itk.ULL,
"char": itk.SC,
"short": itk.SS,
"int": itk.SI,
"long": itk.SL,
"long_long": itk.SLL,
}
component = _io_component_type_dict[componentAsString]
pixel = meshIO.GetPixelTypeAsString(meshIO.GetPointPixelType())
numberOfComponents = meshIO.GetNumberOfPointPixelComponents()
PixelType = itkTemplate._pixelTypeFromIO(pixel, component, numberOfComponents)
MeshType = itk.Mesh[PixelType, dimension]
ReaderType = TemplateReaderType[MeshType]
return ReaderType.New(*args, **kwargs)
@staticmethod
def _pixelTypeFromIO(pixel, component, numberOfComponents):
import itk
if pixel == "scalar":
PixelType = component
elif pixel == "rgb":
PixelType = itk.RGBPixel[component]
elif pixel == "rgba":
PixelType = itk.RGBAPixel[component]
elif pixel == "offset":
PixelType = itk.Offset[numberOfComponents]
elif pixel == "vector":
PixelType = itk.Vector[component, numberOfComponents]
elif pixel == "point":
PixelType = itk.Point[component, numberOfComponents]
elif pixel == "covariant_vector":
PixelType = itk.CovariantVector[component, numberOfComponents]
elif pixel == "symmetric_second_rank_tensor":
PixelType = itk.SymmetricSecondRankTensor[component, numberOfComponents]
elif pixel == "diffusion_tensor_3D":
PixelType = itk.DiffusionTensor3D[component]
elif pixel == "complex":
PixelType = itk.complex[component]
elif pixel == "fixed_array":
PixelType = itk.FixedArray[component, numberOfComponents]
elif pixel == "matrix":
PixelType = itk.Matrix[
component,
int(math.sqrt(numberOfComponents)),
int(math.sqrt(numberOfComponents)),
]
else:
raise RuntimeError("Unknown pixel type: %s." % pixel)
return PixelType
def keys(self):
return self.__template__.keys()
def values(self):
return list(self.__template__.values())
def items(self):
return list(self.__template__.items())
# everything after this comment is for dict interface
# and is a copy/paste from DictMixin
# only methods to edit dictionary are not there
def __iter__(self):
for k in self.keys():
yield k
def __contains__(self, key):
return key in self
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __len__(self):
return len(self.keys())
def GetTypes(self):
"""Helper method which prints out the available template parameters."""
print("<itkTemplate %s>" % self.__name__)
print("Options:")
for tp in self.GetTypesAsList():
print(" " + str(tp).replace("(", "[").replace(")", "]"))
def GetTypesAsList(self):
"""Helper method which returns the available template parameters."""
# Make a list of allowed types, and sort them
ctypes = []
classes = []
others = []
for key_tuple in self.__template__:
key = str(key_tuple)
if "itkCType" in key:
ctypes.append(key)
elif "class" in key:
classes.append(key)
else:
others.append(key)
# Sort the lists
ctypes = sorted(ctypes)
classes = sorted(classes)
others = sorted(others)
return ctypes + classes + others
# create a new New function which accepts parameters
def New(self, *args, **kargs):
import itk
itk.set_inputs(self, args, kargs)
# now, try to add observer to display progress
if "auto_progress" in kargs.keys():
if kargs["auto_progress"] in [True, 1]:
callback = itk.terminal_progress_callback
elif kargs["auto_progress"] == 2:
callback = itk.simple_progress_callback
else:
callback = None
elif itkConfig.ProgressCallback:
callback = itkConfig.ProgressCallback
else:
callback = None
if callback and not issubclass(self.__class__, itk.Command):
try:
name = self.__class__.__name__
def progress():
# self and callback are kept referenced with a closure
callback(name, self.GetProgress())
self.AddObserver(itk.ProgressEvent(), progress)
except AttributeError:
# as this feature is designed for prototyping, it's not really a
# problem if an object doesn't have progress reporter, so adding
# reporter can silently fail
pass
except Exception:
# it seems that something else has gone wrong...
# silently fail to maintain backward compatibility
pass
if itkConfig.NotInPlace and "SetInPlace" in dir(self):
self.SetInPlace(False)
if itk.auto_pipeline.current is not None:
itk.auto_pipeline.current.connect(self)
return self
def output(input):
try:
img = input.GetOutput()
except AttributeError:
img = input
return img
def image(input):
warnings.warn(
"WrapITK warning: itk.image() is deprecated. " "Use itk.output() instead."
)
return output(input)
| 1 | 13,962 | it have no sense in python -> it makes no sense in python | InsightSoftwareConsortium-ITK | cpp |
@@ -29,11 +29,13 @@ import (
type Pool struct {
start, capacity int
rand *rand.Rand
+ openvpnPort int
}
// ServicePortSupplier provides port needed to run a service on
type ServicePortSupplier interface {
Acquire() (Port, error)
+ OpenvpnPort() (Port, error)
}
// NewPool creates a port pool that will provide ports from range 40000-50000 | 1 | /*
* Copyright (C) 2019 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package port
import (
"math/rand"
"time"
log "github.com/cihub/seelog"
"github.com/pkg/errors"
)
// Pool hands out ports for service use
type Pool struct {
start, capacity int
rand *rand.Rand
}
// ServicePortSupplier provides port needed to run a service on
type ServicePortSupplier interface {
Acquire() (Port, error)
}
// NewPool creates a port pool that will provide ports from range 40000-50000
func NewPool() *Pool {
return &Pool{
start: 40000,
capacity: 10000,
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
// NewFixedRangePool creates a fixed size pool from port.Range
func NewFixedRangePool(r Range) *Pool {
return &Pool{
start: r.Start,
capacity: r.Capacity(),
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
// Acquire returns an unused port in pool's range
func (pool *Pool) Acquire() (port Port, err error) {
p := pool.randomPort()
available, err := available(p)
if err != nil {
return 0, errors.Wrap(err, "could not acquire port")
}
if !available {
p, err = pool.seekAvailablePort()
}
log.Debugf("%ssupplying port %v, err %v", logPrefix, p, err)
return Port(p), errors.Wrap(err, "could not acquire port")
}
func (pool *Pool) randomPort() int {
return pool.start + pool.rand.Intn(pool.capacity)
}
func (pool *Pool) seekAvailablePort() (int, error) {
for i := 0; i < pool.capacity; i++ {
p := pool.start + i
available, err := available(p)
if available || err != nil {
return p, err
}
}
return 0, errors.New("port pool is exhausted")
}
| 1 | 14,272 | maybe just do a separate implementation of the pool for openvpn case? It's a bit confusing having two methods here. | mysteriumnetwork-node | go |
@@ -413,7 +413,7 @@ function createTopology(mongoClient, topologyType, options, callback) {
// Open the connection
topology.connect(options, (err, newTopology) => {
if (err) {
- topology.close(true);
+ if (topology) topology.close();
return callback(err);
}
| 1 | 'use strict';
const authenticate = require('../authenticate');
const deprecate = require('util').deprecate;
const Logger = require('mongodb-core').Logger;
const MongoError = require('mongodb-core').MongoError;
const Mongos = require('../topologies/mongos');
const parse = require('mongodb-core').parseConnectionString;
const ReadPreference = require('mongodb-core').ReadPreference;
const ReplSet = require('../topologies/replset');
const Server = require('../topologies/server');
const ServerSessionPool = require('mongodb-core').Sessions.ServerSessionPool;
const monitoringEvents = [
'timeout',
'close',
'serverOpening',
'serverDescriptionChanged',
'serverHeartbeatStarted',
'serverHeartbeatSucceeded',
'serverHeartbeatFailed',
'serverClosed',
'topologyOpening',
'topologyClosed',
'topologyDescriptionChanged',
'commandStarted',
'commandSucceeded',
'commandFailed',
'joined',
'left',
'ping',
'ha',
'all',
'fullsetup',
'open'
];
const ignoreOptionNames = ['native_parser'];
const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db'];
const legacyParse = deprecate(
require('../url_parser'),
'current URL string parser is deprecated, and will be removed in a future version. ' +
'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.'
);
const validOptionNames = [
'poolSize',
'ssl',
'sslValidate',
'sslCA',
'sslCert',
'sslKey',
'sslPass',
'sslCRL',
'autoReconnect',
'noDelay',
'keepAlive',
'keepAliveInitialDelay',
'connectTimeoutMS',
'family',
'socketTimeoutMS',
'reconnectTries',
'reconnectInterval',
'ha',
'haInterval',
'replicaSet',
'secondaryAcceptableLatencyMS',
'acceptableLatencyMS',
'connectWithNoPrimary',
'authSource',
'w',
'wtimeout',
'j',
'forceServerObjectId',
'serializeFunctions',
'ignoreUndefined',
'raw',
'bufferMaxEntries',
'readPreference',
'pkFactory',
'promiseLibrary',
'readConcern',
'maxStalenessSeconds',
'loggerLevel',
'logger',
'promoteValues',
'promoteBuffers',
'promoteLongs',
'domainsEnabled',
'checkServerIdentity',
'validateOptions',
'appname',
'auth',
'user',
'password',
'authMechanism',
'compression',
'fsync',
'readPreferenceTags',
'numberOfRetries',
'auto_reconnect',
'minSize',
'monitorCommands',
'retryWrites',
'useNewUrlParser'
];
function addListeners(mongoClient, topology) {
topology.on('authenticated', createListener(mongoClient, 'authenticated'));
topology.on('error', createListener(mongoClient, 'error'));
topology.on('timeout', createListener(mongoClient, 'timeout'));
topology.on('close', createListener(mongoClient, 'close'));
topology.on('parseError', createListener(mongoClient, 'parseError'));
topology.once('open', createListener(mongoClient, 'open'));
topology.once('fullsetup', createListener(mongoClient, 'fullsetup'));
topology.once('all', createListener(mongoClient, 'all'));
topology.on('reconnect', createListener(mongoClient, 'reconnect'));
}
function assignTopology(client, topology) {
client.topology = topology;
topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology);
}
// Clear out all events
function clearAllEvents(topology) {
monitoringEvents.forEach(event => topology.removeAllListeners(event));
}
// Collect all events in order from SDAM
function collectEvents(mongoClient, topology) {
const MongoClient = require('../mongo_client');
const collectedEvents = [];
if (mongoClient instanceof MongoClient) {
monitoringEvents.forEach(event => {
topology.on(event, (object1, object2) => {
if (event === 'open') {
collectedEvents.push({ event: event, object1: mongoClient });
} else {
collectedEvents.push({ event: event, object1: object1, object2: object2 });
}
});
});
}
return collectedEvents;
}
/**
* Connect to MongoDB using a url as documented at
*
* docs.mongodb.org/manual/reference/connection-string/
*
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
*
* @method
* @param {MongoClient} mongoClient The MongoClient instance with which to connect.
* @param {string} url The connection URI string
* @param {object} [options] Optional settings. See MongoClient.prototype.connect for a list of options.
* @param {MongoClient~connectCallback} [callback] The command result callback
*/
function connect(mongoClient, url, options, callback) {
options = Object.assign({}, options);
// If callback is null throw an exception
if (callback == null) {
throw new Error('no callback function provided');
}
// Get a logger for MongoClient
const logger = Logger('MongoClient', options);
// Did we pass in a Server/ReplSet/Mongos
if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) {
return connectWithUrl(mongoClient, url, options, connectCallback);
}
const parseFn = options.useNewUrlParser ? parse : legacyParse;
const transform = options.useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions;
parseFn(url, options, (err, _object) => {
// Do not attempt to connect if parsing error
if (err) return callback(err);
// Flatten
const object = transform(_object);
// Parse the string
const _finalOptions = createUnifiedOptions(object, options);
// Check if we have connection and socket timeout set
if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000;
if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000;
if (_finalOptions.db_options && _finalOptions.db_options.auth) {
delete _finalOptions.db_options.auth;
}
// Store the merged options object
mongoClient.s.options = _finalOptions;
// Failure modes
if (object.servers.length === 0) {
return callback(new Error('connection string must contain at least one seed host'));
}
// Do we have a replicaset then skip discovery and go straight to connectivity
if (_finalOptions.replicaSet || _finalOptions.rs_name) {
return createTopology(
mongoClient,
'replicaset',
_finalOptions,
connectHandler(mongoClient, _finalOptions, connectCallback)
);
} else if (object.servers.length > 1) {
return createTopology(
mongoClient,
'mongos',
_finalOptions,
connectHandler(mongoClient, _finalOptions, connectCallback)
);
} else {
return createServer(
mongoClient,
_finalOptions,
connectHandler(mongoClient, _finalOptions, connectCallback)
);
}
});
function connectCallback(err, topology) {
const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`;
if (err && err.message === 'no mongos proxies found in seed list') {
if (logger.isWarn()) {
logger.warn(warningMessage);
}
// Return a more specific error message for MongoClient.connect
return callback(new MongoError(warningMessage));
}
// Return the error and db instance
callback(err, topology);
}
}
function connectHandler(client, options, callback) {
return (err, topology) => {
if (err) {
return handleConnectCallback(err, topology, callback);
}
// No authentication just reconnect
if (!options.auth) {
return handleConnectCallback(err, topology, callback);
}
// Authenticate
authenticate(client, options.user, options.password, options, (err, success) => {
if (success) {
handleConnectCallback(null, topology, callback);
} else {
if (topology) topology.close();
const authError = err ? err : new Error('Could not authenticate user ' + options.auth[0]);
handleConnectCallback(authError, topology, callback);
}
});
};
}
/**
* Connect to MongoDB using a url as documented at
*
* docs.mongodb.org/manual/reference/connection-string/
*
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
*
* @method
* @param {MongoClient} mongoClient The MongoClient instance with which to connect.
* @param {MongoClient~connectCallback} [callback] The command result callback
*/
function connectOp(mongoClient, err, callback) {
// Did we have a validation error
if (err) return callback(err);
// Fallback to callback based connect
connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => {
if (err) return callback(err);
callback(null, mongoClient);
});
}
function connectWithUrl(mongoClient, url, options, connectCallback) {
// Set the topology
assignTopology(mongoClient, url);
// Add listeners
addListeners(mongoClient, url);
// Propagate the events to the client
relayEvents(mongoClient, url);
let finalOptions = Object.assign({}, options);
// If we have a readPreference passed in by the db options, convert it from a string
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
finalOptions.readPreference = new ReadPreference(
options.readPreference || options.read_preference
);
}
// Connect
return url.connect(
finalOptions,
connectHandler(mongoClient, finalOptions, (err, topology) => {
if (err) return connectCallback(err, topology);
if (finalOptions.user || finalOptions.password || finalOptions.authMechanism) {
return authenticate(
mongoClient,
finalOptions.user,
finalOptions.password,
finalOptions,
err => {
if (err) return connectCallback(err, topology);
connectCallback(err, topology);
}
);
}
connectCallback(err, topology);
})
);
}
function createListener(mongoClient, event) {
const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']);
return (v1, v2) => {
if (eventSet.has(event)) {
return mongoClient.emit(event, mongoClient);
}
mongoClient.emit(event, v1, v2);
};
}
function createServer(mongoClient, options, callback) {
// Pass in the promise library
options.promiseLibrary = mongoClient.s.promiseLibrary;
// Set default options
const servers = translateOptions(options);
const server = servers[0];
// Propagate the events to the client
const collectedEvents = collectEvents(mongoClient, server);
// Connect to topology
server.connect(options, (err, topology) => {
if (err) {
server.close(true);
return callback(err);
}
// Clear out all the collected event listeners
clearAllEvents(server);
// Relay all the events
relayEvents(mongoClient, server);
// Add listeners
addListeners(mongoClient, server);
// Check if we are really speaking to a mongos
const ismaster = topology.lastIsMaster();
// Set the topology
assignTopology(mongoClient, topology);
// Do we actually have a mongos
if (ismaster && ismaster.msg === 'isdbgrid') {
// Destroy the current connection
topology.close();
// Create mongos connection instead
return createTopology(mongoClient, 'mongos', options, callback);
}
// Fire all the events
replayEvents(mongoClient, collectedEvents);
// Otherwise callback
callback(err, topology);
});
}
function createTopology(mongoClient, topologyType, options, callback) {
// Pass in the promise library
options.promiseLibrary = mongoClient.s.promiseLibrary;
const translationOptions = {};
if (topologyType === 'unified') translationOptions.createServers = false;
// Set default options
const servers = translateOptions(options, translationOptions);
// Create the topology
let topology;
if (topologyType === 'mongos') {
topology = new Mongos(servers, options);
} else if (topologyType === 'replicaset') {
topology = new ReplSet(servers, options);
}
// Add listeners
addListeners(mongoClient, topology);
// Propagate the events to the client
relayEvents(mongoClient, topology);
// Open the connection
topology.connect(options, (err, newTopology) => {
if (err) {
topology.close(true);
return callback(err);
}
assignTopology(mongoClient, newTopology);
callback(null, newTopology);
});
}
function createUnifiedOptions(finalOptions, options) {
const childOptions = [
'mongos',
'server',
'db',
'replset',
'db_options',
'server_options',
'rs_options',
'mongos_options'
];
const noMerge = ['readconcern', 'compression'];
for (const name in options) {
if (noMerge.indexOf(name.toLowerCase()) !== -1) {
finalOptions[name] = options[name];
} else if (childOptions.indexOf(name.toLowerCase()) !== -1) {
finalOptions = mergeOptions(finalOptions, options[name], false);
} else {
if (
options[name] &&
typeof options[name] === 'object' &&
!Buffer.isBuffer(options[name]) &&
!Array.isArray(options[name])
) {
finalOptions = mergeOptions(finalOptions, options[name], true);
} else {
finalOptions[name] = options[name];
}
}
}
return finalOptions;
}
function handleConnectCallback(err, topology, callback) {
return process.nextTick(() => {
try {
callback(err, topology);
} catch (err) {
if (topology) topology.close();
throw err;
}
});
}
function legacyTransformUrlOptions(object) {
return mergeOptions(createUnifiedOptions({}, object), object, false);
}
/**
* Logout user from server, fire off on all connections and remove all auth info.
*
* @method
* @param {MongoClient} mongoClient The MongoClient instance on which to logout.
* @param {object} [options] Optional settings. See MongoClient.prototype.logout for a list of options.
* @param {Db~resultCallback} [callback] The command result callback
*/
function logout(mongoClient, dbName, callback) {
mongoClient.topology.logout(dbName, err => {
if (err) return callback(err);
callback(null, true);
});
}
function mergeOptions(target, source, flatten) {
for (const name in source) {
if (source[name] && typeof source[name] === 'object' && flatten) {
target = mergeOptions(target, source[name], flatten);
} else {
target[name] = source[name];
}
}
return target;
}
function relayEvents(mongoClient, topology) {
const serverOrCommandEvents = [
'serverOpening',
'serverDescriptionChanged',
'serverHeartbeatStarted',
'serverHeartbeatSucceeded',
'serverHeartbeatFailed',
'serverClosed',
'topologyOpening',
'topologyClosed',
'topologyDescriptionChanged',
'commandStarted',
'commandSucceeded',
'commandFailed',
'joined',
'left',
'ping',
'ha'
];
serverOrCommandEvents.forEach(event => {
topology.on(event, (object1, object2) => {
mongoClient.emit(event, object1, object2);
});
});
}
//
// Replay any events due to single server connection switching to Mongos
//
function replayEvents(mongoClient, events) {
for (let i = 0; i < events.length; i++) {
mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
}
}
const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => {
obj[name.toLowerCase()] = name;
return obj;
}, {});
function transformUrlOptions(_object) {
let object = Object.assign({ servers: _object.hosts }, _object.options);
for (let name in object) {
const camelCaseName = LEGACY_OPTIONS_MAP[name];
if (camelCaseName) {
object[camelCaseName] = object[name];
}
}
if (_object.auth) {
const auth = _object.auth;
for (let i in auth) {
if (auth[i]) {
object[i] = auth[i];
}
}
if (auth.username) {
object.auth = auth;
object.user = auth.username;
}
if (auth.db) {
object.authSource = object.authSource || auth.db;
}
}
if (_object.defaultDatabase) {
object.dbName = _object.defaultDatabase;
}
if (object.maxpoolsize) {
object.poolSize = object.maxpoolsize;
}
if (object.readconcernlevel) {
object.readConcern = { level: object.readconcernlevel };
}
if (object.wtimeoutms) {
object.wtimeout = object.wtimeoutms;
}
return object;
}
function translateOptions(options, translationOptions) {
translationOptions = Object.assign({}, { createServers: true }, translationOptions);
// If we have a readPreference passed in by the db options
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
options.readPreference = new ReadPreference(options.readPreference || options.read_preference);
}
// Do we have readPreference tags, add them
if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) {
options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags;
}
// Do we have maxStalenessSeconds
if (options.maxStalenessSeconds) {
options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds;
}
// Set the socket and connection timeouts
if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000;
if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000;
if (!translationOptions.createServers) {
return;
}
// Create server instances
return options.servers.map(serverObj => {
return serverObj.domain_socket
? new Server(serverObj.domain_socket, 27017, options)
: new Server(serverObj.host, serverObj.port, options);
});
}
// Validate options object
function validOptions(options) {
const _validOptions = validOptionNames.concat(legacyOptionNames);
for (const name in options) {
if (ignoreOptionNames.indexOf(name) !== -1) {
continue;
}
if (_validOptions.indexOf(name) === -1 && options.validateOptions) {
return new MongoError(`option ${name} is not supported`);
} else if (_validOptions.indexOf(name) === -1) {
console.warn(`the options [${name}] is not supported`);
}
if (legacyOptionNames.indexOf(name) !== -1) {
console.warn(
`the server/replset/mongos/db options are deprecated, ` +
`all their options are supported at the top level of the options object [${validOptionNames}]`
);
}
}
}
module.exports = { connectOp, logout, validOptions };
| 1 | 15,085 | how is it possible to have a `topology` that is falsey when we had to call `topology.connect` in order to get here? | mongodb-node-mongodb-native | js |
@@ -0,0 +1,13 @@
+require 'spec_helper'
+
+describe Widgets::PlanChurnsController do
+ it 'returns the current churn for the requested plan' do
+ plan = stub(current_churn: 10)
+ PlanFinder.stubs(where: [plan])
+
+ get :show, format: :json, sku: 'sku'
+
+ expect(PlanFinder).to have_received(:where).with(sku: 'sku')
+ expect(number_widget_first_value).to eq 10
+ end
+end | 1 | 1 | 8,631 | Do we need this expectation? If we don't call this method on `PlanFinder` there's no way for the `10` to be returned. Seems somewhat redundant. What do you think? | thoughtbot-upcase | rb |
|
@@ -141,8 +141,6 @@ func NewMinEdgeSiteConfig() *EdgeSiteConfig {
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &edgecoreconfig.DataBase{
- DriverName: DataBaseDriverName,
- AliasName: DataBaseAliasName,
DataSource: DataBaseDataSource,
},
KubeAPIConfig: &cloudcoreconfig.KubeAPIConfig{ | 1 | /*
Copyright 2019 The KubeEdge 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 (
"os"
"path"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/kubeedge/kubeedge/common/constants"
cloudcoreconfig "github.com/kubeedge/kubeedge/pkg/apis/cloudcore/v1alpha1"
edgecoreconfig "github.com/kubeedge/kubeedge/pkg/apis/edgecore/v1alpha1"
metaconfig "github.com/kubeedge/kubeedge/pkg/apis/meta/v1alpha1"
"github.com/kubeedge/kubeedge/pkg/util"
)
// NewDefaultEdgeSiteConfig returns a full EdgeSiteConfig object
func NewDefaultEdgeSiteConfig() *EdgeSiteConfig {
hostnameOverride, err := os.Hostname()
if err != nil {
hostnameOverride = constants.DefaultHostnameOverride
}
localIP, _ := util.GetLocalIP(hostnameOverride)
return &EdgeSiteConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &edgecoreconfig.DataBase{
DriverName: DataBaseDriverName,
AliasName: DataBaseAliasName,
DataSource: DataBaseDataSource,
},
KubeAPIConfig: &cloudcoreconfig.KubeAPIConfig{
Master: "",
ContentType: constants.DefaultKubeContentType,
QPS: constants.DefaultKubeQPS,
Burst: constants.DefaultKubeBurst,
KubeConfig: constants.DefaultKubeConfig,
},
Modules: &Modules{
EdgeController: &cloudcoreconfig.EdgeController{
Enable: true,
NodeUpdateFrequency: 10,
Buffer: &cloudcoreconfig.EdgeControllerBuffer{
UpdatePodStatus: constants.DefaultUpdatePodStatusBuffer,
UpdateNodeStatus: constants.DefaultUpdateNodeStatusBuffer,
QueryConfigmap: constants.DefaultQueryConfigMapBuffer,
QuerySecret: constants.DefaultQuerySecretBuffer,
QueryService: constants.DefaultQueryServiceBuffer,
QueryEndpoints: constants.DefaultQueryEndpointsBuffer,
PodEvent: constants.DefaultPodEventBuffer,
ConfigmapEvent: constants.DefaultConfigMapEventBuffer,
SecretEvent: constants.DefaultSecretEventBuffer,
ServiceEvent: constants.DefaultServiceEventBuffer,
EndpointsEvent: constants.DefaultEndpointsEventBuffer,
QueryPersistentVolume: constants.DefaultQueryPersistentVolumeBuffer,
QueryPersistentVolumeClaim: constants.DefaultQueryPersistentVolumeClaimBuffer,
QueryVolumeAttachment: constants.DefaultQueryVolumeAttachmentBuffer,
QueryNode: constants.DefaultQueryNodeBuffer,
UpdateNode: constants.DefaultUpdateNodeBuffer,
},
Context: &cloudcoreconfig.EdgeControllerContext{
SendModule: metaconfig.ModuleNameMetaManager,
ReceiveModule: metaconfig.ModuleNameEdgeController,
ResponseModule: metaconfig.ModuleNameMetaManager,
},
Load: &cloudcoreconfig.EdgeControllerLoad{
UpdatePodStatusWorkers: constants.DefaultUpdatePodStatusWorkers,
UpdateNodeStatusWorkers: constants.DefaultUpdateNodeStatusWorkers,
QueryConfigmapWorkers: constants.DefaultQueryConfigMapWorkers,
QuerySecretWorkers: constants.DefaultQuerySecretWorkers,
QueryServiceWorkers: constants.DefaultQueryServiceWorkers,
QueryEndpointsWorkers: constants.DefaultQueryEndpointsWorkers,
QueryPersistentVolumeWorkers: constants.DefaultQueryPersistentVolumeWorkers,
QueryPersistentVolumeClaimWorkers: constants.DefaultQueryPersistentVolumeClaimWorkers,
QueryVolumeAttachmentWorkers: constants.DefaultQueryVolumeAttachmentWorkers,
QueryNodeWorkers: constants.DefaultQueryNodeWorkers,
UpdateNodeWorkers: constants.DefaultUpdateNodeWorkers,
},
},
Edged: &edgecoreconfig.Edged{
Enable: true,
NodeStatusUpdateFrequency: constants.DefaultNodeStatusUpdateFrequency,
DockerAddress: constants.DefaultDockerAddress,
RuntimeType: constants.DefaultRuntimeType,
NodeIP: localIP,
ClusterDNS: "",
ClusterDomain: "",
EdgedMemoryCapacity: constants.DefaultEdgedMemoryCapacity,
RemoteRuntimeEndpoint: constants.DefaultRemoteRuntimeEndpoint,
RemoteImageEndpoint: constants.DefaultRemoteImageEndpoint,
PodSandboxImage: constants.DefaultPodSandboxImage,
ImagePullProgressDeadline: constants.DefaultImagePullProgressDeadline,
RuntimeRequestTimeout: constants.DefaultRuntimeRequestTimeout,
HostnameOverride: hostnameOverride,
RegisterNodeNamespace: constants.DefaultRegisterNodeNamespace,
InterfaceName: constants.DefaultInterfaceName,
DevicePluginEnabled: false,
GPUPluginEnabled: false,
ImageGCHighThreshold: constants.DefaultImageGCHighThreshold,
ImageGCLowThreshold: constants.DefaultImageGCLowThreshold,
MaximumDeadContainersPerPod: constants.DefaultMaximumDeadContainersPerPod,
CGroupDriver: edgecoreconfig.CGroupDriverCGroupFS,
},
MetaManager: &edgecoreconfig.MetaManager{
Enable: true,
ContextSendGroup: metaconfig.GroupNameEdgeController,
ContextSendModule: metaconfig.ModuleNameEdgeController,
PodStatusSyncInterval: constants.DefaultPodStatusSyncInterval,
},
},
}
}
// NewMinEdgeSiteConfig returns a common EdgeSiteConfig object
func NewMinEdgeSiteConfig() *EdgeSiteConfig {
hostnameOverride, err := os.Hostname()
if err != nil {
hostnameOverride = constants.DefaultHostnameOverride
}
localIP, _ := util.GetLocalIP(hostnameOverride)
return &EdgeSiteConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &edgecoreconfig.DataBase{
DriverName: DataBaseDriverName,
AliasName: DataBaseAliasName,
DataSource: DataBaseDataSource,
},
KubeAPIConfig: &cloudcoreconfig.KubeAPIConfig{
Master: "",
KubeConfig: constants.DefaultKubeConfig,
},
Modules: &Modules{
Edged: &edgecoreconfig.Edged{
DockerAddress: constants.DefaultDockerAddress,
RuntimeType: constants.DefaultRuntimeType,
NodeIP: localIP,
ClusterDNS: "",
ClusterDomain: "",
RemoteRuntimeEndpoint: constants.DefaultRemoteRuntimeEndpoint,
RemoteImageEndpoint: constants.DefaultRemoteImageEndpoint,
PodSandboxImage: constants.DefaultPodSandboxImage,
HostnameOverride: hostnameOverride,
InterfaceName: constants.DefaultInterfaceName,
DevicePluginEnabled: false,
GPUPluginEnabled: false,
CGroupDriver: edgecoreconfig.CGroupDriverCGroupFS,
},
},
}
}
| 1 | 15,476 | We need to do the same for edgecore | kubeedge-kubeedge | go |
@@ -378,8 +378,15 @@ namespace TestPlatform.CommunicationUtilities.UnitTests
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunCompletePayload>(message)).Returns(payload);
+ var waitHandle = new AutoResetEvent(false);
+ mockHandler.Setup(mh => mh.HandleTestRunComplete(It.IsAny<TestRunCompleteEventArgs>(),
+ It.IsAny<TestRunChangedEventArgs>(), It.IsAny<ICollection<AttachmentSet>>(), It.IsAny<ICollection<string>>())).Callback
+ (() => waitHandle.Set());
+
this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object);
+ waitHandle.WaitOne();
+
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithTests, runCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(rawMessage), Times.Once);
mockHandler.Verify(mh => mh.HandleTestRunComplete(null, null, null, null), Times.Once); | 1 |
// Copyright (c) Microsoft. All rights reserved.
namespace TestPlatform.CommunicationUtilities.UnitTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class TestRequestSenderTests
{
private ITestRequestSender testRequestSender;
private Mock<ICommunicationManager> mockCommunicationManager;
private Mock<IDataSerializer> mockDataSerializer;
[TestInitialize]
public void TestInit()
{
this.mockCommunicationManager = new Mock<ICommunicationManager>();
this.mockDataSerializer = new Mock<IDataSerializer>();
this.testRequestSender = new TestRequestSender(this.mockCommunicationManager.Object, this.mockDataSerializer.Object);
}
[TestMethod]
public void InitializeCommunicationShouldHostServerAndAcceptClient()
{
this.mockCommunicationManager.Setup(mc => mc.HostServer()).Returns(123);
var port = this.testRequestSender.InitializeCommunication();
this.mockCommunicationManager.Verify(mc => mc.HostServer(), Times.Once);
this.mockCommunicationManager.Verify(mc => mc.AcceptClientAsync(), Times.Once);
Assert.AreEqual(port, 123, "Correct port must be returned.");
}
[TestMethod]
public void WaitForRequestHandlerConnectionShouldCallWaitForClientConnection()
{
this.testRequestSender.WaitForRequestHandlerConnection(123);
this.mockCommunicationManager.Verify(mc => mc.WaitForClientConnection(123), Times.Once);
}
[TestMethod]
public void CloseShouldCallStopServerOnCommunicationManager()
{
this.testRequestSender.Close();
this.mockCommunicationManager.Verify(mc => mc.StopServer(), Times.Once);
}
[TestMethod]
public void DisposeShouldCallStopServerOnCommunicationManager()
{
this.testRequestSender.Dispose();
this.mockCommunicationManager.Verify(mc => mc.StopServer(), Times.Once);
}
[TestMethod]
public void InitializeDiscoveryShouldSendCommunicationMessageWithCorrectParameters()
{
var paths = new List<string>() { "Hello", "World" };
this.testRequestSender.InitializeDiscovery(paths, false);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.DiscoveryInitialize, paths), Times.Once);
}
[TestMethod]
public void InitializeExecutionShouldSendCommunicationMessageWithCorrectParameters()
{
var paths = new List<string>() { "Hello", "World" };
this.testRequestSender.InitializeExecution(paths, true);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.ExecutionInitialize, paths), Times.Once);
}
[TestMethod]
public void DiscoverTestsShouldCallHandleDiscoveredTestsOnTestCaseEvent()
{
var sources = new List<string>() { "Hello", "World" };
string settingsXml = "SettingsXml";
var mockHandler = new Mock<ITestDiscoveryEventsHandler>();
var discoveryCriteria = new DiscoveryCriteria(sources, 100, settingsXml);
var testCases = new List<TestCase>() { new TestCase("x.y.z", new Uri("x://y"), "x.dll") };
var rawMessage = "OnDiscoveredTests";
var message = new Message() { MessageType = MessageType.TestCasesFound, Payload = null };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<IEnumerable<TestCase>>(message)).Returns(testCases);
var completePayload = new DiscoveryCompletePayload()
{
IsAborted = false,
LastDiscoveredTests = null,
TotalTests = 1
};
var completeMessage = new Message() { MessageType = MessageType.DiscoveryComplete, Payload = null };
mockHandler.Setup(mh => mh.HandleDiscoveredTests(testCases)).Callback(
() =>
{
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny<string>())).Returns(completeMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<DiscoveryCompletePayload>(completeMessage)).Returns(completePayload);
});
this.testRequestSender.DiscoverTests(discoveryCriteria, mockHandler.Object);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartDiscovery, discoveryCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(rawMessage), Times.Exactly(2));
mockHandler.Verify(mh => mh.HandleDiscoveredTests(testCases), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Exactly(2));
}
[TestMethod]
public void DiscoverTestsShouldCallHandleLogMessageOnTestMessage()
{
var sources = new List<string>() { "Hello", "World" };
string settingsXml = "SettingsXml";
var mockHandler = new Mock<ITestDiscoveryEventsHandler>();
var discoveryCriteria = new DiscoveryCriteria(sources, 100, settingsXml);
var rawMessage = "TestMessage";
var messagePayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Error, Message = rawMessage };
var message = new Message() { MessageType = MessageType.TestMessage, Payload = null };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestMessagePayload>(message)).Returns(messagePayload);
var completePayload = new DiscoveryCompletePayload()
{
IsAborted = false,
LastDiscoveredTests = null,
TotalTests = 1
};
var completeMessage = new Message() { MessageType = MessageType.DiscoveryComplete, Payload = null };
mockHandler.Setup(mh => mh.HandleLogMessage(TestMessageLevel.Error, rawMessage)).Callback(
() =>
{
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny<string>())).Returns(completeMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<DiscoveryCompletePayload>(completeMessage)).Returns(completePayload);
});
this.testRequestSender.DiscoverTests(discoveryCriteria, mockHandler.Object);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartDiscovery, discoveryCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(rawMessage), Times.Exactly(2));
mockHandler.Verify(mh => mh.HandleLogMessage(TestMessageLevel.Error, rawMessage), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Exactly(2));
}
[TestMethod]
public void DiscoverTestsShouldCallHandleDiscoveryCompleteOnDiscoveryCompletion()
{
var sources = new List<string>() { "Hello", "World" };
string settingsXml = "SettingsXml";
var mockHandler = new Mock<ITestDiscoveryEventsHandler>();
var discoveryCriteria = new DiscoveryCriteria(sources, 100, settingsXml);
var rawMessage = "RunComplete";
var completePayload = new DiscoveryCompletePayload()
{
IsAborted = false,
LastDiscoveredTests = null,
TotalTests = 1
};
var message = new Message() { MessageType = MessageType.DiscoveryComplete, Payload = null };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<DiscoveryCompletePayload>(message)).Returns(completePayload);
this.testRequestSender.DiscoverTests(discoveryCriteria, mockHandler.Object);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartDiscovery, discoveryCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(rawMessage), Times.Once);
mockHandler.Verify(mh => mh.HandleDiscoveryComplete(1, null, false), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Once);
}
[TestMethod]
public void StartTestRunWithSourcesShouldCallHandleTestRunStatsChange()
{
var mockHandler = new Mock<ITestRunEventsHandler>();
var runCriteria = new TestRunCriteriaWithSources(null, null, null);
var testRunChangedArgs = new TestRunChangedEventArgs(null, null, null);
var rawMessage = "OnTestRunStatsChange";
var message = new Message() { MessageType = MessageType.TestRunStatsChange, Payload = null };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunChangedEventArgs>(message)).Returns(testRunChangedArgs);
var completePayload = new TestRunCompletePayload()
{
ExecutorUris = null,
LastRunTests = null,
RunAttachments = null,
TestRunCompleteArgs = null
};
var completeMessage = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null };
mockHandler.Setup(mh => mh.HandleTestRunStatsChange(testRunChangedArgs)).Callback(
() =>
{
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny<string>())).Returns(completeMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunCompletePayload>(completeMessage)).Returns(completePayload);
});
var waitHandle = new AutoResetEvent(false);
mockHandler.Setup(mh => mh.HandleTestRunComplete(It.IsAny<TestRunCompleteEventArgs>(),
It.IsAny<TestRunChangedEventArgs>(), It.IsAny<ICollection<AttachmentSet>>(), It.IsAny<ICollection<string>>())).Callback
(() => waitHandle.Set());
this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object);
waitHandle.WaitOne();
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithSources, runCriteria), Times.Once);
// One for run stats and another for runcomplete
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(rawMessage), Times.Exactly(2));
mockHandler.Verify(mh => mh.HandleTestRunStatsChange(testRunChangedArgs), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Exactly(2));
}
[TestMethod]
public void StartTestRunWithTestsShouldCallHandleTestRunStatsChange()
{
var mockHandler = new Mock<ITestRunEventsHandler>();
var runCriteria = new TestRunCriteriaWithTests(null, null, null);
var testRunChangedArgs = new TestRunChangedEventArgs(null, null, null);
var rawMessage = "OnTestRunStatsChange";
var message = new Message() { MessageType = MessageType.TestRunStatsChange, Payload = null };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunChangedEventArgs>(message)).Returns(testRunChangedArgs);
var completePayload = new TestRunCompletePayload()
{
ExecutorUris = null,
LastRunTests = null,
RunAttachments = null,
TestRunCompleteArgs = null
};
var completeMessage = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null };
mockHandler.Setup(mh => mh.HandleTestRunStatsChange(testRunChangedArgs)).Callback(
() =>
{
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny<string>())).Returns(completeMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunCompletePayload>(completeMessage)).Returns(completePayload);
});
this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithTests, runCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(It.IsAny<string>()), Times.Once);
mockHandler.Verify(mh => mh.HandleTestRunStatsChange(testRunChangedArgs), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.AtLeastOnce);
}
[TestMethod]
public void StartTestRunShouldCallHandleLogMessageOnTestMessage()
{
var mockHandler = new Mock<ITestRunEventsHandler>();
var runCriteria = new TestRunCriteriaWithSources(null, null, null);
var rawMessage = "OnLogMessage";
var message = new Message() { MessageType = MessageType.TestMessage, Payload = null };
var payload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Error, Message = rawMessage };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestMessagePayload>(message)).Returns(payload);
var completePayload = new TestRunCompletePayload()
{
ExecutorUris = null, LastRunTests = null, RunAttachments = null, TestRunCompleteArgs = null
};
var completeMessage = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null };
mockHandler.Setup(mh => mh.HandleLogMessage(TestMessageLevel.Error, rawMessage)).Callback(
() =>
{
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny<string>())).Returns(completeMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunCompletePayload>(completeMessage)).Returns(completePayload);
});
this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithSources, runCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(It.IsAny<string>()), Times.Once);
mockHandler.Verify(mh => mh.HandleLogMessage(payload.MessageLevel, payload.Message), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.AtLeastOnce);
}
[TestMethod]
public void StartTestRunShouldCallLaunchProcessWithDebuggerAndWaitForCallback()
{
var mockHandler = new Mock<ITestRunEventsHandler>();
var runCriteria = new TestRunCriteriaWithSources(null, null, null);
var rawMessage = "LaunchProcessWithDebugger";
var message = new Message() { MessageType = MessageType.LaunchAdapterProcessWithDebuggerAttached, Payload = null };
var payload = new TestProcessStartInfo();
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestProcessStartInfo>(message)).Returns(payload);
var completePayload = new TestRunCompletePayload()
{
ExecutorUris = null,
LastRunTests = null,
RunAttachments = null,
TestRunCompleteArgs = null
};
var completeMessage = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null };
mockHandler.Setup(mh => mh.LaunchProcessWithDebuggerAttached(payload)).Callback(
() =>
{
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny<string>())).Returns(completeMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunCompletePayload>(completeMessage)).Returns(completePayload);
});
var waitHandle = new AutoResetEvent(false);
mockHandler.Setup(mh => mh.HandleTestRunComplete(It.IsAny<TestRunCompleteEventArgs>(),
It.IsAny<TestRunChangedEventArgs>(), It.IsAny<ICollection<AttachmentSet>>(), It.IsAny<ICollection<string>>())).Callback
(() => waitHandle.Set());
this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object);
waitHandle.WaitOne();
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithSources, runCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(It.IsAny<string>()), Times.Exactly(2));
mockHandler.Verify(mh => mh.LaunchProcessWithDebuggerAttached(payload), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Exactly(2));
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.LaunchAdapterProcessWithDebuggerAttachedCallback, It.IsAny<object>()), Times.Once);
}
[TestMethod]
public void StartTestRunShouldCallHandleTestRunCompleteOnRunCompletion()
{
var mockHandler = new Mock<ITestRunEventsHandler>();
var runCriteria = new TestRunCriteriaWithTests(null, null, null);
var rawMessage = "ExecComplete";
var message = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null };
var payload = new TestRunCompletePayload() { ExecutorUris = null, LastRunTests = null, RunAttachments = null, TestRunCompleteArgs = null };
this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessage()).Returns(rawMessage);
this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);
this.mockDataSerializer.Setup(ds => ds.DeserializePayload<TestRunCompletePayload>(message)).Returns(payload);
this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object);
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithTests, runCriteria), Times.Once);
this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(rawMessage), Times.Once);
mockHandler.Verify(mh => mh.HandleTestRunComplete(null, null, null, null), Times.Once);
mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Once);
}
[TestMethod]
public void EndSessionShouldSendCorrectEventMessage()
{
this.testRequestSender.EndSession();
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.SessionEnd), Times.Once);
}
[TestMethod]
public void CancelTestRunSessionShouldSendCorrectEventMessage()
{
this.testRequestSender.SendTestRunCancel();
this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.CancelTestRun), Times.Once);
}
}
}
| 1 | 11,081 | This fix has nothing to do with the product change. Just a fix I am making for the test issue. | microsoft-vstest | .cs |
@@ -94,8 +94,7 @@ namespace OpenTelemetry.Trace
}
else if (this.Exporter != null)
{
- // TODO: Make this BatchingActivityProcessor once its available.
- exportingProcessor = new SimpleActivityProcessor(this.Exporter);
+ exportingProcessor = new BatchingActivityProcessor(this.Exporter);
this.Processors.Add(exportingProcessor);
}
| 1 | // <copyright file="ActivityProcessorPipelineBuilder.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 OpenTelemetry.Trace.Internal;
namespace OpenTelemetry.Trace
{
/// <summary>
/// Configures exporting pipeline with chains of processors and exporter.
/// </summary>
public class ActivityProcessorPipelineBuilder
{
private Func<ActivityExporter, ActivityProcessor> lastProcessorFactory;
private List<Func<ActivityProcessor, ActivityProcessor>> processorChain;
internal ActivityProcessorPipelineBuilder()
{
}
internal ActivityExporter Exporter { get; private set; }
internal List<ActivityProcessor> Processors { get; private set; }
/// <summary>
/// Adds chained processor to the pipeline. Processors are executed in the order they were added.
/// </summary>
/// <param name="processorFactory">Function that creates processor from the next one.</param>
/// <returns>Returns <see cref="ActivityProcessorPipelineBuilder"/>.</returns>
public ActivityProcessorPipelineBuilder AddProcessor(Func<ActivityProcessor, ActivityProcessor> processorFactory)
{
if (processorFactory == null)
{
throw new ArgumentNullException(nameof(processorFactory));
}
if (this.processorChain == null)
{
this.processorChain = new List<Func<ActivityProcessor, ActivityProcessor>>();
}
this.processorChain.Add(processorFactory);
return this;
}
/// <summary>
/// Configures last processor that invokes exporter. When not set, <see cref="SimpleActivityProcessor"/> is used.
/// </summary>
/// <param name="processorFactory">Factory that creates exporting processor from the exporter.</param>
/// <returns>Returns <see cref="ActivityProcessorPipelineBuilder"/>.</returns>
public ActivityProcessorPipelineBuilder SetExportingProcessor(Func<ActivityExporter, ActivityProcessor> processorFactory)
{
this.lastProcessorFactory = processorFactory ?? throw new ArgumentNullException(nameof(processorFactory));
return this;
}
/// <summary>
/// Configures exporter.
/// </summary>
/// <param name="exporter">Exporter instance.</param>
/// <returns>Returns <see cref="ActivityProcessorPipelineBuilder"/>.</returns>
public ActivityProcessorPipelineBuilder SetExporter(ActivityExporter exporter)
{
this.Exporter = exporter ?? throw new ArgumentNullException(nameof(exporter));
return this;
}
internal ActivityProcessor Build()
{
this.Processors = new List<ActivityProcessor>();
ActivityProcessor exportingProcessor = null;
// build or create default exporting processor
if (this.lastProcessorFactory != null)
{
exportingProcessor = this.lastProcessorFactory.Invoke(this.Exporter);
this.Processors.Add(exportingProcessor);
}
else if (this.Exporter != null)
{
// TODO: Make this BatchingActivityProcessor once its available.
exportingProcessor = new SimpleActivityProcessor(this.Exporter);
this.Processors.Add(exportingProcessor);
}
if (this.processorChain == null)
{
// if there is no chain, return exporting processor.
if (exportingProcessor == null)
{
exportingProcessor = new NoopActivityProcessor();
this.Processors.Add(exportingProcessor);
}
return exportingProcessor;
}
var next = exportingProcessor;
// build chain from the end to the beginning
for (int i = this.processorChain.Count - 1; i >= 0; i--)
{
next = this.processorChain[i].Invoke(next);
this.Processors.Add(next);
}
// return the last processor in the chain - it will be called first
return this.Processors[this.Processors.Count - 1];
}
}
}
| 1 | 15,236 | Don't know what should be the default. Lets keep BatchingProcessor for now. And revisit the area after beta. | open-telemetry-opentelemetry-dotnet | .cs |
@@ -1,4 +1,4 @@
-require 'rspec/support/reentrant_mutex'
+RSpec::Support.require_rspec_support 'reentrant_mutex'
module RSpec
module Core | 1 | require 'rspec/support/reentrant_mutex'
module RSpec
module Core
# This module is included in {ExampleGroup}, making the methods
# available to be called from within example blocks.
#
# @see ClassMethods
module MemoizedHelpers
# @note `subject` was contributed by Joe Ferris to support the one-liner
# syntax embraced by shoulda matchers:
#
# describe Widget do
# it { is_expected.to validate_presence_of(:name) }
# # or
# it { should validate_presence_of(:name) }
# end
#
# While the examples below demonstrate how to use `subject`
# explicitly in examples, we recommend that you define a method with
# an intention revealing name instead.
#
# @example
#
# # Explicit declaration of subject.
# describe Person do
# subject { Person.new(:birthdate => 19.years.ago) }
# it "should be eligible to vote" do
# subject.should be_eligible_to_vote
# # ^ ^ explicit reference to subject not recommended
# end
# end
#
# # Implicit subject => { Person.new }.
# describe Person do
# it "should be eligible to vote" do
# subject.should be_eligible_to_vote
# # ^ ^ explicit reference to subject not recommended
# end
# end
#
# # One-liner syntax - expectation is set on the subject.
# describe Person do
# it { is_expected.to be_eligible_to_vote }
# # or
# it { should be_eligible_to_vote }
# end
#
# @note Because `subject` is designed to create state that is reset
# between each example, and `before(:context)` is designed to setup
# state that is shared across _all_ examples in an example group,
# `subject` is _not_ intended to be used in a `before(:context)` hook.
#
# @see #should
# @see #should_not
# @see #is_expected
def subject
__memoized.fetch_or_store(:subject) do
described = described_class || self.class.metadata.fetch(:description_args).first
Class === described ? described.new : described
end
end
# When `should` is called with no explicit receiver, the call is
# delegated to the object returned by `subject`. Combined with an
# implicit subject this supports very concise expressions.
#
# @example
#
# describe Person do
# it { should be_eligible_to_vote }
# end
#
# @see #subject
# @see #is_expected
#
# @note This only works if you are using rspec-expectations.
# @note If you are using RSpec's newer expect-based syntax you may
# want to use `is_expected.to` instead of `should`.
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message)
end
# Just like `should`, `should_not` delegates to the subject (implicit or
# explicit) of the example group.
#
# @example
#
# describe Person do
# it { should_not be_eligible_to_vote }
# end
#
# @see #subject
# @see #is_expected
#
# @note This only works if you are using rspec-expectations.
# @note If you are using RSpec's newer expect-based syntax you may
# want to use `is_expected.to_not` instead of `should_not`.
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message)
end
# Wraps the `subject` in `expect` to make it the target of an expectation.
# Designed to read nicely for one-liners.
#
# @example
#
# describe [1, 2, 3] do
# it { is_expected.to be_an Array }
# it { is_expected.not_to include 4 }
# end
#
# @see #subject
# @see #should
# @see #should_not
#
# @note This only works if you are using rspec-expectations.
def is_expected
expect(subject)
end
# @private
# should just be placed in private section,
# but Ruby issues warnings on private attributes.
# and expanding it to the equivalent method upsets Rubocop,
# b/c it should obviously be a reader
attr_reader :__memoized
private :__memoized
private
# @private
def initialize(*)
__init_memoized
super
end
# @private
def __init_memoized
@__memoized = if RSpec.configuration.threadsafe?
ThreadsafeMemoized.new
else
NonThreadSafeMemoized.new
end
end
# @private
class ThreadsafeMemoized
def initialize
@memoized = {}
@mutex = Support::ReentrantMutex.new
end
def fetch_or_store(key)
@memoized.fetch(key) do # only first access pays for synchronization
@mutex.synchronize do
@memoized.fetch(key) { @memoized[key] = yield }
end
end
end
end
# @private
class NonThreadSafeMemoized
def initialize
@memoized = {}
end
def fetch_or_store(key)
@memoized.fetch(key) { @memoized[key] = yield }
end
end
# Used internally to customize the behavior of the
# memoized hash when used in a `before(:context)` hook.
#
# @private
class ContextHookMemoized
def self.isolate_for_context_hook(example_group_instance)
exploding_memoized = self
example_group_instance.instance_exec do
@__memoized = exploding_memoized
begin
yield
ensure
# This is doing a reset instead of just isolating for context hook.
# Really, this should set the old @__memoized back into place.
#
# Caller is the before and after context hooks
# which are both called from self.run
# I didn't look at why it made tests fail, maybe an object was getting reused in RSpec tests,
# if so, then that probably already works, and its the tests that are wrong.
__init_memoized
end
end
end
def self.fetch_or_store(key, &_block)
description = if key == :subject
"subject"
else
"let declaration `#{key}`"
end
raise <<-EOS
#{description} accessed in #{article} #{hook_expression} hook at:
#{CallerFilter.first_non_rspec_line}
`let` and `subject` declarations are not intended to be called
in #{article} #{hook_expression} hook, as they exist to define state that
is reset between each example, while #{hook_expression} exists to
#{hook_intention}.
EOS
end
# @private
class Before < self
def self.hook_expression
"`before(:context)`"
end
def self.article
"a"
end
def self.hook_intention
"define state that is shared across examples in an example group"
end
end
# @private
class After < self
def self.hook_expression
"`after(:context)`"
end
def self.article
"an"
end
def self.hook_intention
"cleanup state that is shared across examples in an example group"
end
end
end
# This module is extended onto {ExampleGroup}, making the methods
# available to be called from within example group blocks.
# You can think of them as being analagous to class macros.
module ClassMethods
# Generates a method whose return value is memoized after the first
# call. Useful for reducing duplication between examples that assign
# values to the same local variable.
#
# @note `let` _can_ enhance readability when used sparingly (1,2, or
# maybe 3 declarations) in any given example group, but that can
# quickly degrade with overuse. YMMV.
#
# @note `let` can be configured to be threadsafe or not.
# If it is threadsafe, it will take longer to access the value.
# If it is not threadsafe, it may behave in surprising ways in examples
# that spawn separate threads. Specify this on `RSpec.configure`
#
# @note Because `let` is designed to create state that is reset between
# each example, and `before(:context)` is designed to setup state that
# is shared across _all_ examples in an example group, `let` is _not_
# intended to be used in a `before(:context)` hook.
#
# @example
#
# describe Thing do
# let(:thing) { Thing.new }
#
# it "does something" do
# # First invocation, executes block, memoizes and returns result.
# thing.do_something
#
# # Second invocation, returns the memoized value.
# thing.should be_something
# end
# end
def let(name, &block)
# We have to pass the block directly to `define_method` to
# allow it to use method constructs like `super` and `return`.
raise "#let or #subject called without a block" if block.nil?
MemoizedHelpers.module_for(self).__send__(:define_method, name, &block)
# Apply the memoization. The method has been defined in an ancestor
# module so we can use `super` here to get the value.
if block.arity == 1
define_method(name) { __memoized.fetch_or_store(name) { super(RSpec.current_example, &nil) } }
else
define_method(name) { __memoized.fetch_or_store(name) { super(&nil) } }
end
end
# Just like `let`, except the block is invoked by an implicit `before`
# hook. This serves a dual purpose of setting up state and providing a
# memoized reference to that state.
#
# @example
#
# class Thing
# def self.count
# @count ||= 0
# end
#
# def self.count=(val)
# @count += val
# end
#
# def self.reset_count
# @count = 0
# end
#
# def initialize
# self.class.count += 1
# end
# end
#
# describe Thing do
# after(:example) { Thing.reset_count }
#
# context "using let" do
# let(:thing) { Thing.new }
#
# it "is not invoked implicitly" do
# Thing.count.should eq(0)
# end
#
# it "can be invoked explicitly" do
# thing
# Thing.count.should eq(1)
# end
# end
#
# context "using let!" do
# let!(:thing) { Thing.new }
#
# it "is invoked implicitly" do
# Thing.count.should eq(1)
# end
#
# it "returns memoized version on first invocation" do
# thing
# Thing.count.should eq(1)
# end
# end
# end
def let!(name, &block)
let(name, &block)
before { __send__(name) }
end
# Declares a `subject` for an example group which can then be wrapped
# with `expect` using `is_expected` to make it the target of an
# expectation in a concise, one-line example.
#
# Given a `name`, defines a method with that name which returns the
# `subject`. This lets you declare the subject once and access it
# implicitly in one-liners and explicitly using an intention revealing
# name.
#
# When given a `name`, calling `super` in the block is not supported.
#
# @note `subject` can be configured to be threadsafe or not.
# If it is threadsafe, it will take longer to access the value.
# If it is not threadsafe, it may behave in surprising ways in examples
# that spawn separate threads. Specify this on `RSpec.configure`
#
# @param name [String,Symbol] used to define an accessor with an
# intention revealing name
# @param block defines the value to be returned by `subject` in examples
#
# @example
#
# describe CheckingAccount, "with $50" do
# subject { CheckingAccount.new(Money.new(50, :USD)) }
# it { is_expected.to have_a_balance_of(Money.new(50, :USD)) }
# it { is_expected.not_to be_overdrawn }
# end
#
# describe CheckingAccount, "with a non-zero starting balance" do
# subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
# it { is_expected.not_to be_overdrawn }
# it "has a balance equal to the starting balance" do
# account.balance.should eq(Money.new(50, :USD))
# end
# end
#
# @see MemoizedHelpers#should
# @see MemoizedHelpers#should_not
# @see MemoizedHelpers#is_expected
def subject(name=nil, &block)
if name
let(name, &block)
alias_method :subject, name
self::NamedSubjectPreventSuper.__send__(:define_method, name) do
raise NotImplementedError, "`super` in named subjects is not supported"
end
else
let(:subject, &block)
end
end
# Just like `subject`, except the block is invoked by an implicit
# `before` hook. This serves a dual purpose of setting up state and
# providing a memoized reference to that state.
#
# @example
#
# class Thing
# def self.count
# @count ||= 0
# end
#
# def self.count=(val)
# @count += val
# end
#
# def self.reset_count
# @count = 0
# end
#
# def initialize
# self.class.count += 1
# end
# end
#
# describe Thing do
# after(:example) { Thing.reset_count }
#
# context "using subject" do
# subject { Thing.new }
#
# it "is not invoked implicitly" do
# Thing.count.should eq(0)
# end
#
# it "can be invoked explicitly" do
# subject
# Thing.count.should eq(1)
# end
# end
#
# context "using subject!" do
# subject!(:thing) { Thing.new }
#
# it "is invoked implicitly" do
# Thing.count.should eq(1)
# end
#
# it "returns memoized version on first invocation" do
# subject
# Thing.count.should eq(1)
# end
# end
# end
def subject!(name=nil, &block)
subject(name, &block)
before { subject }
end
end
# @private
#
# Gets the LetDefinitions module. The module is mixed into
# the example group and is used to hold all let definitions.
# This is done so that the block passed to `let` can be
# forwarded directly on to `define_method`, so that all method
# constructs (including `super` and `return`) can be used in
# a `let` block.
#
# The memoization is provided by a method definition on the
# example group that supers to the LetDefinitions definition
# in order to get the value to memoize.
def self.module_for(example_group)
get_constant_or_yield(example_group, :LetDefinitions) do
mod = Module.new do
include Module.new {
example_group.const_set(:NamedSubjectPreventSuper, self)
}
end
example_group.const_set(:LetDefinitions, mod)
mod
end
end
# @private
def self.define_helpers_on(example_group)
example_group.__send__(:include, module_for(example_group))
end
if Module.method(:const_defined?).arity == 1 # for 1.8
# @private
#
# Gets the named constant or yields.
# On 1.8, const_defined? / const_get do not take into
# account the inheritance hierarchy.
# :nocov:
def self.get_constant_or_yield(example_group, name)
if example_group.const_defined?(name)
example_group.const_get(name)
else
yield
end
end
# :nocov:
else
# @private
#
# Gets the named constant or yields.
# On 1.9, const_defined? / const_get take into account the
# the inheritance by default, and accept an argument to
# disable this behavior. It's important that we don't
# consider inheritance here; each example group level that
# uses a `let` should get its own `LetDefinitions` module.
def self.get_constant_or_yield(example_group, name)
if example_group.const_defined?(name, (check_ancestors = false))
example_group.const_get(name, check_ancestors)
else
yield
end
end
end
end
end
end
| 1 | 15,588 | Ah that's how it's happening, it's probably using the `require_relative` in the optimised one and that counts as a different require to the bare one. | rspec-rspec-core | rb |
@@ -27,6 +27,7 @@ namespace MvvmCross.Platforms.Ios.Binding.Views
: base(tableView)
{
_cellIdentifier = new NSString(cellIdentifier);
+ tableView.RegisterNibForCellReuse(UINib.FromName(cellIdentifier, NSBundle.MainBundle), cellIdentifier);
}
public MvxSimpleTableViewSource(UITableView tableView, string nibName, string cellIdentifier = null, | 1 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
using System;
using Foundation;
using MvvmCross.Logging;
using MvvmCross.Platforms.Ios;
using UIKit;
namespace MvvmCross.Platforms.Ios.Binding.Views
{
public class MvxSimpleTableViewSource : MvxTableViewSource
{
private readonly NSString _cellIdentifier;
private readonly MvxIosMajorVersionChecker _iosVersion6Checker = new MvxIosMajorVersionChecker(6);
protected virtual NSString CellIdentifier => _cellIdentifier;
public MvxSimpleTableViewSource(IntPtr handle)
: base(handle)
{
MvxLog.Instance.Warn("MvxSimpleTableViewSource IntPtr constructor used - we expect this only to be called during memory leak debugging - see https://github.com/MvvmCross/MvvmCross/pull/467");
}
public MvxSimpleTableViewSource(UITableView tableView, string cellIdentifier)
: base(tableView)
{
_cellIdentifier = new NSString(cellIdentifier);
}
public MvxSimpleTableViewSource(UITableView tableView, string nibName, string cellIdentifier = null,
NSBundle bundle = null)
: base(tableView)
{
// if no cellIdentifier supplied, then use the nibName as cellId
cellIdentifier = cellIdentifier ?? nibName;
_cellIdentifier = new NSString(cellIdentifier);
tableView.RegisterNibForCellReuse(UINib.FromName(nibName, bundle ?? NSBundle.MainBundle), cellIdentifier);
}
public MvxSimpleTableViewSource(UITableView tableView, Type cellType, string cellIdentifier = null)
: base(tableView)
{
// if no cellIdentifier supplied, then use the cell type name as cellId
cellIdentifier = cellIdentifier ?? cellType.Name;
_cellIdentifier = new NSString(cellIdentifier);
tableView.RegisterClassForCellReuse(cellType, _cellIdentifier);
}
protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
{
if (_iosVersion6Checker.IsVersionOrHigher)
return tableView.DequeueReusableCell(CellIdentifier, indexPath);
return tableView.DequeueReusableCell(CellIdentifier);
}
}
}
| 1 | 14,779 | What happens if there is no NIB/XIB with that name? | MvvmCross-MvvmCross | .cs |
@@ -79,7 +79,7 @@ type Server struct {
ap actpool.ActPool
gs *gasstation.GasStation
broadcastHandler BroadcastOutbound
- cfg config.API
+ cfg config.Config
registry *protocol.Registry
blockListener *blockListener
grpcserver *grpc.Server | 1 | // Copyright (c) 2019 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 api
import (
"context"
"encoding/hex"
"math/big"
"net"
"sort"
"strconv"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/iotexproject/iotex-proto/golang/iotexapi"
"github.com/iotexproject/iotex-proto/golang/iotextypes"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
"github.com/iotexproject/go-pkgs/hash"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/action/protocol"
"github.com/iotexproject/iotex-core/action/protocol/poll"
"github.com/iotexproject/iotex-core/action/protocol/rolldpos"
"github.com/iotexproject/iotex-core/actpool"
"github.com/iotexproject/iotex-core/blockchain"
"github.com/iotexproject/iotex-core/blockchain/block"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/dispatcher"
"github.com/iotexproject/iotex-core/gasstation"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/pkg/util/byteutil"
"github.com/iotexproject/iotex-core/pkg/version"
"github.com/iotexproject/iotex-core/state"
)
var (
// ErrInternalServer indicates the internal server error
ErrInternalServer = errors.New("internal server error")
// ErrReceipt indicates the error of receipt
ErrReceipt = errors.New("invalid receipt")
// ErrAction indicates the error of action
ErrAction = errors.New("invalid action")
)
// BroadcastOutbound sends a broadcast message to the whole network
type BroadcastOutbound func(ctx context.Context, chainID uint32, msg proto.Message) error
// Config represents the config to setup api
type Config struct {
broadcastHandler BroadcastOutbound
}
// Option is the option to override the api config
type Option func(cfg *Config) error
// WithBroadcastOutbound is the option to broadcast msg outbound
func WithBroadcastOutbound(broadcastHandler BroadcastOutbound) Option {
return func(cfg *Config) error {
cfg.broadcastHandler = broadcastHandler
return nil
}
}
// Server provides api for user to query blockchain data
type Server struct {
bc blockchain.Blockchain
dp dispatcher.Dispatcher
ap actpool.ActPool
gs *gasstation.GasStation
broadcastHandler BroadcastOutbound
cfg config.API
registry *protocol.Registry
blockListener *blockListener
grpcserver *grpc.Server
hasActionIndex bool
}
// NewServer creates a new server
func NewServer(
cfg config.Config,
chain blockchain.Blockchain,
dispatcher dispatcher.Dispatcher,
actPool actpool.ActPool,
registry *protocol.Registry,
opts ...Option,
) (*Server, error) {
apiCfg := Config{}
for _, opt := range opts {
if err := opt(&apiCfg); err != nil {
return nil, err
}
}
if cfg.API == (config.API{}) {
log.L().Warn("API server is not configured.")
cfg.API = config.Default.API
}
if cfg.API.RangeQueryLimit < uint64(cfg.API.TpsWindow) {
return nil, errors.New("range query upper limit cannot be less than tps window")
}
svr := &Server{
bc: chain,
dp: dispatcher,
ap: actPool,
broadcastHandler: apiCfg.broadcastHandler,
cfg: cfg.API,
registry: registry,
blockListener: newBlockListener(),
gs: gasstation.NewGasStation(chain, cfg.API, cfg.Genesis.ActionGasLimit),
}
if _, ok := cfg.Plugins[config.GatewayPlugin]; ok {
svr.hasActionIndex = true
}
svr.grpcserver = grpc.NewServer(
grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
)
iotexapi.RegisterAPIServiceServer(svr.grpcserver, svr)
grpc_prometheus.Register(svr.grpcserver)
reflection.Register(svr.grpcserver)
return svr, nil
}
// GetAccount returns the metadata of an account
func (api *Server) GetAccount(ctx context.Context, in *iotexapi.GetAccountRequest) (*iotexapi.GetAccountResponse, error) {
state, err := api.bc.StateByAddr(in.Address)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
pendingNonce, err := api.ap.GetPendingNonce(in.Address)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
numActions, err := api.bc.GetActionCountByAddress(in.Address)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
accountMeta := &iotextypes.AccountMeta{
Address: in.Address,
Balance: state.Balance.String(),
Nonce: state.Nonce,
PendingNonce: pendingNonce,
NumActions: numActions,
}
return &iotexapi.GetAccountResponse{AccountMeta: accountMeta}, nil
}
// GetActions returns actions
func (api *Server) GetActions(ctx context.Context, in *iotexapi.GetActionsRequest) (*iotexapi.GetActionsResponse, error) {
if !api.hasActionIndex && (in.GetByHash() != nil || in.GetByAddr() != nil) {
return nil, status.Error(codes.NotFound, "Action index is not available.")
}
switch {
case in.GetByIndex() != nil:
request := in.GetByIndex()
return api.getActions(request.Start, request.Count)
case in.GetByHash() != nil:
request := in.GetByHash()
return api.getSingleAction(request.ActionHash, request.CheckPending)
case in.GetByAddr() != nil:
request := in.GetByAddr()
return api.getActionsByAddress(request.Address, request.Start, request.Count)
case in.GetUnconfirmedByAddr() != nil:
request := in.GetUnconfirmedByAddr()
return api.getUnconfirmedActionsByAddress(request.Address, request.Start, request.Count)
case in.GetByBlk() != nil:
request := in.GetByBlk()
return api.getActionsByBlock(request.BlkHash, request.Start, request.Count)
default:
return nil, status.Error(codes.NotFound, "invalid GetActionsRequest type")
}
}
// GetBlockMetas returns block metadata
func (api *Server) GetBlockMetas(ctx context.Context, in *iotexapi.GetBlockMetasRequest) (*iotexapi.GetBlockMetasResponse, error) {
switch {
case in.GetByIndex() != nil:
request := in.GetByIndex()
return api.getBlockMetas(request.Start, request.Count)
case in.GetByHash() != nil:
request := in.GetByHash()
return api.getBlockMeta(request.BlkHash)
default:
return nil, status.Error(codes.NotFound, "invalid GetBlockMetasRequest type")
}
}
// GetChainMeta returns blockchain metadata
func (api *Server) GetChainMeta(ctx context.Context, in *iotexapi.GetChainMetaRequest) (*iotexapi.GetChainMetaResponse, error) {
tipHeight := api.bc.TipHeight()
if tipHeight == 0 {
return &iotexapi.GetChainMetaResponse{
ChainMeta: &iotextypes.ChainMeta{
Epoch: &iotextypes.EpochData{},
},
}, nil
}
totalActions, err := api.bc.GetTotalActions()
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
blockLimit := int64(api.cfg.TpsWindow)
if blockLimit <= 0 {
return nil, status.Errorf(codes.Internal, "block limit is %d", blockLimit)
}
// avoid genesis block
if int64(tipHeight) < blockLimit {
blockLimit = int64(tipHeight)
}
r, err := api.getBlockMetas(tipHeight-uint64(blockLimit)+1, uint64(blockLimit))
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
blks := r.BlkMetas
if len(blks) == 0 {
return nil, status.Error(codes.NotFound, "get 0 blocks! not able to calculate aps")
}
var numActions int64
for _, blk := range blks {
numActions += blk.NumActions
}
p, ok := api.registry.Find(rolldpos.ProtocolID)
if !ok {
return nil, status.Error(codes.Internal, "rolldpos protocol is not registered")
}
rp, ok := p.(*rolldpos.Protocol)
if !ok {
return nil, status.Error(codes.Internal, "fail to cast rolldpos protocol")
}
epochNum := rp.GetEpochNum(tipHeight)
epochHeight := rp.GetEpochHeight(epochNum)
gravityChainStartHeight, err := api.getGravityChainStartHeight(epochHeight)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
timeDuration := blks[len(blks)-1].Timestamp.GetSeconds() - blks[0].Timestamp.GetSeconds()
// if time duration is less than 1 second, we set it to be 1 second
if timeDuration < 1 {
timeDuration = 1
}
tps := numActions / timeDuration
chainMeta := &iotextypes.ChainMeta{
Height: tipHeight,
Epoch: &iotextypes.EpochData{
Num: epochNum,
Height: epochHeight,
GravityChainStartHeight: gravityChainStartHeight,
},
NumActions: int64(totalActions),
Tps: tps,
}
return &iotexapi.GetChainMetaResponse{ChainMeta: chainMeta}, nil
}
// GetServerMeta gets the server metadata
func (api *Server) GetServerMeta(ctx context.Context,
in *iotexapi.GetServerMetaRequest) (*iotexapi.GetServerMetaResponse, error) {
return &iotexapi.GetServerMetaResponse{ServerMeta: &iotextypes.ServerMeta{
PackageVersion: version.PackageVersion,
PackageCommitID: version.PackageCommitID,
GitStatus: version.GitStatus,
GoVersion: version.GoVersion,
BuildTime: version.BuildTime,
}}, nil
}
// SendAction is the API to send an action to blockchain.
func (api *Server) SendAction(ctx context.Context, in *iotexapi.SendActionRequest) (res *iotexapi.SendActionResponse, err error) {
log.L().Debug("receive send action request")
// broadcast to the network
if err = api.broadcastHandler(context.Background(), api.bc.ChainID(), in.Action); err != nil {
log.L().Warn("Failed to broadcast SendAction request.", zap.Error(err))
}
// send to actpool via dispatcher
api.dp.HandleBroadcast(context.Background(), api.bc.ChainID(), in.Action)
var selp action.SealedEnvelope
if err = selp.LoadProto(in.Action); err != nil {
return
}
hash := selp.Hash()
return &iotexapi.SendActionResponse{ActionHash: hex.EncodeToString(hash[:])}, nil
}
// GetReceiptByAction gets receipt with corresponding action hash
func (api *Server) GetReceiptByAction(ctx context.Context, in *iotexapi.GetReceiptByActionRequest) (*iotexapi.GetReceiptByActionResponse, error) {
if !api.hasActionIndex {
return nil, status.Error(codes.NotFound, "Receipt index is not available")
}
actHash, err := hash.HexStringToHash256(in.ActionHash)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
receipt, err := api.bc.GetReceiptByActionHash(actHash)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
blkHash, err := api.bc.GetBlockHashByActionHash(actHash)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
return &iotexapi.GetReceiptByActionResponse{
ReceiptInfo: &iotexapi.ReceiptInfo{
Receipt: receipt.ConvertToReceiptPb(),
BlkHash: hex.EncodeToString(blkHash[:]),
},
}, nil
}
// ReadContract reads the state in a contract address specified by the slot
func (api *Server) ReadContract(ctx context.Context, in *iotexapi.ReadContractRequest) (*iotexapi.ReadContractResponse, error) {
log.L().Debug("receive read smart contract request")
sc := &action.Execution{}
if err := sc.LoadProto(in.Execution); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
caller, err := api.bc.StateByAddr(in.CallerAddress)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
sc, _ = action.NewExecution(
sc.Contract(),
caller.Nonce+1,
sc.Amount(),
api.gs.ActionGasLimit(),
big.NewInt(0),
sc.Data(),
)
callerAddr, err := address.FromString(in.CallerAddress)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
retval, receipt, err := api.bc.ExecuteContractRead(callerAddr, sc)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &iotexapi.ReadContractResponse{
Data: hex.EncodeToString(retval),
Receipt: receipt.ConvertToReceiptPb(),
}, nil
}
// ReadState reads state on blockchain
func (api *Server) ReadState(ctx context.Context, in *iotexapi.ReadStateRequest) (*iotexapi.ReadStateResponse, error) {
res, err := api.readState(ctx, in)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
return res, nil
}
// SuggestGasPrice suggests gas price
func (api *Server) SuggestGasPrice(ctx context.Context, in *iotexapi.SuggestGasPriceRequest) (*iotexapi.SuggestGasPriceResponse, error) {
suggestPrice, err := api.gs.SuggestGasPrice()
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &iotexapi.SuggestGasPriceResponse{GasPrice: suggestPrice}, nil
}
// EstimateGasForAction estimates gas for action
func (api *Server) EstimateGasForAction(ctx context.Context, in *iotexapi.EstimateGasForActionRequest) (*iotexapi.EstimateGasForActionResponse, error) {
estimateGas, err := api.gs.EstimateGasForAction(in.Action)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &iotexapi.EstimateGasForActionResponse{Gas: estimateGas}, nil
}
// GetEpochMeta gets epoch metadata
func (api *Server) GetEpochMeta(
ctx context.Context,
in *iotexapi.GetEpochMetaRequest,
) (*iotexapi.GetEpochMetaResponse, error) {
if in.EpochNumber < 1 {
return nil, status.Error(codes.InvalidArgument, "epoch number cannot be less than one")
}
p, ok := api.registry.Find(rolldpos.ProtocolID)
if !ok {
return nil, status.Error(codes.Internal, "rolldpos protocol is not registered")
}
rp, ok := p.(*rolldpos.Protocol)
if !ok {
return nil, status.Error(codes.Internal, "fail to cast rolldpos protocol")
}
epochHeight := rp.GetEpochHeight(in.EpochNumber)
gravityChainStartHeight, err := api.getGravityChainStartHeight(epochHeight)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
epochData := &iotextypes.EpochData{
Num: in.EpochNumber,
Height: epochHeight,
GravityChainStartHeight: gravityChainStartHeight,
}
numBlks, produce, err := api.bc.ProductivityByEpoch(in.EpochNumber)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
readStateRequest := &iotexapi.ReadStateRequest{
ProtocolID: []byte(poll.ProtocolID),
MethodName: []byte("BlockProducersByEpoch"),
Arguments: [][]byte{byteutil.Uint64ToBytes(in.EpochNumber)},
}
res, err := api.readState(context.Background(), readStateRequest)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
var BlockProducers state.CandidateList
if err := BlockProducers.Deserialize(res.Data); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
var blockProducersInfo []*iotexapi.BlockProducerInfo
for _, bp := range BlockProducers {
var active bool
var blockProduction uint64
if production, ok := produce[bp.Address]; ok {
active = true
blockProduction = production
}
blockProducersInfo = append(blockProducersInfo, &iotexapi.BlockProducerInfo{
Address: bp.Address,
Votes: bp.Votes.String(),
Active: active,
Production: blockProduction,
})
}
return &iotexapi.GetEpochMetaResponse{
EpochData: epochData,
TotalBlocks: numBlks,
BlockProducersInfo: blockProducersInfo,
}, nil
}
// GetRawBlocks gets raw block data
func (api *Server) GetRawBlocks(
ctx context.Context,
in *iotexapi.GetRawBlocksRequest,
) (*iotexapi.GetRawBlocksResponse, error) {
if in.Count == 0 || in.Count > api.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
tipHeight := api.bc.TipHeight()
if in.StartHeight > tipHeight {
return nil, status.Error(codes.InvalidArgument, "start height should not exceed tip height")
}
var res []*iotexapi.BlockInfo
for height := int(in.StartHeight); height <= int(tipHeight); height++ {
if uint64(len(res)) >= in.Count {
break
}
blk, err := api.bc.GetBlockByHeight(uint64(height))
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
var receiptsPb []*iotextypes.Receipt
if in.WithReceipts {
receipts, err := api.bc.GetReceiptsByHeight(uint64(height))
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
for _, receipt := range receipts {
receiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())
}
}
res = append(res, &iotexapi.BlockInfo{
Block: blk.ConvertToBlockPb(),
Receipts: receiptsPb,
})
}
return &iotexapi.GetRawBlocksResponse{Blocks: res}, nil
}
// StreamBlocks streams blocks
func (api *Server) StreamBlocks(in *iotexapi.StreamBlocksRequest, stream iotexapi.APIService_StreamBlocksServer) error {
errChan := make(chan error)
if err := api.blockListener.AddStream(stream, errChan); err != nil {
return status.Error(codes.Internal, err.Error())
}
for {
select {
case err := <-errChan:
if err != nil {
err = status.Error(codes.Aborted, err.Error())
}
return err
}
}
}
// Start starts the API server
func (api *Server) Start() error {
portStr := ":" + strconv.Itoa(api.cfg.Port)
lis, err := net.Listen("tcp", portStr)
if err != nil {
log.L().Error("API server failed to listen.", zap.Error(err))
return errors.Wrap(err, "API server failed to listen")
}
log.L().Info("API server is listening.", zap.String("addr", lis.Addr().String()))
go func() {
if err := api.grpcserver.Serve(lis); err != nil {
log.L().Fatal("Node failed to serve.", zap.Error(err))
}
}()
if err := api.bc.AddSubscriber(api.blockListener); err != nil {
return errors.Wrap(err, "failed to subscribe to block creations")
}
if err := api.blockListener.Start(); err != nil {
return errors.Wrap(err, "failed to start block listener")
}
return nil
}
// Stop stops the API server
func (api *Server) Stop() error {
api.grpcserver.Stop()
if err := api.bc.RemoveSubscriber(api.blockListener); err != nil {
return errors.Wrap(err, "failed to unsubscribe block listener")
}
return api.blockListener.Stop()
}
func (api *Server) readState(ctx context.Context, in *iotexapi.ReadStateRequest) (*iotexapi.ReadStateResponse, error) {
p, ok := api.registry.Find(string(in.ProtocolID))
if !ok {
return nil, status.Errorf(codes.Internal, "protocol %s isn't registered", string(in.ProtocolID))
}
// TODO: need to complete the context
ctx = protocol.WithRunActionsCtx(ctx, protocol.RunActionsCtx{
BlockHeight: api.bc.TipHeight(),
Registry: api.registry,
})
ws, err := api.bc.GetFactory().NewWorkingSet()
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
data, err := p.ReadState(ctx, ws, in.MethodName, in.Arguments...)
// TODO: need to distinguish user error and system error
if err != nil {
return nil, err
}
out := iotexapi.ReadStateResponse{
Data: data,
}
return &out, nil
}
func (api *Server) getActionsFromIndex(totalActions, start, count uint64) (*iotexapi.GetActionsResponse, error) {
var actionInfo []*iotexapi.ActionInfo
for i := start; i < start+count; i++ {
hash, err := api.bc.GetActionHashFromIndex(i)
if err != nil {
continue
}
act, err := api.getAction(hash, false)
if err != nil {
return nil, status.Error(codes.Unavailable, err.Error())
}
actionInfo = append(actionInfo, act)
}
return &iotexapi.GetActionsResponse{
Total: totalActions,
ActionInfo: actionInfo,
}, nil
}
// GetActions returns actions within the range
// This is a workaround for the slow access issue if the start index is very big
func (api *Server) getActions(start uint64, count uint64) (*iotexapi.GetActionsResponse, error) {
if count > api.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
totalActions, err := api.bc.GetTotalActions()
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if totalActions == uint64(0) {
return &iotexapi.GetActionsResponse{}, nil
}
if start >= totalActions {
return nil, status.Error(codes.InvalidArgument, "start exceeds the limit")
}
if api.hasActionIndex {
return api.getActionsFromIndex(totalActions, start, count)
}
// Finding actions in reverse order saves time for querying most recent actions
reverseStart := totalActions - (start + count)
if totalActions < start+count {
reverseStart = uint64(0)
count = totalActions - start
}
var res []*iotexapi.ActionInfo
var hit bool
for height := api.bc.TipHeight(); height >= 1 && count > 0; height-- {
blk, err := api.bc.GetBlockByHeight(height)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
if !hit && reverseStart >= uint64(len(blk.Actions)) {
reverseStart -= uint64(len(blk.Actions))
continue
}
// now reverseStart < len(blk.Actions), we are going to fetch actions from this block
hit = true
act := api.reverseActionsInBlock(blk, reverseStart, count)
res = append(act, res...)
count -= uint64(len(act))
reverseStart = 0
}
return &iotexapi.GetActionsResponse{
Total: totalActions,
ActionInfo: res,
}, nil
}
// getSingleAction returns action by action hash
func (api *Server) getSingleAction(actionHash string, checkPending bool) (*iotexapi.GetActionsResponse, error) {
actHash, err := hash.HexStringToHash256(actionHash)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
act, err := api.getAction(actHash, checkPending)
if err != nil {
return nil, status.Error(codes.Unavailable, err.Error())
}
return &iotexapi.GetActionsResponse{
Total: 1,
ActionInfo: []*iotexapi.ActionInfo{act},
}, nil
}
// getActionsByAddress returns all actions associated with an address
func (api *Server) getActionsByAddress(address string, start uint64, count uint64) (*iotexapi.GetActionsResponse, error) {
if count > api.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
actions, err := api.getTotalActionsByAddress(address)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
if len(actions) == 0 {
return &iotexapi.GetActionsResponse{}, nil
}
if start >= uint64(len(actions)) {
return nil, status.Error(codes.InvalidArgument, "start exceeds the limit")
}
var res []*iotexapi.ActionInfo
for i := start; i < uint64(len(actions)) && i < start+count; i++ {
act, err := api.getAction(actions[i], false)
if err != nil {
continue
}
res = append(res, act)
}
// sort action by timestamp
sort.Slice(res, func(i, j int) bool {
return res[i].Timestamp.Seconds < res[j].Timestamp.Seconds
})
return &iotexapi.GetActionsResponse{
Total: uint64(len(actions)),
ActionInfo: res,
}, nil
}
// getUnconfirmedActionsByAddress returns all unconfirmed actions in actpool associated with an address
func (api *Server) getUnconfirmedActionsByAddress(address string, start uint64, count uint64) (*iotexapi.GetActionsResponse, error) {
if count > api.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
selps := api.ap.GetUnconfirmedActs(address)
if len(selps) == 0 {
return &iotexapi.GetActionsResponse{}, nil
}
if start >= uint64(len(selps)) {
return nil, status.Error(codes.InvalidArgument, "start exceeds the limit")
}
var res []*iotexapi.ActionInfo
for i := start; i < uint64(len(selps)) && i < start+count; i++ {
act, err := api.pendingAction(selps[i])
if err != nil {
continue
}
res = append(res, act)
}
return &iotexapi.GetActionsResponse{
Total: uint64(len(selps)),
ActionInfo: res,
}, nil
}
// getActionsByBlock returns all actions in a block
func (api *Server) getActionsByBlock(blkHash string, start uint64, count uint64) (*iotexapi.GetActionsResponse, error) {
if count > api.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
hash, err := hash.HexStringToHash256(blkHash)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
blk, err := api.bc.GetBlockByHash(hash)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
if len(blk.Actions) == 0 {
return &iotexapi.GetActionsResponse{}, nil
}
if start >= uint64(len(blk.Actions)) {
return nil, status.Error(codes.InvalidArgument, "start exceeds the limit")
}
res := api.actionsInBlock(blk, start, count)
return &iotexapi.GetActionsResponse{
Total: uint64(len(blk.Actions)),
ActionInfo: res,
}, nil
}
// getBlockMetas gets block within the height range
func (api *Server) getBlockMetas(start uint64, count uint64) (*iotexapi.GetBlockMetasResponse, error) {
if count > api.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
tipHeight := api.bc.TipHeight()
if start > tipHeight {
return nil, status.Error(codes.InvalidArgument, "start height should not exceed tip height")
}
var res []*iotextypes.BlockMeta
for height := start; height <= tipHeight && count > 0; height++ {
blk, err := api.bc.GetBlockByHeight(height)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
hash := blk.HashBlock()
ts, _ := ptypes.TimestampProto(blk.Header.Timestamp())
txRoot := blk.TxRoot()
receiptRoot := blk.ReceiptRoot()
deltaStateDigest := blk.DeltaStateDigest()
transferAmount := getTranferAmountInBlock(blk)
blockMeta := &iotextypes.BlockMeta{
Hash: hex.EncodeToString(hash[:]),
Height: blk.Height(),
Timestamp: ts,
NumActions: int64(len(blk.Actions)),
ProducerAddress: blk.ProducerAddress(),
TransferAmount: transferAmount.String(),
TxRoot: hex.EncodeToString(txRoot[:]),
ReceiptRoot: hex.EncodeToString(receiptRoot[:]),
DeltaStateDigest: hex.EncodeToString(deltaStateDigest[:]),
}
res = append(res, blockMeta)
count--
}
return &iotexapi.GetBlockMetasResponse{
Total: tipHeight,
BlkMetas: res,
}, nil
}
// getBlockMeta returns block by block hash
func (api *Server) getBlockMeta(blkHash string) (*iotexapi.GetBlockMetasResponse, error) {
hash, err := hash.HexStringToHash256(blkHash)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
blk, err := api.bc.GetBlockByHash(hash)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
ts, _ := ptypes.TimestampProto(blk.Header.Timestamp())
txRoot := blk.TxRoot()
receiptRoot := blk.ReceiptRoot()
deltaStateDigest := blk.DeltaStateDigest()
transferAmount := getTranferAmountInBlock(blk)
blockMeta := &iotextypes.BlockMeta{
Hash: blkHash,
Height: blk.Height(),
Timestamp: ts,
NumActions: int64(len(blk.Actions)),
ProducerAddress: blk.ProducerAddress(),
TransferAmount: transferAmount.String(),
TxRoot: hex.EncodeToString(txRoot[:]),
ReceiptRoot: hex.EncodeToString(receiptRoot[:]),
DeltaStateDigest: hex.EncodeToString(deltaStateDigest[:]),
}
return &iotexapi.GetBlockMetasResponse{
Total: 1,
BlkMetas: []*iotextypes.BlockMeta{blockMeta},
}, nil
}
func (api *Server) getGravityChainStartHeight(epochHeight uint64) (uint64, error) {
gravityChainStartHeight := epochHeight
if _, ok := api.registry.Find(poll.ProtocolID); ok {
readStateRequest := &iotexapi.ReadStateRequest{
ProtocolID: []byte(poll.ProtocolID),
MethodName: []byte("GetGravityChainStartHeight"),
Arguments: [][]byte{byteutil.Uint64ToBytes(epochHeight)},
}
res, err := api.readState(context.Background(), readStateRequest)
if err != nil {
return 0, err
}
gravityChainStartHeight = byteutil.BytesToUint64(res.GetData())
}
return gravityChainStartHeight, nil
}
func (api *Server) committedAction(selp action.SealedEnvelope) (*iotexapi.ActionInfo, error) {
actHash := selp.Hash()
blkHash, err := api.bc.GetBlockHashByActionHash(actHash)
if err != nil {
return nil, err
}
header, err := api.bc.BlockHeaderByHash(blkHash)
if err != nil {
return nil, err
}
sender, _ := address.FromBytes(selp.SrcPubkey().Hash())
receipt, err := api.bc.GetReceiptByActionHash(actHash)
if err != nil {
return nil, err
}
gas := new(big.Int)
gas = gas.Mul(selp.GasPrice(), big.NewInt(int64(receipt.GasConsumed)))
return &iotexapi.ActionInfo{
Action: selp.Proto(),
ActHash: hex.EncodeToString(actHash[:]),
BlkHash: hex.EncodeToString(blkHash[:]),
BlkHeight: header.Height(),
Sender: sender.String(),
GasFee: gas.String(),
Timestamp: header.BlockHeaderCoreProto().Timestamp,
}, nil
}
func (api *Server) pendingAction(selp action.SealedEnvelope) (*iotexapi.ActionInfo, error) {
actHash := selp.Hash()
sender, _ := address.FromBytes(selp.SrcPubkey().Hash())
return &iotexapi.ActionInfo{
Action: selp.Proto(),
ActHash: hex.EncodeToString(actHash[:]),
BlkHash: hex.EncodeToString(hash.ZeroHash256[:]),
BlkHeight: 0,
Sender: sender.String(),
Timestamp: nil,
}, nil
}
func (api *Server) getAction(actHash hash.Hash256, checkPending bool) (*iotexapi.ActionInfo, error) {
selp, err := api.bc.GetActionByActionHash(actHash)
if err == nil {
return api.committedAction(selp)
}
// Try to fetch pending action from actpool
if checkPending {
selp, err = api.ap.GetActionByHash(actHash)
}
if err != nil {
return nil, err
}
return api.pendingAction(selp)
}
func (api *Server) getTotalActionsByAddress(address string) ([]hash.Hash256, error) {
actions, err := api.bc.GetActionsFromAddress(address)
if err != nil {
return nil, err
}
actionsToAddress, err := api.bc.GetActionsToAddress(address)
if err != nil {
return nil, err
}
return append(actions, actionsToAddress...), nil
}
func (api *Server) actionsInBlock(blk *block.Block, start, count uint64) []*iotexapi.ActionInfo {
h := blk.HashBlock()
blkHash := hex.EncodeToString(h[:])
blkHeight := blk.Height()
ts := blk.Header.BlockHeaderCoreProto().Timestamp
var res []*iotexapi.ActionInfo
for i := start; i < uint64(len(blk.Actions)) && i < start+count; i++ {
selp := blk.Actions[i]
actHash := selp.Hash()
sender, _ := address.FromBytes(selp.SrcPubkey().Hash())
res = append(res, &iotexapi.ActionInfo{
Action: selp.Proto(),
ActHash: hex.EncodeToString(actHash[:]),
BlkHash: blkHash,
BlkHeight: blkHeight,
Sender: sender.String(),
Timestamp: ts,
})
}
return res
}
func (api *Server) reverseActionsInBlock(blk *block.Block, reverseStart, count uint64) []*iotexapi.ActionInfo {
h := blk.HashBlock()
blkHash := hex.EncodeToString(h[:])
blkHeight := blk.Height()
ts := blk.Header.BlockHeaderCoreProto().Timestamp
var res []*iotexapi.ActionInfo
for i := reverseStart; i < uint64(len(blk.Actions)) && i < reverseStart+count; i++ {
ri := uint64(len(blk.Actions)) - 1 - i
selp := blk.Actions[ri]
actHash := selp.Hash()
sender, _ := address.FromBytes(selp.SrcPubkey().Hash())
res = append([]*iotexapi.ActionInfo{
{
Action: selp.Proto(),
ActHash: hex.EncodeToString(actHash[:]),
BlkHash: blkHash,
BlkHeight: blkHeight,
Sender: sender.String(),
Timestamp: ts,
},
}, res...)
}
return res
}
func getTranferAmountInBlock(blk *block.Block) *big.Int {
totalAmount := big.NewInt(0)
for _, selp := range blk.Actions {
transfer, ok := selp.Action().(*action.Transfer)
if !ok {
continue
}
totalAmount.Add(totalAmount, transfer.Amount())
}
return totalAmount
}
| 1 | 18,199 | this is not necessary? | iotexproject-iotex-core | go |
@@ -19,6 +19,7 @@ import (
"github.com/aws/amazon-ecs-agent/agent/taskresource"
asmauthres "github.com/aws/amazon-ecs-agent/agent/taskresource/asmauth"
+ asmsecretres "github.com/aws/amazon-ecs-agent/agent/taskresource/asmsecret"
cgroupres "github.com/aws/amazon-ecs-agent/agent/taskresource/cgroup"
ssmsecretres "github.com/aws/amazon-ecs-agent/agent/taskresource/ssmsecret"
"github.com/aws/amazon-ecs-agent/agent/taskresource/volume" | 1 | // Copyright 2018 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 types
import (
"encoding/json"
"errors"
"github.com/aws/amazon-ecs-agent/agent/taskresource"
asmauthres "github.com/aws/amazon-ecs-agent/agent/taskresource/asmauth"
cgroupres "github.com/aws/amazon-ecs-agent/agent/taskresource/cgroup"
ssmsecretres "github.com/aws/amazon-ecs-agent/agent/taskresource/ssmsecret"
"github.com/aws/amazon-ecs-agent/agent/taskresource/volume"
)
const (
// CgroupKey is the string used in resources map to represent cgroup resource
CgroupKey = "cgroup"
// DockerVolumeKey is the string used in resources map to represent docker volume
DockerVolumeKey = "dockerVolume"
// ASMAuthKey is the string used in resources map to represent asm auth
ASMAuthKey = asmauthres.ResourceName
// SSMSecretKey is the string used in resources map to represent ssm secret
SSMSecretKey = ssmsecretres.ResourceName
)
// ResourcesMap represents the map of resource type to the corresponding resource
// objects
type ResourcesMap map[string][]taskresource.TaskResource
// UnmarshalJSON unmarshals ResourcesMap object
func (rm *ResourcesMap) UnmarshalJSON(data []byte) error {
resources := make(map[string]json.RawMessage)
err := json.Unmarshal(data, &resources)
if err != nil {
return err
}
result := make(map[string][]taskresource.TaskResource)
for key, value := range resources {
switch key {
case CgroupKey:
if unmarshlCgroup(key, value, result) != nil {
return err
}
case DockerVolumeKey:
if unmarshalDockerVolume(key, value, result) != nil {
return err
}
case ASMAuthKey:
if unmarshalASMAuthKey(key, value, result) != nil {
return err
}
case SSMSecretKey:
if unmarshalSSMSecretKey(key, value, result) != nil {
return err
}
default:
return errors.New("Unsupported resource type")
}
}
*rm = result
return nil
}
func unmarshlCgroup(key string, value json.RawMessage, result map[string][]taskresource.TaskResource) error {
var cgroups []json.RawMessage
err := json.Unmarshal(value, &cgroups)
if err != nil {
return err
}
for _, c := range cgroups {
cgroup := &cgroupres.CgroupResource{}
err := cgroup.UnmarshalJSON(c)
if err != nil {
return err
}
result[key] = append(result[key], cgroup)
}
return nil
}
func unmarshalDockerVolume(key string, value json.RawMessage, result map[string][]taskresource.TaskResource) error {
var volumes []json.RawMessage
err := json.Unmarshal(value, &volumes)
if err != nil {
return err
}
for _, vol := range volumes {
dockerVolume := &volume.VolumeResource{}
err := dockerVolume.UnmarshalJSON(vol)
if err != nil {
return err
}
result[key] = append(result[key], dockerVolume)
}
return nil
}
func unmarshalASMAuthKey(key string, value json.RawMessage, result map[string][]taskresource.TaskResource) error {
var asmauths []json.RawMessage
err := json.Unmarshal(value, &asmauths)
if err != nil {
return err
}
for _, a := range asmauths {
auth := &asmauthres.ASMAuthResource{}
err := auth.UnmarshalJSON(a)
if err != nil {
return err
}
result[key] = append(result[key], auth)
}
return nil
}
func unmarshalSSMSecretKey(key string, value json.RawMessage, result map[string][]taskresource.TaskResource) error {
var ssmsecrets []json.RawMessage
err := json.Unmarshal(value, &ssmsecrets)
if err != nil {
return err
}
for _, secret := range ssmsecrets {
res := &ssmsecretres.SSMSecretResource{}
err := res.UnmarshalJSON(secret)
if err != nil {
return err
}
result[key] = append(result[key], res)
}
return nil
}
| 1 | 21,333 | typo: `asmsecrets "github...` | aws-amazon-ecs-agent | go |
@@ -269,14 +269,14 @@ function neve_sanitize_meta_ordering( $value ) {
);
if ( empty( $value ) ) {
- return $allowed;
+ return wp_json_encode( $allowed );
}
$decoded = json_decode( $value, true );
foreach ( $decoded as $val ) {
if ( ! in_array( $val, $allowed, true ) ) {
- return $allowed;
+ return wp_json_encode( $allowed );
}
}
| 1 | <?php
/**
*
* Sanitize functions.
*
* Author: Andrei Baicus <[email protected]>
* Created on: 20/08/2018
*
* @package Neve\Globals
*/
/**
* Function to sanitize alpha color.
*
* @param string $value Hex or RGBA color.
*
* @return string
*/
function neve_sanitize_colors( $value ) {
$is_var = ( strpos( $value, 'var' ) !== false );
if ( $is_var ) {
return sanitize_text_field( $value );
}
// Is this an rgba color or a hex?
$mode = ( false === strpos( $value, 'rgba' ) ) ? 'hex' : 'rgba';
if ( 'rgba' === $mode ) {
return neve_sanitize_rgba( $value );
} else {
return sanitize_hex_color( $value );
}
}
/**
* Sanitize rgba color.
*
* @param string $value Color in rgba format.
*
* @return string
*/
function neve_sanitize_rgba( $value ) {
$red = 'rgba(0,0,0,0)';
$green = 'rgba(0,0,0,0)';
$blue = 'rgba(0,0,0,0)';
$alpha = 'rgba(0,0,0,0)'; // If empty or an array return transparent
// By now we know the string is formatted as an rgba color so we need to further sanitize it.
$value = str_replace( ' ', '', $value );
sscanf( $value, 'rgba(%d,%d,%d,%f)', $red, $green, $blue, $alpha );
return 'rgba(' . $red . ',' . $green . ',' . $blue . ',' . $alpha . ')';
}
/**
* Sanitize checkbox output.
*
* @param bool $value value to be sanitized.
*
* @return bool
*/
function neve_sanitize_checkbox( $value ) {
return true === (bool) $value;
}
/**
* Check if a string is in json format
*
* @param string $string Input.
*
* @return bool
* @since 1.1.38
*/
function neve_is_json( $string ) {
return is_string( $string ) && is_array( json_decode( $string, true ) );
}
/**
* Sanitize values for range inputs.
*
* @param string $input Control input.
*
* @return string|float Returns json string or float.
*/
function neve_sanitize_range_value( $input ) {
if ( ! neve_is_json( $input ) ) {
return floatval( $input );
}
$range_value = json_decode( $input, true );
$range_value['desktop'] = isset( $range_value['desktop'] ) && is_numeric( $range_value['desktop'] ) ? floatval( $range_value['desktop'] ) : '';
$range_value['tablet'] = isset( $range_value['tablet'] ) && is_numeric( $range_value['tablet'] ) ? floatval( $range_value['tablet'] ) : '';
$range_value['mobile'] = isset( $range_value['mobile'] ) && is_numeric( $range_value['mobile'] ) ? floatval( $range_value['mobile'] ) : '';
return wp_json_encode( $range_value );
}
/**
* Sanitize font weight values.
*
* @param string $value font-weight value.
*
* @return string
*/
function neve_sanitize_font_weight( $value ) {
$allowed = array( '100', '200', '300', '400', '500', '600', '700', '800', '900' );
if ( ! in_array( (string) $value, $allowed, true ) ) {
return '300';
}
return $value;
}
/**
* Sanitize font weight values.
*
* @param string $value font-weight value.
*
* @return string
*/
function neve_sanitize_text_transform( $value ) {
$allowed = array( 'none', 'capitalize', 'uppercase', 'lowercase' );
if ( ! in_array( $value, $allowed, true ) ) {
return 'none';
}
return $value;
}
/**
* Sanitize the background control.
*
* @param array $value input value.
*
* @return WP_Error | array
*/
function neve_sanitize_background( $value ) {
if ( ! is_array( $value ) ) {
return new WP_Error();
}
if ( ! isset( $value['type'] ) || ! in_array( $value['type'], array( 'image', 'color' ), true ) ) {
return new WP_Error();
}
return $value;
}
/**
* Sanitize the button appearance control.
*
* @param array $value the control value.
*
* @return array
*/
function neve_sanitize_button_appearance( $value ) {
return $value;
}
/**
* Sanitize the typography control.
*
* @param array $value the control value.
*
* @return array
*/
function neve_sanitize_typography_control( $value ) {
$keys = [
'lineHeight',
'letterSpacing',
'fontWeight',
'fontSize',
'textTransform',
];
// Approve Keys.
foreach ( $value as $key => $values ) {
if ( ! in_array( $key, $keys, true ) ) {
unset( $value[ $key ] );
}
}
// Font Weight.
if ( ! in_array( $value['fontWeight'], [ '100', '200', '300', '400', '500', '600', '700', '800', '900' ], true ) ) {
$value['fontWeight'] = '300';
}
// Text Transform.
if ( ! in_array( $value['textTransform'], [ 'none', 'uppercase', 'lowercase', 'capitalize' ], true ) ) {
$value['textTransform'] = 'none';
}
// Make sure we deal with arrays.
foreach ( [ 'letterSpacing', 'lineHeight', 'fontSize' ] as $value_type ) {
if ( ! is_array( $value[ $value_type ] ) ) {
$value[ $value_type ] = [];
}
}
return $value;
}
/**
* Sanitize alignment.
*
* @param array $input alignment responsive array.
*
* @return array
*/
function neve_sanitize_alignment( $input ) {
$default = [
'mobile' => 'left',
'tablet' => 'left',
'desktop' => 'left',
];
$allowed = [ 'left', 'center', 'right', 'justify' ];
if ( ! is_array( $input ) ) {
return $default;
}
foreach ( $input as $device => $alignment ) {
if ( ! in_array( $alignment, $allowed ) ) {
$input[ $device ] = 'left';
}
}
return $input;
}
/**
* Sanitize position.
*
* @param array $input alignment responsive array.
*
* @return array
*/
function neve_sanitize_position( $input ) {
$default = [
'mobile' => 'center',
'tablet' => 'center',
'desktop' => 'center',
];
$allowed = [ 'flex-start', 'center', 'flex-end' ];
if ( ! is_array( $input ) ) {
return $default;
}
foreach ( $input as $device => $alignment ) {
if ( ! in_array( $alignment, $allowed ) ) {
$input[ $device ] = 'center';
}
}
return $input;
}
/**
* Sanitize meta order control.
*/
function neve_sanitize_meta_ordering( $value ) {
$allowed = array(
'author',
'category',
'date',
'comments',
'reading',
);
if ( empty( $value ) ) {
return $allowed;
}
$decoded = json_decode( $value, true );
foreach ( $decoded as $val ) {
if ( ! in_array( $val, $allowed, true ) ) {
return $allowed;
}
}
return $value;
}
/**
* Sanitize blend mode option.
*
* @param string $input Control input.
*
* @return string
*/
function neve_sanitize_blend_mode( $input ) {
$blend_mode_options = [ 'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'saturation', 'color', 'difference', 'exclusion', 'hue', 'luminosity' ];
if ( ! in_array( $input, $blend_mode_options, true ) ) {
return 'normal';
}
return $input;
}
/**
* Sanitize the container layout value
*
* @param string $value value from the control.
*
* @return string
*/
function neve_sanitize_container_layout( $value ) {
$allowed_values = array( 'contained', 'full-width' );
if ( ! in_array( $value, $allowed_values, true ) ) {
return 'contained';
}
return esc_html( $value );
}
/**
* Sanitize Button Type option.
*
* @param string $value the control value.
*
* @return string
*/
function neve_sanitize_button_type( $value ) {
if ( ! in_array( $value, [ 'primary', 'secondary' ], true ) ) {
return 'primary';
}
return $value;
}
| 1 | 21,917 | I think that the JSON encoding should be handled by the control itself, not the sanitization function. This should only confirm that the input is correct, not reformat it | Codeinwp-neve | php |
@@ -79,6 +79,12 @@ func (i *Inbound) SetRegistry(registry transport.Registry) {
i.registry = registry
}
+// Transports returns the inbound's HTTP transport.
+func (i *Inbound) Transports() []transport.Transport {
+ // TODO factor out transport and return it here.
+ return []transport.Transport{}
+}
+
// Start starts the inbound with a given service detail, opening a listening
// socket.
func (i *Inbound) Start() error { | 1 | // Copyright (c) 2016 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 http
import (
"net"
"net/http"
"go.uber.org/yarpc/internal/errors"
intnet "go.uber.org/yarpc/internal/net"
"go.uber.org/yarpc/transport"
"github.com/opentracing/opentracing-go"
)
// NewInbound builds a new HTTP inbound that listens on the given address.
func NewInbound(addr string) *Inbound {
return &Inbound{
addr: addr,
tracer: opentracing.GlobalTracer(),
}
}
// Inbound represents an HTTP Inbound. It is the same as the transport Inbound
// except it exposes the address on which the system is listening for
// connections.
type Inbound struct {
addr string
mux *http.ServeMux
muxPattern string
server *intnet.HTTPServer
registry transport.Registry
tracer opentracing.Tracer
}
// WithMux specifies the ServeMux that the HTTP server should use and the
// pattern under which the YARPC endpoint should be registered.
func (i *Inbound) WithMux(pattern string, mux *http.ServeMux) *Inbound {
i.mux = mux
i.muxPattern = pattern
return i
}
// WithTracer configures a tracer on this inbound.
func (i *Inbound) WithTracer(tracer opentracing.Tracer) *Inbound {
i.tracer = tracer
return i
}
// WithRegistry configures a registry to handle incoming requests,
// as a chained method for convenience.
func (i *Inbound) WithRegistry(registry transport.Registry) *Inbound {
i.registry = registry
return i
}
// SetRegistry configures a registry to handle incoming requests.
// This satisfies the transport.Inbound interface, and would be called
// by a dispatcher when it starts.
func (i *Inbound) SetRegistry(registry transport.Registry) {
i.registry = registry
}
// Start starts the inbound with a given service detail, opening a listening
// socket.
func (i *Inbound) Start() error {
if i.registry == nil {
return errors.NoRegistryError{}
}
var httpHandler http.Handler = handler{
registry: i.registry,
tracer: i.tracer,
}
if i.mux != nil {
i.mux.Handle(i.muxPattern, httpHandler)
httpHandler = i.mux
}
i.server = intnet.NewHTTPServer(&http.Server{
Addr: i.addr,
Handler: httpHandler,
})
if err := i.server.ListenAndServe(); err != nil {
return err
}
i.addr = i.server.Listener().Addr().String() // in case it changed
return nil
}
// Stop the inbound, closing the listening socket.
func (i *Inbound) Stop() error {
if i.server == nil {
return nil
}
return i.server.Stop()
}
// Addr returns the address on which the server is listening. Returns nil if
// Start has not been called yet.
func (i *Inbound) Addr() net.Addr {
if i.server == nil {
return nil
}
listener := i.server.Listener()
if listener == nil {
return nil
}
return listener.Addr()
}
| 1 | 11,567 | Should we put a TODO here to route the http.Transport through here? | yarpc-yarpc-go | go |
@@ -177,7 +177,7 @@ func RemoveManagementInterface(networkName string) error {
var err error
var maxRetry = 3
var i = 0
- cmd := fmt.Sprintf("Get-VMSwitch -Name %s | Set-VMSwitch -AllowManagementOS $false ", networkName)
+ cmd := fmt.Sprintf("Get-VMSwitch -ComputerName $(hostname) -Name %s | Set-VMSwitch -ComputerName $(hostname) -AllowManagementOS $false ", networkName)
// Retry the operation here because an error is returned at the first invocation.
for i < maxRetry {
_, err = ps.RunCommand(cmd) | 1 | //go:build windows
// +build windows
//Copyright 2020 Antrea 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 util
import (
"bufio"
"encoding/json"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/Microsoft/go-winio"
"github.com/Microsoft/hcsshim"
"github.com/containernetworking/plugins/pkg/ip"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
ps "antrea.io/antrea/pkg/agent/util/powershell"
)
const (
ContainerVNICPrefix = "vEthernet"
HNSNetworkType = "Transparent"
LocalHNSNetwork = "antrea-hnsnetwork"
OVSExtensionID = "583CC151-73EC-4A6A-8B47-578297AD7623"
namedPipePrefix = `\\.\pipe\`
commandRetryTimeout = 5 * time.Second
commandRetryInterval = time.Second
MetricDefault = 256
MetricHigh = 50
)
type Route struct {
LinkIndex int
DestinationSubnet *net.IPNet
GatewayAddress net.IP
RouteMetric int
}
func (r Route) String() string {
return fmt.Sprintf("LinkIndex: %d, DestinationSubnet: %s, GatewayAddress: %s, RouteMetric: %d",
r.LinkIndex, r.DestinationSubnet, r.GatewayAddress, r.RouteMetric)
}
type Neighbor struct {
LinkIndex int
IPAddress net.IP
LinkLayerAddress net.HardwareAddr
State string
}
func (n Neighbor) String() string {
return fmt.Sprintf("LinkIndex: %d, IPAddress: %s, LinkLayerAddress: %s", n.LinkIndex, n.IPAddress, n.LinkLayerAddress)
}
func GetNSPath(containerNetNS string) (string, error) {
return containerNetNS, nil
}
// IsVirtualAdapter checks if the provided adapter is virtual.
func IsVirtualAdapter(name string) (bool, error) {
cmd := fmt.Sprintf(`Get-NetAdapter -InterfaceAlias "%s" | Select-Object -Property Virtual | Format-Table -HideTableHeaders`, name)
out, err := ps.RunCommand(cmd)
if err != nil {
return false, err
}
isVirtual, err := strconv.ParseBool(strings.TrimSpace(out))
if err != nil {
return false, err
}
return isVirtual, nil
}
func GetHostInterfaceStatus(ifaceName string) (string, error) {
cmd := fmt.Sprintf(`Get-NetAdapter -InterfaceAlias "%s" | Select-Object -Property Status | Format-Table -HideTableHeaders`, ifaceName)
out, err := ps.RunCommand(cmd)
if err != nil {
return "", err
}
return strings.TrimSpace(out), nil
}
// EnableHostInterface sets the specified interface status as UP.
func EnableHostInterface(ifaceName string) error {
cmd := fmt.Sprintf(`Enable-NetAdapter -InterfaceAlias "%s"`, ifaceName)
// Enable-NetAdapter is not a blocking operation based on our testing.
// It returns immediately no matter whether the interface has been enabled or not.
// So we need to check the interface status to ensure it is up before returning.
if err := wait.PollImmediate(commandRetryInterval, commandRetryTimeout, func() (done bool, err error) {
if _, err := ps.RunCommand(cmd); err != nil {
klog.Errorf("Failed to run command %s: %v", cmd, err)
return false, nil
}
status, err := GetHostInterfaceStatus(ifaceName)
if err != nil {
klog.Errorf("Failed to run command %s: %v", cmd, err)
return false, nil
}
if !strings.EqualFold(status, "Up") {
klog.Infof("Waiting for host interface %s to be up", ifaceName)
return false, nil
}
return true, nil
}); err != nil {
return fmt.Errorf("failed to enable interface %s: %v", ifaceName, err)
}
return nil
}
// ConfigureInterfaceAddress adds IPAddress on the specified interface.
func ConfigureInterfaceAddress(ifaceName string, ipConfig *net.IPNet) error {
ipStr := strings.Split(ipConfig.String(), "/")
cmd := fmt.Sprintf(`New-NetIPAddress -InterfaceAlias "%s" -IPAddress %s -PrefixLength %s`, ifaceName, ipStr[0], ipStr[1])
_, err := ps.RunCommand(cmd)
// If the address already exists, ignore the error.
if err != nil && !strings.Contains(err.Error(), "already exists") {
return err
}
return nil
}
// RemoveInterfaceAddress removes IPAddress from the specified interface.
func RemoveInterfaceAddress(ifaceName string, ipAddr net.IP) error {
cmd := fmt.Sprintf(`Remove-NetIPAddress -InterfaceAlias "%s" -IPAddress %s -Confirm:$false`, ifaceName, ipAddr.String())
_, err := ps.RunCommand(cmd)
// If the address does not exist, ignore the error.
if err != nil && !strings.Contains(err.Error(), "No matching") {
return err
}
return nil
}
// ConfigureInterfaceAddressWithDefaultGateway adds IPAddress on the specified interface and sets the default gateway
// for the host.
func ConfigureInterfaceAddressWithDefaultGateway(ifaceName string, ipConfig *net.IPNet, gateway string) error {
ipStr := strings.Split(ipConfig.String(), "/")
cmd := fmt.Sprintf(`New-NetIPAddress -InterfaceAlias "%s" -IPAddress %s -PrefixLength %s`, ifaceName, ipStr[0], ipStr[1])
if gateway != "" {
cmd = fmt.Sprintf("%s -DefaultGateway %s", cmd, gateway)
}
_, err := ps.RunCommand(cmd)
// If the address already exists, ignore the error.
if err != nil && !strings.Contains(err.Error(), "already exists") {
return err
}
return nil
}
// EnableIPForwarding enables the IP interface to forward packets that arrive on this interface to other interfaces.
func EnableIPForwarding(ifaceName string) error {
cmd := fmt.Sprintf(`Set-NetIPInterface -InterfaceAlias "%s" -Forwarding Enabled`, ifaceName)
_, err := ps.RunCommand(cmd)
return err
}
// RemoveManagementInterface removes the management interface of the HNS Network, and then the physical interface can be
// added to the OVS bridge. This function is called only if Hyper-V feature is installed on the host.
func RemoveManagementInterface(networkName string) error {
var err error
var maxRetry = 3
var i = 0
cmd := fmt.Sprintf("Get-VMSwitch -Name %s | Set-VMSwitch -AllowManagementOS $false ", networkName)
// Retry the operation here because an error is returned at the first invocation.
for i < maxRetry {
_, err = ps.RunCommand(cmd)
if err == nil {
return nil
}
i++
}
return err
}
// ConfigureMACAddress set specified MAC address on interface.
func SetAdapterMACAddress(adapterName string, macConfig *net.HardwareAddr) error {
macAddr := strings.Replace(macConfig.String(), ":", "", -1)
cmd := fmt.Sprintf("Set-NetAdapterAdvancedProperty -Name %s -RegistryKeyword NetworkAddress -RegistryValue %s",
adapterName, macAddr)
_, err := ps.RunCommand(cmd)
return err
}
// WindowsHyperVEnabled checks if the Hyper-V is enabled on the host.
// Hyper-V feature contains multiple components/sub-features. According to the
// test, OVS requires "Microsoft-Hyper-V" feature to be enabled.
func WindowsHyperVEnabled() (bool, error) {
cmd := "$(Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V).State"
result, err := ps.RunCommand(cmd)
if err != nil {
return true, err
}
return strings.HasPrefix(result, "Enabled"), nil
}
// CreateHNSNetwork creates a new HNS Network, whose type is "Transparent". The NetworkAdapter is using the host
// interface which is configured with Node IP. HNS Network properties "ManagementIP" and "SourceMac" are used to record
// the original IP and MAC addresses on the network adapter.
func CreateHNSNetwork(hnsNetName string, subnetCIDR *net.IPNet, nodeIP *net.IPNet, adapter *net.Interface) (*hcsshim.HNSNetwork, error) {
adapterMAC := adapter.HardwareAddr
adapterName := adapter.Name
gateway := ip.NextIP(subnetCIDR.IP.Mask(subnetCIDR.Mask))
network := &hcsshim.HNSNetwork{
Name: hnsNetName,
Type: HNSNetworkType,
NetworkAdapterName: adapterName,
Subnets: []hcsshim.Subnet{
{
AddressPrefix: subnetCIDR.String(),
GatewayAddress: gateway.String(),
},
},
ManagementIP: nodeIP.String(),
SourceMac: adapterMAC.String(),
}
hnsNet, err := network.Create()
if err != nil {
return nil, err
}
return hnsNet, nil
}
func DeleteHNSNetwork(hnsNetName string) error {
hnsNet, err := hcsshim.GetHNSNetworkByName(hnsNetName)
if err != nil {
if _, ok := err.(hcsshim.NetworkNotFoundError); !ok {
return nil
}
return err
}
_, err = hnsNet.Delete()
return err
}
type vSwitchExtensionPolicy struct {
ExtensionID string `json:"Id,omitempty"`
IsEnabled bool
}
type ExtensionsPolicy struct {
Extensions []vSwitchExtensionPolicy `json:"Extensions"`
}
// EnableHNSNetworkExtension enables the specified vSwitchExtension on the target HNS Network. Antrea calls this function
// to enable OVS Extension on the HNS Network.
func EnableHNSNetworkExtension(hnsNetID string, vSwitchExtension string) error {
extensionPolicy := vSwitchExtensionPolicy{
ExtensionID: vSwitchExtension,
IsEnabled: true,
}
jsonString, _ := json.Marshal(
ExtensionsPolicy{
Extensions: []vSwitchExtensionPolicy{extensionPolicy},
})
_, err := hcsshim.HNSNetworkRequest("POST", hnsNetID, string(jsonString))
if err != nil {
return err
}
return nil
}
func SetLinkUp(name string) (net.HardwareAddr, int, error) {
// Set host gateway interface up.
if err := EnableHostInterface(name); err != nil {
klog.Errorf("Failed to set host link for %s up: %v", name, err)
if strings.Contains(err.Error(), "ObjectNotFound") {
return nil, 0, newLinkNotFoundError(name)
}
return nil, 0, err
}
iface, err := net.InterfaceByName(name)
if err != nil {
if opErr, ok := err.(*net.OpError); ok && opErr.Err.Error() == "no such network interface" {
return nil, 0, newLinkNotFoundError(name)
}
return nil, 0, err
}
mac := iface.HardwareAddr
index := iface.Index
return mac, index, nil
}
func addrEqual(addr1, addr2 *net.IPNet) bool {
size1, _ := addr1.Mask.Size()
size2, _ := addr2.Mask.Size()
return addr1.IP.Equal(addr2.IP) && size1 == size2
}
func addrSliceDifference(s1, s2 []*net.IPNet) []*net.IPNet {
var diff []*net.IPNet
for _, e1 := range s1 {
found := false
for _, e2 := range s2 {
if addrEqual(e1, e2) {
found = true
break
}
}
if !found {
diff = append(diff, e1)
}
}
return diff
}
// ConfigureLinkAddresses adds the provided addresses to the interface identified by index idx, if
// they are missing from the interface. Any other existing address already configured for the
// interface will be removed, unless it is a link-local address. At the moment, this function only
// supports IPv4 addresses and will ignore any address in ipNets that is not IPv4.
func ConfigureLinkAddresses(idx int, ipNets []*net.IPNet) error {
iface, _ := net.InterfaceByIndex(idx)
ifaceName := iface.Name
var addrs []*net.IPNet
ifaceAddrs, err := iface.Addrs()
if err != nil {
return fmt.Errorf("failed to query IPv4 address list for interface %s: %v", ifaceName, err)
}
for _, addr := range ifaceAddrs {
if ipNet, ok := addr.(*net.IPNet); ok {
if ipNet.IP.To4() != nil && !ipNet.IP.IsLinkLocalUnicast() {
addrs = append(addrs, ipNet)
}
}
}
addrsToAdd := addrSliceDifference(ipNets, addrs)
addrsToRemove := addrSliceDifference(addrs, ipNets)
if len(addrsToAdd) == 0 && len(addrsToRemove) == 0 {
klog.V(2).Infof("IP configuration for interface %s does not need to change", ifaceName)
return nil
}
for _, addr := range addrsToRemove {
klog.V(2).Infof("Removing address %v from interface %s", addr, ifaceName)
if err := RemoveInterfaceAddress(ifaceName, addr.IP); err != nil {
return fmt.Errorf("failed to remove address %v from interface %s: %v", addr, ifaceName, err)
}
}
for _, addr := range addrsToAdd {
klog.V(2).Infof("Adding address %v to interface %s", addr, ifaceName)
if addr.IP.To4() == nil {
klog.Warningf("Windows only supports IPv4 addresses, skipping this address %v", addr)
return nil
}
if err := ConfigureInterfaceAddress(ifaceName, addr); err != nil {
return fmt.Errorf("failed to add address %v to interface %s: %v", addr, ifaceName, err)
}
}
return nil
}
// PrepareHNSNetwork creates HNS Network for containers.
func PrepareHNSNetwork(subnetCIDR *net.IPNet, nodeIPNet *net.IPNet, uplinkAdapter *net.Interface) error {
klog.InfoS("Creating HNSNetwork", "name", LocalHNSNetwork, "subnet", subnetCIDR, "nodeIP", nodeIPNet, "adapter", uplinkAdapter)
hnsNet, err := CreateHNSNetwork(LocalHNSNetwork, subnetCIDR, nodeIPNet, uplinkAdapter)
if err != nil {
return fmt.Errorf("error creating HNSNetwork: %v", err)
}
// Enable OVS Extension on the HNS Network. If an error occurs, delete the HNS Network and return the error.
if err = enableHNSOnOVS(hnsNet); err != nil {
hnsNet.Delete()
return err
}
if err = EnableRSCOnVSwitch(LocalHNSNetwork); err != nil {
return err
}
klog.Infof("Created HNSNetwork with name %s id %s", hnsNet.Name, hnsNet.Id)
return nil
}
// EnableRSCOnVSwitch enables RSC in the vSwitch to reduce host CPU utilization and increase throughput for virtual
// workloads by coalescing multiple TCP segments into fewer, but larger segments.
func EnableRSCOnVSwitch(vSwitch string) error {
cmd := fmt.Sprintf("Get-VMSwitch -Name %s | Select-Object -Property SoftwareRscEnabled | Format-Table -HideTableHeaders", vSwitch)
stdout, err := ps.RunCommand(cmd)
if err != nil {
return err
}
stdout = strings.TrimSpace(stdout)
// RSC doc says it applies to Windows Server 2019, which is the only Windows operating system supported so far, so
// this should not happen. However, this is only an optimization, no need to crash the process even if it's not
// supported.
// https://docs.microsoft.com/en-us/windows-server/networking/technologies/hpn/rsc-in-the-vswitch
if len(stdout) == 0 {
klog.Warning("Receive Segment Coalescing (RSC) is not supported by this Windows Server version")
return nil
}
if strings.EqualFold(stdout, "True") {
klog.Infof("Receive Segment Coalescing (RSC) for vSwitch %s is already enabled", vSwitch)
return nil
}
cmd = fmt.Sprintf("Set-VMSwitch -Name %s -EnableSoftwareRsc $True", vSwitch)
_, err = ps.RunCommand(cmd)
if err != nil {
return err
}
klog.Infof("Enabled Receive Segment Coalescing (RSC) for vSwitch %s", vSwitch)
return nil
}
func enableHNSOnOVS(hnsNet *hcsshim.HNSNetwork) error {
// Release OS management for HNS Network if Hyper-V is enabled.
hypervEnabled, err := WindowsHyperVEnabled()
if err != nil {
return err
}
if hypervEnabled {
if err := RemoveManagementInterface(LocalHNSNetwork); err != nil {
klog.Errorf("Failed to remove the interface managed by OS for HNSNetwork %s", LocalHNSNetwork)
return err
}
}
// Enable the HNS Network with OVS extension.
if err := EnableHNSNetworkExtension(hnsNet.Id, OVSExtensionID); err != nil {
return err
}
return err
}
// GetDefaultGatewayByInterfaceIndex returns the default gateway configured on the specified interface.
func GetDefaultGatewayByInterfaceIndex(ifIndex int) (string, error) {
cmd := fmt.Sprintf("$(Get-NetRoute -InterfaceIndex %d -DestinationPrefix 0.0.0.0/0 ).NextHop", ifIndex)
defaultGW, err := ps.RunCommand(cmd)
if err != nil {
return "", err
}
defaultGW = strings.ReplaceAll(defaultGW, "\r\n", "")
return defaultGW, nil
}
// GetDNServersByInterfaceIndex returns the DNS servers configured on the specified interface.
func GetDNServersByInterfaceIndex(ifIndex int) (string, error) {
cmd := fmt.Sprintf("$(Get-DnsClientServerAddress -InterfaceIndex %d -AddressFamily IPv4).ServerAddresses", ifIndex)
dnsServers, err := ps.RunCommand(cmd)
if err != nil {
return "", err
}
dnsServers = strings.ReplaceAll(dnsServers, "\r\n", ",")
dnsServers = strings.TrimRight(dnsServers, ",")
return dnsServers, nil
}
// SetAdapterDNSServers configures DNSServers on network adapter.
func SetAdapterDNSServers(adapterName, dnsServers string) error {
cmd := fmt.Sprintf("Set-DnsClientServerAddress -InterfaceAlias %s -ServerAddresses %s", adapterName, dnsServers)
if _, err := ps.RunCommand(cmd); err != nil {
return err
}
return nil
}
// ListenLocalSocket creates a listener on a Unix domain socket or a Windows named pipe.
// - If the specified address starts with "\\.\pipe\", create a listener on the a Windows named pipe path.
// - Else create a listener on a local Unix domain socket.
func ListenLocalSocket(address string) (net.Listener, error) {
if strings.HasPrefix(address, namedPipePrefix) {
return winio.ListenPipe(address, nil)
}
return listenUnix(address)
}
// DialLocalSocket connects to a Unix domain socket or a Windows named pipe.
// - If the specified address starts with "\\.\pipe\", connect to a Windows named pipe path.
// - Else connect to a Unix domain socket.
func DialLocalSocket(address string) (net.Conn, error) {
if strings.HasPrefix(address, namedPipePrefix) {
return winio.DialPipe(address, nil)
}
return dialUnix(address)
}
func HostInterfaceExists(ifaceName string) bool {
if _, err := net.InterfaceByName(ifaceName); err == nil {
return true
}
// Some kinds of interfaces cannot be retrieved by "net.InterfaceByName" such as
// container vnic.
// So if a interface cannot be found by above function, use powershell command
// "Get-NetAdapter" to check if it exists.
cmd := fmt.Sprintf(`Get-NetAdapter -InterfaceAlias "%s"`, ifaceName)
if _, err := ps.RunCommand(cmd); err != nil {
return false
}
return true
}
// SetInterfaceMTU configures interface MTU on host for Pods. MTU change cannot be realized with HNSEndpoint because
// there's no MTU field in HNSEndpoint:
// https://github.com/Microsoft/hcsshim/blob/4a468a6f7ae547974bc32911395c51fb1862b7df/internal/hns/hnsendpoint.go#L12
func SetInterfaceMTU(ifaceName string, mtu int) error {
cmd := fmt.Sprintf("Set-NetIPInterface -IncludeAllCompartments -InterfaceAlias \"%s\" -NlMtuBytes %d",
ifaceName, mtu)
_, err := ps.RunCommand(cmd)
return err
}
func NewNetRoute(route *Route) error {
cmd := fmt.Sprintf("New-NetRoute -InterfaceIndex %v -DestinationPrefix %v -NextHop %v -RouteMetric %d -Verbose",
route.LinkIndex, route.DestinationSubnet.String(), route.GatewayAddress.String(), route.RouteMetric)
_, err := ps.RunCommand(cmd)
return err
}
func RemoveNetRoute(route *Route) error {
cmd := fmt.Sprintf("Remove-NetRoute -InterfaceIndex %v -DestinationPrefix %v -Verbose -Confirm:$false",
route.LinkIndex, route.DestinationSubnet.String())
_, err := ps.RunCommand(cmd)
return err
}
func ReplaceNetRoute(route *Route) error {
rs, err := GetNetRoutes(route.LinkIndex, route.DestinationSubnet)
if err != nil {
return err
}
if len(rs) == 0 {
if err := NewNetRoute(route); err != nil {
return err
}
return nil
}
found := false
for _, r := range rs {
if r.GatewayAddress.Equal(route.GatewayAddress) {
found = true
break
}
}
if found {
return nil
}
if err := RemoveNetRoute(route); err != nil {
return err
}
if err := NewNetRoute(route); err != nil {
return err
}
return nil
}
func GetNetRoutes(linkIndex int, dstSubnet *net.IPNet) ([]Route, error) {
cmd := fmt.Sprintf("Get-NetRoute -InterfaceIndex %d -DestinationPrefix %s -ErrorAction Ignore | Format-Table -HideTableHeaders",
linkIndex, dstSubnet.String())
return getNetRoutes(cmd)
}
func GetNetRoutesAll() ([]Route, error) {
cmd := "Get-NetRoute -ErrorAction Ignore | Format-Table -HideTableHeaders"
return getNetRoutes(cmd)
}
func getNetRoutes(cmd string) ([]Route, error) {
routesStr, _ := ps.RunCommand(cmd)
parsed := parseGetNetCmdResult(routesStr, 6)
var routes []Route
for _, items := range parsed {
idx, err := strconv.Atoi(items[0])
if err != nil {
return nil, fmt.Errorf("failed to parse the LinkIndex '%s': %v", items[0], err)
}
_, dstSubnet, err := net.ParseCIDR(items[1])
if err != nil {
return nil, fmt.Errorf("failed to parse the DestinationSubnet '%s': %v", items[1], err)
}
gw := net.ParseIP(items[2])
metric, err := strconv.Atoi(items[3])
if err != nil {
return nil, fmt.Errorf("failed to parse the RouteMetric '%s': %v", items[3], err)
}
route := Route{
LinkIndex: idx,
DestinationSubnet: dstSubnet,
GatewayAddress: gw,
RouteMetric: metric,
}
routes = append(routes, route)
}
return routes, nil
}
func parseGetNetCmdResult(result string, itemNum int) [][]string {
scanner := bufio.NewScanner(strings.NewReader(result))
parsed := [][]string{}
for scanner.Scan() {
items := strings.Fields(scanner.Text())
if len(items) < itemNum {
// Skip if an empty line or something similar
continue
}
parsed = append(parsed, items)
}
return parsed
}
func NewNetNat(netNatName string, subnetCIDR *net.IPNet) error {
cmd := fmt.Sprintf(`Get-NetNat -Name %s | Select-Object InternalIPInterfaceAddressPrefix | Format-Table -HideTableHeaders`, netNatName)
if internalNet, err := ps.RunCommand(cmd); err != nil {
if !strings.Contains(err.Error(), "No MSFT_NetNat objects found") {
klog.ErrorS(err, "Failed to check the existing netnat", "name", netNatName)
return err
}
} else {
if strings.Contains(internalNet, subnetCIDR.String()) {
return nil
}
klog.InfoS("Removing the existing netnat", "name", netNatName, "internalIPInterfaceAddressPrefix", internalNet)
cmd = fmt.Sprintf("Remove-NetNat -Name %s -Confirm:$false", netNatName)
if _, err := ps.RunCommand(cmd); err != nil {
klog.ErrorS(err, "Failed to remove the existing netnat", "name", netNatName, "internalIPInterfaceAddressPrefix", internalNet)
return err
}
}
cmd = fmt.Sprintf(`New-NetNat -Name %s -InternalIPInterfaceAddressPrefix %s`, netNatName, subnetCIDR.String())
_, err := ps.RunCommand(cmd)
if err != nil {
klog.ErrorS(err, "Failed to add netnat", "name", netNatName, "internalIPInterfaceAddressPrefix", subnetCIDR.String())
return err
}
return nil
}
func ReplaceNetNatStaticMapping(netNatName string, externalIPAddr string, externalPort uint16, internalIPAddr string, internalPort uint16, proto string) error {
staticMappingStr, err := GetNetNatStaticMapping(netNatName, externalIPAddr, externalPort, proto)
if err != nil {
return err
}
parsed := parseGetNetCmdResult(staticMappingStr, 6)
if len(parsed) > 0 {
items := parsed[0]
if items[4] == internalIPAddr && items[5] == strconv.Itoa(int(internalPort)) {
return nil
}
firstCol := strings.Split(items[0], ";")
id, err := strconv.Atoi(firstCol[1])
if err != nil {
return err
}
if err := RemoveNetNatStaticMappingByID(netNatName, id); err != nil {
return err
}
}
return AddNetNatStaticMapping(netNatName, externalIPAddr, externalPort, internalIPAddr, internalPort, proto)
}
// GetNetNatStaticMapping checks if a NetNatStaticMapping exists.
func GetNetNatStaticMapping(netNatName string, externalIPAddr string, externalPort uint16, proto string) (string, error) {
cmd := fmt.Sprintf("Get-NetNatStaticMapping -NatName %s", netNatName) +
fmt.Sprintf("|? ExternalIPAddress -EQ %s", externalIPAddr) +
fmt.Sprintf("|? ExternalPort -EQ %d", externalPort) +
fmt.Sprintf("|? Protocol -EQ %s", proto) +
"| Format-Table -HideTableHeaders"
staticMappingStr, err := ps.RunCommand(cmd)
if err != nil && !strings.Contains(err.Error(), "No MSFT_NetNatStaticMapping objects found") {
return "", err
}
return staticMappingStr, nil
}
// AddNetNatStaticMapping adds a static mapping to a NAT instance.
func AddNetNatStaticMapping(netNatName string, externalIPAddr string, externalPort uint16, internalIPAddr string, internalPort uint16, proto string) error {
cmd := fmt.Sprintf("Add-NetNatStaticMapping -NatName %s -ExternalIPAddress %s -ExternalPort %d -InternalIPAddress %s -InternalPort %d -Protocol %s",
netNatName, externalIPAddr, externalPort, internalIPAddr, internalPort, proto)
_, err := ps.RunCommand(cmd)
return err
}
func RemoveNetNatStaticMapping(netNatName string, externalIPAddr string, externalPort uint16, proto string) error {
staticMappingStr, err := GetNetNatStaticMapping(netNatName, externalIPAddr, externalPort, proto)
if err != nil {
return err
}
parsed := parseGetNetCmdResult(staticMappingStr, 6)
if len(parsed) == 0 {
return nil
}
firstCol := strings.Split(parsed[0][0], ";")
id, err := strconv.Atoi(firstCol[1])
if err != nil {
return err
}
return RemoveNetNatStaticMappingByID(netNatName, id)
}
func RemoveNetNatStaticMappingByID(netNatName string, id int) error {
cmd := fmt.Sprintf("Remove-NetNatStaticMapping -NatName %s -StaticMappingID %d -Confirm:$false", netNatName, id)
_, err := ps.RunCommand(cmd)
return err
}
// GetNetNeighbor gets neighbor cache entries with Get-NetNeighbor.
func GetNetNeighbor(neighbor *Neighbor) ([]Neighbor, error) {
cmd := fmt.Sprintf("Get-NetNeighbor -InterfaceIndex %d -IPAddress %s | Format-Table -HideTableHeaders", neighbor.LinkIndex, neighbor.IPAddress.String())
neighborsStr, err := ps.RunCommand(cmd)
if err != nil && !strings.Contains(err.Error(), "No matching MSFT_NetNeighbor objects") {
return nil, err
}
parsed := parseGetNetCmdResult(neighborsStr, 5)
var neighbors []Neighbor
for _, items := range parsed {
idx, err := strconv.Atoi(items[0])
if err != nil {
return nil, fmt.Errorf("failed to parse the LinkIndex '%s': %v", items[0], err)
}
dstIP := net.ParseIP(items[1])
if err != nil {
return nil, fmt.Errorf("failed to parse the DestinationIP '%s': %v", items[1], err)
}
// Get-NetRoute returns LinkLayerAddress like "AA-BB-CC-DD-EE-FF".
mac, err := net.ParseMAC(strings.ReplaceAll(items[2], "-", ":"))
if err != nil {
return nil, fmt.Errorf("failed to parse the Gateway MAC '%s': %v", items[2], err)
}
neighbor := Neighbor{
LinkIndex: idx,
IPAddress: dstIP,
LinkLayerAddress: mac,
State: items[3],
}
neighbors = append(neighbors, neighbor)
}
return neighbors, nil
}
// NewNetNeighbor creates a new neighbor cache entry with New-NetNeighbor.
func NewNetNeighbor(neighbor *Neighbor) error {
cmd := fmt.Sprintf("New-NetNeighbor -InterfaceIndex %d -IPAddress %s -LinkLayerAddress %s -State Permanent",
neighbor.LinkIndex, neighbor.IPAddress, neighbor.LinkLayerAddress)
_, err := ps.RunCommand(cmd)
return err
}
func RemoveNetNeighbor(neighbor *Neighbor) error {
cmd := fmt.Sprintf("Remove-NetNeighbor -InterfaceIndex %d -IPAddress %s -Confirm:$false",
neighbor.LinkIndex, neighbor.IPAddress)
_, err := ps.RunCommand(cmd)
return err
}
func ReplaceNetNeighbor(neighbor *Neighbor) error {
neighbors, err := GetNetNeighbor(neighbor)
if err != nil {
return err
}
if len(neighbors) == 0 {
if err := NewNetNeighbor(neighbor); err != nil {
return err
}
return nil
}
for _, n := range neighbors {
if n.LinkLayerAddress.String() == neighbor.LinkLayerAddress.String() && n.State == neighbor.State {
return nil
}
}
if err := RemoveNetNeighbor(neighbor); err != nil {
return err
}
return NewNetNeighbor(neighbor)
}
| 1 | 50,548 | Sorry, could you explain more about the issue? Doesn't ComputerName already default to local computer? > -ComputerName Specifies one or more Hyper-V hosts on which the virtual switch is to be configured. NetBIOS names, IP addresses, and fully qualified domain names are allowable. The default is the local computer. Use localhost or a dot (.) to specify the local computer explicitly. | antrea-io-antrea | go |
@@ -131,9 +131,13 @@ func runCliTool(logger *log.Logger, testCase *junitxml.TestCase, cmdString strin
}
// RunTestCommand runs given test command
-func RunTestCommand(cmd string, args []string, logger *log.Logger, testCase *junitxml.TestCase) bool {
+func RunTestCommand(cmd string, args []string, logger *log.Logger, testCase *junitxml.TestCase, allowError bool) bool {
if err := runCliTool(logger, testCase, cmd, args); err != nil {
- Failure(testCase, logger, fmt.Sprintf("Error running cmd: %v\n", err))
+ if allowError {
+ logger.Printf("[%v] %v", testCase.Name, fmt.Sprintf("Error running cmd: %v\n", err))
+ } else {
+ Failure(testCase, logger, fmt.Sprintf("Error running cmd: %v\n", err))
+ }
return false
}
return true | 1 | // Copyright 2020 Google 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 utils contains e2e tests utils for cli tools e2e tests
package utils
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"regexp"
"sort"
"strings"
"sync"
"github.com/GoogleCloudPlatform/compute-image-tools/go/e2e_test_utils/junitxml"
"github.com/GoogleCloudPlatform/compute-image-tools/go/e2e_test_utils/test_config"
)
// CLITestType defines which type of test is going to be executed
type CLITestType string
// List all test types here
const (
Wrapper CLITestType = "1 wrapper"
GcloudProdWrapperLatest CLITestType = "2 gcloud-prod wrapper-latest"
GcloudLatestWrapperLatest CLITestType = "3 gcloud-latest wrapper-latest"
)
var (
gcloudUpdateLock = sync.Mutex{}
)
// CLITestSuite executes given test suite.
func CLITestSuite(ctx context.Context, tswg *sync.WaitGroup, testSuites chan *junitxml.TestSuite,
logger *log.Logger, testSuiteRegex, testCaseRegex *regexp.Regexp,
testProjectConfig *testconfig.Project, testSuiteName string, testsMap map[CLITestType]map[*junitxml.TestCase]func(
context.Context, *junitxml.TestCase, *log.Logger, *testconfig.Project, CLITestType)) {
defer tswg.Done()
if testSuiteRegex != nil && !testSuiteRegex.MatchString(testSuiteName) {
return
}
testSuite := junitxml.NewTestSuite(testSuiteName)
defer testSuite.Finish(testSuites)
logger.Printf("Running CLITestSuite %q", testSuite.Name)
tests := runTestCases(ctx, logger, testCaseRegex, testProjectConfig, testSuite.Name, testsMap)
for ret := range tests {
testSuite.TestCase = append(testSuite.TestCase, ret)
}
logger.Printf("Finished CLITestSuite %q", testSuite.Name)
}
func runTestCases(ctx context.Context, logger *log.Logger, regex *regexp.Regexp,
testProjectConfig *testconfig.Project, testSuiteName string, testsMap map[CLITestType]map[*junitxml.TestCase]func(
context.Context, *junitxml.TestCase, *log.Logger, *testconfig.Project, CLITestType)) chan *junitxml.TestCase {
tests := make(chan *junitxml.TestCase)
var ttwg sync.WaitGroup
ttwg.Add(len(testsMap))
tts := make([]string, 0, len(testsMap))
for tt := range testsMap {
tts = append(tts, string(tt))
}
sort.Strings(tts)
go func() {
for _, ttStr := range tts {
tt := CLITestType(ttStr)
m := testsMap[tt]
logger.Printf("=== Running CLITestSuite %v for test type %v ===", testSuiteName, tt)
var wg sync.WaitGroup
for tc, f := range m {
wg.Add(1)
go func(ctx context.Context, wg *sync.WaitGroup, tc *junitxml.TestCase, tt CLITestType, f func(
context.Context, *junitxml.TestCase, *log.Logger, *testconfig.Project, CLITestType)) {
defer wg.Done()
if tc.FilterTestCase(regex) {
tc.Finish(tests)
} else {
defer tc.Finish(tests)
logger.Printf("Running TestCase %s.%q", tc.Classname, tc.Name)
f(ctx, tc, logger, testProjectConfig, tt)
logger.Printf("TestCase %s.%q finished in %fs", tc.Classname, tc.Name, tc.Time)
}
}(ctx, &wg, tc, tt, f)
}
wg.Wait()
ttwg.Done()
logger.Printf("=== Finished running CLITestSuite %v for test type %v ===", testSuiteName, tt)
}
}()
go func() {
ttwg.Wait()
close(tests)
}()
return tests
}
func runCliTool(logger *log.Logger, testCase *junitxml.TestCase, cmdString string, args []string) error {
prefix := "Test Env"
if testCase != nil {
prefix = testCase.Name
}
logger.Printf("[%v] Running command: '%s %s'", prefix, cmdString, strings.Join(args, " "))
cmd := exec.Command(cmdString, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// RunTestCommand runs given test command
func RunTestCommand(cmd string, args []string, logger *log.Logger, testCase *junitxml.TestCase) bool {
if err := runCliTool(logger, testCase, cmd, args); err != nil {
Failure(testCase, logger, fmt.Sprintf("Error running cmd: %v\n", err))
return false
}
return true
}
func runCliToolAsync(logger *log.Logger, testCase *junitxml.TestCase, cmdString string, args []string) (*exec.Cmd, error) {
logger.Printf("[%v] Running command: '%s %s'", testCase.Name, cmdString, strings.Join(args, " "))
cmd := exec.Command(cmdString, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
return cmd, err
}
// RunTestCommandAsync runs given test command asynchronously
func RunTestCommandAsync(cmd string, args []string, logger *log.Logger, testCase *junitxml.TestCase) *exec.Cmd {
cmdPtr, err := runCliToolAsync(logger, testCase, cmd, args)
if err != nil {
Failure(testCase, logger, fmt.Sprintf("Error starting cmd: %v\n", err))
return nil
}
return cmdPtr
}
// GcloudAuth runs "gcloud auth"
func GcloudAuth(logger *log.Logger, testCase *junitxml.TestCase) bool {
// This file exists in test env. For local testing, download a creds file from project
// compute-image-tools-test.
credsPath := "/etc/compute-image-tools-test-service-account/creds.json"
cmd := "gcloud"
args := []string{"auth", "activate-service-account", "--key-file=" + credsPath}
if err := runCliTool(logger, testCase, cmd, args); err != nil {
Failure(testCase, logger, fmt.Sprintf("Error running cmd: %v\n", err))
return false
}
return true
}
func gcloudUpdate(logger *log.Logger, testCase *junitxml.TestCase, latest bool) bool {
gcloudUpdateLock.Lock()
defer gcloudUpdateLock.Unlock()
// auth is required for gcloud updates
if !GcloudAuth(logger, testCase) {
return false
}
cmd := "gcloud"
if latest {
args := []string{"components", "repositories", "add",
"https://storage.googleapis.com/cloud-sdk-testing/ci/staging/components-2.json", "--quiet"}
if err := runCliTool(logger, testCase, cmd, args); err != nil {
logger.Printf("Error running cmd: %v\n", err)
testCase.WriteFailure("Error running cmd: %v", err)
return false
}
} else {
args := []string{"components", "repositories", "remove", "--all"}
if err := runCliTool(logger, testCase, cmd, args); err != nil {
logger.Printf("Error running cmd: %v\n", err)
testCase.WriteFailure("Error running cmd: %v", err)
return false
}
}
args := []string{"components", "update", "--quiet"}
if err := runCliTool(logger, testCase, cmd, args); err != nil {
logger.Printf("Error running cmd: %v\n", err)
testCase.WriteFailure("Error running cmd: %v", err)
return false
}
// an additional auth is required if updated through a different repository
if !GcloudAuth(logger, testCase) {
return false
}
return true
}
// RunTestForTestType runs test for given test type
func RunTestForTestType(cmd string, args []string, testType CLITestType, logger *log.Logger, testCase *junitxml.TestCase) bool {
switch testType {
case Wrapper:
if !RunTestCommand(cmd, args, logger, testCase) {
return false
}
case GcloudProdWrapperLatest:
if !gcloudUpdate(logger, testCase, false) {
return false
}
if !RunTestCommand(cmd, args, logger, testCase) {
return false
}
case GcloudLatestWrapperLatest:
if !gcloudUpdate(logger, testCase, true) {
return false
}
if !RunTestCommand(cmd, args, logger, testCase) {
return false
}
}
return true
}
// Failure logs failure message to both test case output and logger.
func Failure(testCase *junitxml.TestCase, logger *log.Logger, msg string) {
prefix := "Test Env"
if testCase != nil {
prefix = testCase.Name
testCase.WriteFailure(msg)
}
logger.Printf("[%v] %v", prefix, msg)
}
// ContainsSubString checks whether the string slice contains a substring anywhere.
func ContainsSubString(strs []string, s string) bool {
for _, str := range strs {
if strings.Contains(str, s) {
return true
}
}
return false
}
| 1 | 11,536 | `allowError` is a big vague. Does this mean the test case is asserting that an error should occur? If it means "maybe an error can occur, and that's okay" -- what's an example of this? | GoogleCloudPlatform-compute-image-tools | go |
@@ -29,7 +29,11 @@ var Xrc20Cmd = &cobra.Command{
var xrc20ContractAddress string
func xrc20Contract() (address.Address, error) {
- return alias.IOAddress(xrc20ContractAddress)
+ addr, err := alias.IOAddress(xrc20ContractAddress)
+ if err != nil {
+ return nil, output.NewError(output.FlagError, "invalid xrc20 address flag", err)
+ }
+ return addr, nil
}
type amountMessage struct { | 1 | // Copyright (c) 2019 IoTeX Foundation
// 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 action
import (
"encoding/hex"
"fmt"
"math/big"
"strconv"
"github.com/spf13/cobra"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-core/ioctl/cmd/alias"
"github.com/iotexproject/iotex-core/ioctl/cmd/config"
"github.com/iotexproject/iotex-core/ioctl/output"
)
//Xrc20Cmd represent erc20 standard command-line
var Xrc20Cmd = &cobra.Command{
Use: "xrc20",
Short: "Supporting ERC20 standard command-line from ioctl",
}
var xrc20ContractAddress string
func xrc20Contract() (address.Address, error) {
return alias.IOAddress(xrc20ContractAddress)
}
type amountMessage struct {
RawData string `json:"rawData"`
Decimal string `json:"decimal"`
}
func (m *amountMessage) String() string {
if output.Format == "" {
return fmt.Sprintf("Raw output: %s\nOutput in decimal: %s", m.RawData, m.Decimal)
}
return output.FormatString(output.Result, m)
}
func init() {
Xrc20Cmd.AddCommand(xrc20TotalSupplyCmd)
Xrc20Cmd.AddCommand(xrc20BalanceOfCmd)
Xrc20Cmd.AddCommand(xrc20TransferCmd)
Xrc20Cmd.AddCommand(xrc20TransferFromCmd)
Xrc20Cmd.AddCommand(xrc20ApproveCmd)
Xrc20Cmd.AddCommand(xrc20AllowanceCmd)
Xrc20Cmd.PersistentFlags().StringVarP(&xrc20ContractAddress, "contract-address", "c", "",
"set contract address")
Xrc20Cmd.PersistentFlags().StringVar(&config.ReadConfig.Endpoint, "endpoint",
config.ReadConfig.Endpoint, "set endpoint for once")
Xrc20Cmd.PersistentFlags().BoolVar(&config.Insecure, "insecure", config.Insecure,
"insecure connection for once (default false)")
cobra.MarkFlagRequired(Xrc20Cmd.PersistentFlags(), "contract-address")
}
func parseAmount(contract address.Address, amount string) (*big.Int, error) {
decimalBytecode, err := hex.DecodeString("313ce567")
if err != nil {
return nil, output.NewError(output.ConvertError, "failed to decode 313ce567", err)
}
result, err := Read(contract, decimalBytecode)
if err != nil {
return nil, output.NewError(0, "failed to read contract", err)
}
var decimal int64
if result != "" {
decimal, err = strconv.ParseInt(result, 16, 8)
if err != nil {
return nil, output.NewError(output.ConvertError, "failed to convert string into int64", err)
}
} else {
decimal = int64(0)
}
amountFloat, ok := (*big.Float).SetString(new(big.Float), amount)
if !ok {
return nil, output.NewError(output.ConvertError, "failed to convert string into bit float", err)
}
amountResultFloat := amountFloat.Mul(amountFloat, new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10),
big.NewInt(decimal), nil)))
if !amountResultFloat.IsInt() {
return nil, output.NewError(output.ValidationError, "unappropriated amount", nil)
}
var amountResultInt *big.Int
amountResultInt, _ = amountResultFloat.Int(amountResultInt)
return amountResultInt, nil
}
| 1 | 19,300 | return statements should not be cuddled if block has more than two lines (from `wsl`) | iotexproject-iotex-core | go |
@@ -10,11 +10,12 @@ import java.util.*;
import java.util.concurrent.TimeUnit;
import static java.lang.management.ManagementFactory.*;
+import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* A collection of Java Virtual Machine metrics.
*/
-public class VirtualMachineMetrics {
+public class VirtualMachineMetrics implements Metric {
public static class GarbageCollector {
private final long runs, timeMS;
| 1 | package com.yammer.metrics.core;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.Thread.State;
import java.lang.management.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static java.lang.management.ManagementFactory.*;
/**
* A collection of Java Virtual Machine metrics.
*/
public class VirtualMachineMetrics {
public static class GarbageCollector {
private final long runs, timeMS;
public GarbageCollector(long runs, long timeMS) {
this.runs = runs;
this.timeMS = timeMS;
}
public long getRuns() {
return runs;
}
public long getTime(TimeUnit unit) {
return unit.convert(timeMS, TimeUnit.MILLISECONDS);
}
}
private VirtualMachineMetrics() { /* unused */ }
/**
* Returns the percentage of the JVM's heap which is being used.
*
* @return the percentage of the JVM's heap which is being used
*/
public static double heapUsage() {
final MemoryUsage bean = getMemoryMXBean().getHeapMemoryUsage();
return bean.getUsed() / (double) bean.getMax();
}
/**
* Returns the percentage of the JVM's non-heap memory (e.g., direct buffers) which is being
* used.
*
* @return the percentage of the JVM's non-heap memory which is being used
*/
public static double nonHeapUsage() {
final MemoryUsage bean = getMemoryMXBean().getNonHeapMemoryUsage();
return bean.getUsed() / (double) bean.getMax();
}
/**
* Returns a map of memory pool names to the percentage of that pool which is being used.
*
* @return a map of memory pool names to the percentage of that pool which is being used
*/
public static Map<String, Double> memoryPoolUsage() {
final Map<String, Double> pools = new TreeMap<String, Double>();
for (MemoryPoolMXBean bean : getMemoryPoolMXBeans()) {
final double max = bean.getUsage().getMax() == -1 ?
bean.getUsage().getCommitted() :
bean.getUsage().getMax();
pools.put(bean.getName(), bean.getUsage().getUsed() / max);
}
return pools;
}
/**
* Returns the percentage of available file descriptors which are currently in use.
*
* @return the percentage of available file descriptors which are currently in use, or {@code
* NaN} if the running JVM does not have access to this information
*/
public static double fileDescriptorUsage() {
try {
final OperatingSystemMXBean bean = getOperatingSystemMXBean();
final Method getOpenFileDescriptorCount = bean.getClass()
.getDeclaredMethod(
"getOpenFileDescriptorCount");
getOpenFileDescriptorCount.setAccessible(true);
final Long openFds = (Long) getOpenFileDescriptorCount.invoke(bean);
final Method getMaxFileDescriptorCount = bean.getClass()
.getDeclaredMethod(
"getMaxFileDescriptorCount");
getMaxFileDescriptorCount.setAccessible(true);
final Long maxFds = (Long) getMaxFileDescriptorCount.invoke(bean);
return openFds.doubleValue() / maxFds.doubleValue();
} catch (Exception e) {
return Double.NaN;
}
}
/**
* Returns the version of the currently-running jvm.
*
* @return the version of the currently-running jvm, eg "1.6.0_24"
* @see <a href="http://java.sun.com/j2se/versioning_naming.html">J2SE SDK/JRE Version String
* Naming Convention</a>
*/
public static String vmVersion() {
return System.getProperty("java.runtime.version");
}
/**
* Returns the name of the currently-running jvm.
*
* @return the name of the currently-running jvm, eg "Java HotSpot(TM) Client VM"
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties()">System.getProperties()</a>
*/
public static String vmName() {
return System.getProperty("java.vm.name");
}
/**
* Returns the number of seconds the JVM process has been running.
*
* @return the number of seconds the JVM process has been running
*/
public static long uptime() {
return getRuntimeMXBean().getUptime() / 1000;
}
/**
* Returns the number of live threads (includes {@link #daemonThreadCount()}.
*
* @return the number of live threads
*/
public static long threadCount() {
return getThreadMXBean().getThreadCount();
}
/**
* Returns the number of live daemon threads.
*
* @return the number of live daemon threads
*/
public static long daemonThreadCount() {
return getThreadMXBean().getDaemonThreadCount();
}
/**
* Returns a map of garbage collector names to garbage collector information.
*
* @return a map of garbage collector names to garbage collector information
*/
public static Map<String, GarbageCollector> garbageCollectors() {
final Map<String, GarbageCollector> gcs = new HashMap<String, GarbageCollector>();
for (GarbageCollectorMXBean bean : getGarbageCollectorMXBeans()) {
gcs.put(bean.getName(),
new GarbageCollector(bean.getCollectionCount(), bean.getCollectionTime()));
}
return gcs;
}
/**
* Returns a set of strings describing deadlocked threads, if any are deadlocked.
*
* @return a set of any deadlocked threads
*/
public static Set<String> deadlockedThreads() {
final long[] threadIds = getThreadMXBean().findDeadlockedThreads();
if (threadIds != null) {
final Set<String> threads = new HashSet<String>();
final ThreadInfo[] infos = getThreadMXBean().getThreadInfo(threadIds, 100);
for (ThreadInfo info : infos) {
final StringBuilder stackTrace = new StringBuilder();
for (StackTraceElement element : info.getStackTrace()) {
stackTrace.append("\t at ").append(element.toString()).append('\n');
}
threads.add(
String.format(
"%s locked on %s (owned by %s):\n%s",
info.getThreadName(), info.getLockName(),
info.getLockOwnerName(),
stackTrace.toString()
)
);
}
return threads;
}
return Collections.emptySet();
}
/**
* Returns a map of thread states to the percentage of all threads which are in that state.
*
* @return a map of thread states to percentages
*/
public static Map<State, Double> threadStatePercentages() {
final Map<State, Double> conditions = new HashMap<State, Double>();
for (State state : State.values()) {
conditions.put(state, 0.0);
}
final long[] allThreadIds = getThreadMXBean().getAllThreadIds();
final ThreadInfo[] allThreads = getThreadMXBean().getThreadInfo(allThreadIds);
int liveCount = 0;
for (ThreadInfo info : allThreads) {
if (info != null) {
final State state = info.getThreadState();
conditions.put(state, conditions.get(state) + 1);
liveCount++;
}
}
for (State state : new ArrayList<State>(conditions.keySet())) {
conditions.put(state, conditions.get(state) / liveCount);
}
return conditions;
}
/**
* Dumps all of the threads' current information to an output stream.
*
* @param out an output stream
* @throws IOException if something goes wrong
*/
public static void threadDump(OutputStream out) throws IOException {
final ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
final PrintWriter writer = new PrintWriter(out, true);
for (int ti = threads.length - 1; ti > 0; ti--) {
final ThreadInfo t = threads[ti];
writer.printf("%s id=%d state=%s",
t.getThreadName(),
t.getThreadId(),
t.getThreadState());
final LockInfo lock = t.getLockInfo();
if (lock != null && t.getThreadState() != Thread.State.BLOCKED) {
writer.printf("\n - waiting on <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
writer.printf("\n - locked <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
} else if (lock != null && t.getThreadState() == Thread.State.BLOCKED) {
writer.printf("\n - waiting to lock <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
}
if (t.isSuspended()) {
writer.print(" (suspended)");
}
if (t.isInNative()) {
writer.print(" (running in native)");
}
writer.println();
if (t.getLockOwnerName() != null) {
writer.printf(" owned by %s id=%d\n", t.getLockOwnerName(), t.getLockOwnerId());
}
final StackTraceElement[] elements = t.getStackTrace();
final MonitorInfo[] monitors = t.getLockedMonitors();
for (int i = 0; i < elements.length; i++) {
final StackTraceElement element = elements[i];
writer.printf(" at %s\n", element);
for (int j = 1; j < monitors.length; j++) {
final MonitorInfo monitor = monitors[j];
if (monitor.getLockedStackDepth() == i) {
writer.printf(" - locked %s\n", monitor);
}
}
}
writer.println();
final LockInfo[] locks = t.getLockedSynchronizers();
if (locks.length > 0) {
writer.printf(" Locked synchronizers: count = %d\n", locks.length);
for (LockInfo l : locks) {
writer.printf(" - %s\n", l);
}
writer.println();
}
}
writer.println();
writer.flush();
}
}
| 1 | 5,406 | Why does VirtualMachineMetrics have to implement Metric? | dropwizard-metrics | java |
@@ -64,16 +64,12 @@ func TestSingleAccountManager_SignVote(t *testing.T) {
require.NoError(err)
voteeAddress, err := iotxaddress.GetAddressByPubkey(iotxaddress.IsTestnet, iotxaddress.ChainID, votePubKey)
require.NoError(err)
- rawVote, err := action.NewVote(uint64(1), voterAddress.RawAddress, voteeAddress.RawAddress, uint64(100000), big.NewInt(10))
+ vote, err := action.NewVote(uint64(1), voterAddress.RawAddress, voteeAddress.RawAddress, uint64(100000), big.NewInt(10))
require.NoError(err)
- signedVote, err := m.SignVote(rawVote)
- require.NoError(err)
- require.NotNil(signedVote)
+ require.NoError(m.SignVote(vote))
require.NoError(accountManager.Remove(rawAddr1))
- signedVote, err = m.SignVote(rawVote)
- require.Equal(ErrNumAccounts, errors.Cause(err))
- require.Nil(signedVote)
+ require.Equal(ErrNumAccounts, errors.Cause(m.SignVote(vote)))
}
func TestSingleAccountManager_SignHash(t *testing.T) { | 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 keystore
import (
"encoding/json"
"math/big"
"testing"
"github.com/facebookgo/clock"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/iotexproject/iotex-core/blockchain"
"github.com/iotexproject/iotex-core/blockchain/action"
"github.com/iotexproject/iotex-core/iotxaddress"
"github.com/iotexproject/iotex-core/pkg/hash"
"github.com/iotexproject/iotex-core/pkg/keypair"
)
func TestSingleAccountManager_SignTransfer(t *testing.T) {
require := require.New(t)
key := &Key{PublicKey: pubKey1, PrivateKey: priKey1, RawAddress: rawAddr1}
keyBytes, err := json.Marshal(key)
require.NoError(err)
accountManager := NewMemAccountManager()
accountManager.Import(keyBytes)
m, err := NewSingleAccountManager(accountManager)
require.NoError(err)
tsf, err := action.NewTransfer(uint64(1), big.NewInt(1), rawAddr1, rawAddr2, []byte{}, uint64(100000), big.NewInt(10))
require.NoError(err)
require.NoError(m.SignTransfer(tsf))
require.NoError(accountManager.Remove(rawAddr1))
require.Equal(ErrNumAccounts, errors.Cause(m.SignTransfer(tsf)))
}
func TestSingleAccountManager_SignVote(t *testing.T) {
require := require.New(t)
key := &Key{PublicKey: pubKey1, PrivateKey: priKey1, RawAddress: rawAddr1}
keyBytes, err := json.Marshal(key)
require.NoError(err)
accountManager := NewMemAccountManager()
accountManager.Import(keyBytes)
m, err := NewSingleAccountManager(accountManager)
require.NoError(err)
selfPubKey, err := keypair.DecodePublicKey(pubKey1)
require.NoError(err)
votePubKey, err := keypair.DecodePublicKey(pubKey2)
require.NoError(err)
voterAddress, err := iotxaddress.GetAddressByPubkey(iotxaddress.IsTestnet, iotxaddress.ChainID, selfPubKey)
require.NoError(err)
voteeAddress, err := iotxaddress.GetAddressByPubkey(iotxaddress.IsTestnet, iotxaddress.ChainID, votePubKey)
require.NoError(err)
rawVote, err := action.NewVote(uint64(1), voterAddress.RawAddress, voteeAddress.RawAddress, uint64(100000), big.NewInt(10))
require.NoError(err)
signedVote, err := m.SignVote(rawVote)
require.NoError(err)
require.NotNil(signedVote)
require.NoError(accountManager.Remove(rawAddr1))
signedVote, err = m.SignVote(rawVote)
require.Equal(ErrNumAccounts, errors.Cause(err))
require.Nil(signedVote)
}
func TestSingleAccountManager_SignHash(t *testing.T) {
require := require.New(t)
key := &Key{PublicKey: pubKey1, PrivateKey: priKey1, RawAddress: rawAddr1}
keyBytes, err := json.Marshal(key)
require.NoError(err)
accountManager := NewMemAccountManager()
accountManager.Import(keyBytes)
m, err := NewSingleAccountManager(accountManager)
require.NoError(err)
blk := blockchain.NewBlock(1, 0, hash.ZeroHash32B, clock.New(), nil, nil, nil)
hash := blk.HashBlock()
signature, err := m.SignHash(hash[:])
require.NoError(err)
require.NotNil(signature)
require.NoError(accountManager.Remove(rawAddr1))
signature, err = m.SignHash(hash[:])
require.Equal(ErrNumAccounts, errors.Cause(err))
require.Nil(signature)
}
| 1 | 11,956 | line is 121 characters | iotexproject-iotex-core | go |
@@ -93,7 +93,7 @@ function setProperty(dom, name, value, oldValue, isSvg) {
}
}
// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6
- else if (name[0] === 'o' && name[1] === 'n') {
+ else if (name.slice(0, 2) === 'on') {
let useCapture = name !== (name = name.replace(/Capture$/, ''));
let nameLower = name.toLowerCase();
name = (nameLower in dom ? nameLower : name).slice(2); | 1 | import { IS_NON_DIMENSIONAL } from '../constants';
import options from '../options';
/**
* Diff the old and new properties of a VNode and apply changes to the DOM node
* @param {import('../internal').PreactElement} dom The DOM node to apply
* changes to
* @param {object} newProps The new props
* @param {object} oldProps The old props
* @param {boolean} isSvg Whether or not this node is an SVG node
* @param {boolean} hydrate Whether or not we are in hydration mode
*/
export function diffProps(dom, newProps, oldProps, isSvg, hydrate) {
let i;
for (i in oldProps) {
if (!(i in newProps)) {
setProperty(dom, i, null, oldProps[i], isSvg);
}
}
for (i in newProps) {
if (
(!hydrate || typeof newProps[i] == 'function') &&
i !== 'value' &&
i !== 'checked' &&
oldProps[i] !== newProps[i]
) {
setProperty(dom, i, newProps[i], oldProps[i], isSvg);
}
}
}
function setStyle(style, key, value) {
if (key[0] === '-') {
style.setProperty(key, value);
} else if (
typeof value === 'number' &&
IS_NON_DIMENSIONAL.test(key) === false
) {
style[key] = value + 'px';
} else if (value == null) {
style[key] = '';
} else {
style[key] = value;
}
}
/**
* Set a property value on a DOM node
* @param {import('../internal').PreactElement} dom The DOM node to modify
* @param {string} name The name of the property to set
* @param {*} value The value to set the property to
* @param {*} oldValue The old value the property had
* @param {boolean} isSvg Whether or not this DOM node is an SVG node or not
*/
function setProperty(dom, name, value, oldValue, isSvg) {
if (isSvg) {
if (name === 'className') {
name = 'class';
}
} else if (name === 'class') {
name = 'className';
}
if (name === 'key' || name === 'children') {
} else if (name === 'style') {
const s = dom.style;
if (typeof value === 'string') {
s.cssText = value;
} else {
if (typeof oldValue === 'string') {
s.cssText = '';
oldValue = null;
}
if (oldValue) {
for (let i in oldValue) {
if (!(value && i in value)) {
setStyle(s, i, '');
}
}
}
if (value) {
for (let i in value) {
if (!oldValue || value[i] !== oldValue[i]) {
setStyle(s, i, value[i]);
}
}
}
}
}
// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6
else if (name[0] === 'o' && name[1] === 'n') {
let useCapture = name !== (name = name.replace(/Capture$/, ''));
let nameLower = name.toLowerCase();
name = (nameLower in dom ? nameLower : name).slice(2);
if (value) {
if (!oldValue) dom.addEventListener(name, eventProxy, useCapture);
(dom._listeners || (dom._listeners = {}))[name] = value;
} else {
dom.removeEventListener(name, eventProxy, useCapture);
}
} else if (
name !== 'list' &&
name !== 'tagName' &&
// HTMLButtonElement.form and HTMLInputElement.form are read-only but can be set using
// setAttribute
name !== 'form' &&
name !== 'type' &&
name !== 'size' &&
!isSvg &&
name in dom
) {
dom[name] = value == null ? '' : value;
} else if (
typeof value !== 'function' &&
name !== 'dangerouslySetInnerHTML'
) {
if (name !== (name = name.replace(/^xlink:?/, ''))) {
if (value == null || value === false) {
dom.removeAttributeNS(
'http://www.w3.org/1999/xlink',
name.toLowerCase()
);
} else {
dom.setAttributeNS(
'http://www.w3.org/1999/xlink',
name.toLowerCase(),
value
);
}
} else if (value == null || value === false) {
dom.removeAttribute(name);
} else {
dom.setAttribute(name, value);
}
}
}
/**
* Proxy an event to hooked event handlers
* @param {Event} e The event object from the browser
* @private
*/
function eventProxy(e) {
this._listeners[e.type](options.event ? options.event(e) : e);
}
| 1 | 15,182 | How's that linked esbench looking with slice? | preactjs-preact | js |
@@ -131,14 +131,11 @@ class RemoteFileSystem(luigi.target.FileSystem):
return exists
def _ftp_exists(self, path, mtime):
- path_parts = path.split('/')
- path = '/'.join(path_parts[:-1])
- fn = path_parts[-1]
-
- files = self.conn.nlst(path)
+ dirname = os.path.dirname(path)
+ files = self.conn.nlst(dirname)
exists = False
- if fn in files:
+ if path in files:
if mtime:
mdtm = self.conn.sendcmd('MDTM ' + path)
modified = datetime.datetime.strptime(mdtm[4:], "%Y%m%d%H%M%S") | 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.
#
"""
This library is a wrapper of ftplib.
It is convenient to move data from/to FTP.
There is an example on how to use it (example/ftp_experiment_outputs.py)
You can also find unittest for each class.
Be aware that normal ftp do not provide secure communication.
"""
import datetime
import ftplib
import os
import random
import tempfile
import io
import luigi
import luigi.file
import luigi.format
import luigi.target
from luigi.format import FileWrapper
import logging
logger = logging.getLogger('luigi-interface')
class RemoteFileSystem(luigi.target.FileSystem):
def __init__(self, host, username=None, password=None, port=None, tls=False, timeout=60, sftp=False):
self.host = host
self.username = username
self.password = password
self.tls = tls
self.timeout = timeout
self.sftp = sftp
if port is None:
if self.sftp:
self.port = 22
else:
self.port = 21
else:
self.port = port
def _connect(self):
"""
Log in to ftp.
"""
if self.sftp:
self._sftp_connect()
else:
self._ftp_connect()
def _sftp_connect(self):
try:
import pysftp
except ImportError:
logger.warning('Please install pysftp to use SFTP.')
self.conn = pysftp.Connection(self.host, username=self.username, password=self.password, port=self.port)
def _ftp_connect(self):
if self.tls:
self.conn = ftplib.FTP_TLS()
else:
self.conn = ftplib.FTP()
self.conn.connect(self.host, self.port, timeout=self.timeout)
self.conn.login(self.username, self.password)
if self.tls:
self.conn.prot_p()
def _close(self):
"""
Close ftp connection.
"""
if self.sftp:
self._sftp_close()
else:
self._ftp_close()
def _sftp_close(self):
self.conn.close()
def _ftp_close(self):
self.conn.quit()
def exists(self, path, mtime=None):
"""
Return `True` if file or directory at `path` exist, False otherwise.
Additional check on modified time when mtime is passed in.
Return False if the file's modified time is older mtime.
"""
self._connect()
if self.sftp:
exists = self._sftp_exists(path, mtime)
else:
exists = self._ftp_exists(path, mtime)
self._close()
return exists
def _sftp_exists(self, path, mtime):
exists = False
if mtime:
exists = self.conn.stat(path).st_mtime > mtime
elif self.conn.exists(path):
exists = True
return exists
def _ftp_exists(self, path, mtime):
path_parts = path.split('/')
path = '/'.join(path_parts[:-1])
fn = path_parts[-1]
files = self.conn.nlst(path)
exists = False
if fn in files:
if mtime:
mdtm = self.conn.sendcmd('MDTM ' + path)
modified = datetime.datetime.strptime(mdtm[4:], "%Y%m%d%H%M%S")
exists = modified > mtime
else:
exists = True
return exists
def remove(self, path, recursive=True):
"""
Remove file or directory at location ``path``.
:param path: a path within the FileSystem to remove.
:type path: str
:param recursive: if the path is a directory, recursively remove the directory and
all of its descendants. Defaults to ``True``.
:type recursive: bool
"""
self._connect()
if self.sftp:
self._sftp_remove(path, recursive)
else:
self._ftp_remove(path, recursive)
self._close()
def _sftp_remove(self, path, recursive):
if self.conn.isfile(path):
self.conn.unlink(path)
else:
if not recursive:
raise RuntimeError("Path is not a regular file, and recursive option is not set")
directories = []
# walk the tree, and execute call backs when files,
# directories and unknown types are encountered
# files must be removed first. then directories can be removed
# after the files are gone.
self.conn.walktree(path, self.conn.unlink, directories.append, self.conn.unlink)
for directory in reversed(directories):
self.conn.rmdir(directory)
self.conn.rmdir(path)
def _ftp_remove(self, path, recursive):
if recursive:
self._rm_recursive(self.conn, path)
else:
try:
# try delete file
self.conn.delete(path)
except ftplib.all_errors:
# it is a folder, delete it
self.conn.rmd(path)
def _rm_recursive(self, ftp, path):
"""
Recursively delete a directory tree on a remote server.
Source: https://gist.github.com/artlogic/2632647
"""
wd = ftp.pwd()
# check if it is a file first, because some FTP servers don't return
# correctly on ftp.nlst(file)
try:
ftp.cwd(path)
except ftplib.all_errors:
# this is a file, we will just delete the file
ftp.delete(path)
return
try:
names = ftp.nlst()
except ftplib.all_errors as e:
# some FTP servers complain when you try and list non-existent paths
return
for name in names:
if os.path.split(name)[1] in ('.', '..'):
continue
try:
ftp.cwd(name) # if we can cwd to it, it's a folder
ftp.cwd(wd) # don't try a nuke a folder we're in
ftp.cwd(path) # then go back to where we were
self._rm_recursive(ftp, name)
except ftplib.all_errors as e:
ftp.delete(name)
try:
ftp.cwd(wd) # do not delete the folder that we are in
ftp.rmd(path)
except ftplib.all_errors as e:
print('_rm_recursive: Could not remove {0}: {1}'.format(path, e))
def put(self, local_path, path, atomic=True):
"""
Put file from local filesystem to (s)FTP.
"""
self._connect()
if self.sftp:
self._sftp_put(local_path, path, atomic)
else:
self._ftp_put(local_path, path, atomic)
self._close()
def _sftp_put(self, local_path, path, atomic):
normpath = os.path.normpath(path)
directory = os.path.dirname(normpath)
self.conn.makedirs(directory)
if atomic:
tmp_path = os.path.join(directory, 'luigi-tmp-{:09d}'.format(random.randrange(0, 1e10)))
else:
tmp_path = normpath
self.conn.put(local_path, tmp_path)
if atomic:
self.conn.rename(tmp_path, normpath)
def _ftp_put(self, local_path, path, atomic):
normpath = os.path.normpath(path)
folder = os.path.dirname(normpath)
# create paths if do not exists
for subfolder in folder.split(os.sep):
if subfolder and subfolder not in self.conn.nlst():
self.conn.mkd(subfolder)
self.conn.cwd(subfolder)
# go back to ftp root folder
self.conn.cwd("/")
# random file name
if atomic:
tmp_path = folder + os.sep + 'luigi-tmp-%09d' % random.randrange(0, 1e10)
else:
tmp_path = normpath
self.conn.storbinary('STOR %s' % tmp_path, open(local_path, 'rb'))
if atomic:
self.conn.rename(tmp_path, normpath)
def get(self, path, local_path):
"""
Download file from (s)FTP to local filesystem.
"""
normpath = os.path.normpath(local_path)
folder = os.path.dirname(normpath)
if folder and not os.path.exists(folder):
os.makedirs(folder)
tmp_local_path = local_path + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
# download file
self._connect()
if self.sftp:
self._sftp_get(path, tmp_local_path)
else:
self._ftp_get(path, tmp_local_path)
self._close()
os.rename(tmp_local_path, local_path)
def _sftp_get(self, path, tmp_local_path):
self.conn.get(path, tmp_local_path)
def _ftp_get(self, path, tmp_local_path):
self.conn.retrbinary('RETR %s' % path, open(tmp_local_path, 'wb').write)
class AtomicFtpFile(luigi.target.AtomicLocalFile):
"""
Simple class that writes to a temp file and upload to ftp on close().
Also cleans up the temp file if close is not invoked.
"""
def __init__(self, fs, path):
"""
Initializes an AtomicFtpfile instance.
:param fs:
:param path:
:type path: str
"""
self._fs = fs
super(AtomicFtpFile, self).__init__(path)
def move_to_final_destination(self):
self._fs.put(self.tmp_path, self.path)
@property
def fs(self):
return self._fs
class RemoteTarget(luigi.target.FileSystemTarget):
"""
Target used for reading from remote files.
The target is implemented using ssh commands streaming data over the network.
"""
def __init__(
self, path, host, format=None, username=None,
password=None, port=None, mtime=None, tls=False,
timeout=60, sftp=False
):
if format is None:
format = luigi.format.get_default_format()
self.path = path
self.mtime = mtime
self.format = format
self.tls = tls
self.timeout = timeout
self.sftp = sftp
self._fs = RemoteFileSystem(host, username, password, port, tls, timeout, sftp)
@property
def fs(self):
return self._fs
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 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.
:type mode: str
"""
if mode == 'w':
return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path))
elif mode == 'r':
temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp')
self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
# download file to local
self._fs.get(self.path, self.__tmp_path)
return self.format.pipe_reader(
FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r')))
)
else:
raise Exception("mode must be 'r' or 'w' (got: %s)" % mode)
def exists(self):
return self.fs.exists(self.path, self.mtime)
def put(self, local_path, atomic=True):
self.fs.put(local_path, self.path, atomic)
def get(self, local_path):
self.fs.get(self.path, local_path)
| 1 | 15,092 | The split and join was probably done to ensure that this still works on Windows because os.path.dirname works differently depending on the os you're running under :(. It would probably be a little better to do `dirname, _, fn = path.rpartition('/')` if you want something cleaner than the split/join. | spotify-luigi | py |
@@ -81,6 +81,10 @@ public abstract class SessionMap implements HasReadyState, Routable {
public abstract void remove(SessionId id);
+ public int getCount() {
+ return -10;
+ };
+
public URI getUri(SessionId id) throws NoSuchSessionException {
return get(id).getUri();
} | 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.grid.sessionmap;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.grid.data.Session;
import org.openqa.selenium.internal.Require;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.HttpHandler;
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.Tracer;
import org.openqa.selenium.status.HasReadyState;
import java.net.URI;
import java.util.Map;
import static org.openqa.selenium.remote.http.Route.combine;
import static org.openqa.selenium.remote.http.Route.delete;
import static org.openqa.selenium.remote.http.Route.post;
/**
* Provides a stable API for looking up where on the Grid a particular webdriver instance is
* running.
* <p>
* This class responds to the following URLs:
* <table summary="HTTP commands the SessionMap understands">
* <tr>
* <th>Verb</th>
* <th>URL Template</th>
* <th>Meaning</th>
* </tr>
* <tr>
* <td>DELETE</td>
* <td>/se/grid/session/{sessionId}</td>
* <td>Removes a {@link URI} from the session map. Calling this method more than once for the same
* {@link SessionId} will not throw an error.</td>
* </tr>
* <tr>
* <td>GET</td>
* <td>/se/grid/session/{sessionId}</td>
* <td>Retrieves the {@link URI} associated the {@link SessionId}, or throws a
* {@link org.openqa.selenium.NoSuchSessionException} should the session not be present.</td>
* </tr>
* <tr>
* <td>POST</td>
* <td>/se/grid/session/{sessionId}</td>
* <td>Registers the session with session map. In theory, the session map never expires a session
* from its mappings, but realistically, sessions may end up being removed for many reasons.
* </td>
* </tr>
* </table>
*/
public abstract class SessionMap implements HasReadyState, Routable {
protected final Tracer tracer;
private final Route routes;
public abstract boolean add(Session session);
public abstract Session get(SessionId id) throws NoSuchSessionException;
public abstract void remove(SessionId id);
public URI getUri(SessionId id) throws NoSuchSessionException {
return get(id).getUri();
}
public SessionMap(Tracer tracer) {
this.tracer = Require.nonNull("Tracer", tracer);
Json json = new Json();
routes = combine(
Route.get("/se/grid/session/{sessionId}/uri")
.to(params -> new GetSessionUri(this, sessionIdFrom(params))),
post("/se/grid/session")
.to(() -> new AddToSessionMap(tracer, json, this)),
Route.get("/se/grid/session/{sessionId}")
.to(params -> new GetFromSessionMap(tracer, this, sessionIdFrom(params))),
delete("/se/grid/session/{sessionId}")
.to(params -> new RemoveFromSession(tracer, this, sessionIdFrom(params))));
}
private SessionId sessionIdFrom(Map<String, String> params) {
return new SessionId(params.get("sessionId"));
}
@Override
public boolean matches(HttpRequest req) {
return routes.matches(req);
}
@Override
public HttpResponse execute(HttpRequest req) {
return routes.execute(req);
}
}
| 1 | 17,774 | This is not the right approach. The `Distributor` maintains a model of the current state of the Grid. That model already contains the information about every active session. We don't need to modify `SessionMap` to expose it further. | SeleniumHQ-selenium | py |
@@ -335,6 +335,9 @@ func (s *session) run() error {
var closeErr closeError
handshakeEvent := s.handshakeEvent
+ var pacingDeadline time.Time
+
+ s.maybeResetTimer(time.Time{})
runLoop:
for { | 1 | package quic
import (
"context"
"crypto/tls"
"errors"
"net"
"sync"
"time"
"github.com/lucas-clemente/quic-go/ackhandler"
"github.com/lucas-clemente/quic-go/congestion"
"github.com/lucas-clemente/quic-go/internal/crypto"
"github.com/lucas-clemente/quic-go/internal/flowcontrol"
"github.com/lucas-clemente/quic-go/internal/handshake"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/utils"
"github.com/lucas-clemente/quic-go/internal/wire"
"github.com/lucas-clemente/quic-go/qerr"
)
type unpacker interface {
Unpack(headerBinary []byte, hdr *wire.Header, data []byte) (*unpackedPacket, error)
}
type streamGetter interface {
GetOrOpenStream(protocol.StreamID) (streamI, error)
}
type receivedPacket struct {
remoteAddr net.Addr
header *wire.Header
data []byte
rcvTime time.Time
}
var (
newCryptoSetup = handshake.NewCryptoSetup
newCryptoSetupClient = handshake.NewCryptoSetupClient
)
type closeError struct {
err error
remote bool
}
// A Session is a QUIC session
type session struct {
connectionID protocol.ConnectionID
perspective protocol.Perspective
version protocol.VersionNumber
config *Config
conn connection
streamsMap *streamsMap
cryptoStream cryptoStreamI
rttStats *congestion.RTTStats
sentPacketHandler ackhandler.SentPacketHandler
receivedPacketHandler ackhandler.ReceivedPacketHandler
streamFramer *streamFramer
windowUpdateQueue *windowUpdateQueue
connFlowController flowcontrol.ConnectionFlowController
unpacker unpacker
packer *packetPacker
cryptoSetup handshake.CryptoSetup
receivedPackets chan *receivedPacket
sendingScheduled chan struct{}
// closeChan is used to notify the run loop that it should terminate.
closeChan chan closeError
closeOnce sync.Once
ctx context.Context
ctxCancel context.CancelFunc
// when we receive too many undecryptable packets during the handshake, we send a Public reset
// but only after a time of protocol.PublicResetTimeout has passed
undecryptablePackets []*receivedPacket
receivedTooManyUndecrytablePacketsTime time.Time
// this channel is passed to the CryptoSetup and receives the transport parameters, as soon as the peer sends them
paramsChan <-chan handshake.TransportParameters
// the handshakeEvent channel is passed to the CryptoSetup.
// It receives when it makes sense to try decrypting undecryptable packets.
handshakeEvent <-chan struct{}
// handshakeChan is returned by handshakeStatus.
// It receives any error that might occur during the handshake.
// It is closed when the handshake is complete.
handshakeChan chan error
handshakeComplete bool
lastRcvdPacketNumber protocol.PacketNumber
// Used to calculate the next packet number from the truncated wire
// representation, and sent back in public reset packets
largestRcvdPacketNumber protocol.PacketNumber
sessionCreationTime time.Time
lastNetworkActivityTime time.Time
peerParams *handshake.TransportParameters
timer *utils.Timer
// keepAlivePingSent stores whether a Ping frame was sent to the peer or not
// it is reset as soon as we receive a packet from the peer
keepAlivePingSent bool
}
var _ Session = &session{}
var _ streamSender = &session{}
// newSession makes a new session
func newSession(
conn connection,
v protocol.VersionNumber,
connectionID protocol.ConnectionID,
scfg *handshake.ServerConfig,
tlsConf *tls.Config,
config *Config,
) (packetHandler, error) {
paramsChan := make(chan handshake.TransportParameters)
handshakeEvent := make(chan struct{}, 1)
s := &session{
conn: conn,
connectionID: connectionID,
perspective: protocol.PerspectiveServer,
version: v,
config: config,
handshakeEvent: handshakeEvent,
paramsChan: paramsChan,
}
s.preSetup()
transportParams := &handshake.TransportParameters{
StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
MaxStreams: protocol.MaxIncomingStreams,
IdleTimeout: s.config.IdleTimeout,
}
cs, err := newCryptoSetup(
s.cryptoStream,
s.connectionID,
s.conn.RemoteAddr(),
s.version,
scfg,
transportParams,
s.config.Versions,
s.config.AcceptCookie,
paramsChan,
handshakeEvent,
)
if err != nil {
return nil, err
}
s.cryptoSetup = cs
return s, s.postSetup(1)
}
// declare this as a variable, so that we can it mock it in the tests
var newClientSession = func(
conn connection,
hostname string,
v protocol.VersionNumber,
connectionID protocol.ConnectionID,
tlsConf *tls.Config,
config *Config,
initialVersion protocol.VersionNumber,
negotiatedVersions []protocol.VersionNumber, // needed for validation of the GQUIC version negotiaton
) (packetHandler, error) {
paramsChan := make(chan handshake.TransportParameters)
handshakeEvent := make(chan struct{}, 1)
s := &session{
conn: conn,
connectionID: connectionID,
perspective: protocol.PerspectiveClient,
version: v,
config: config,
handshakeEvent: handshakeEvent,
paramsChan: paramsChan,
}
s.preSetup()
transportParams := &handshake.TransportParameters{
StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
MaxStreams: protocol.MaxIncomingStreams,
IdleTimeout: s.config.IdleTimeout,
OmitConnectionID: s.config.RequestConnectionIDOmission,
}
cs, err := newCryptoSetupClient(
s.cryptoStream,
hostname,
s.connectionID,
s.version,
tlsConf,
transportParams,
paramsChan,
handshakeEvent,
initialVersion,
negotiatedVersions,
)
if err != nil {
return nil, err
}
s.cryptoSetup = cs
return s, s.postSetup(1)
}
func newTLSServerSession(
conn connection,
connectionID protocol.ConnectionID,
initialPacketNumber protocol.PacketNumber,
config *Config,
tls handshake.MintTLS,
cryptoStreamConn *handshake.CryptoStreamConn,
nullAEAD crypto.AEAD,
peerParams *handshake.TransportParameters,
v protocol.VersionNumber,
) (packetHandler, error) {
handshakeEvent := make(chan struct{}, 1)
s := &session{
conn: conn,
config: config,
connectionID: connectionID,
perspective: protocol.PerspectiveServer,
version: v,
handshakeEvent: handshakeEvent,
}
s.preSetup()
s.cryptoSetup = handshake.NewCryptoSetupTLSServer(
tls,
cryptoStreamConn,
nullAEAD,
handshakeEvent,
v,
)
if err := s.postSetup(initialPacketNumber); err != nil {
return nil, err
}
s.peerParams = peerParams
s.processTransportParameters(peerParams)
s.unpacker = &packetUnpacker{aead: s.cryptoSetup, version: s.version}
return s, nil
}
// declare this as a variable, such that we can it mock it in the tests
var newTLSClientSession = func(
conn connection,
hostname string,
v protocol.VersionNumber,
connectionID protocol.ConnectionID,
config *Config,
tls handshake.MintTLS,
paramsChan <-chan handshake.TransportParameters,
initialPacketNumber protocol.PacketNumber,
) (packetHandler, error) {
handshakeEvent := make(chan struct{}, 1)
s := &session{
conn: conn,
config: config,
connectionID: connectionID,
perspective: protocol.PerspectiveClient,
version: v,
handshakeEvent: handshakeEvent,
paramsChan: paramsChan,
}
s.preSetup()
tls.SetCryptoStream(s.cryptoStream)
cs, err := handshake.NewCryptoSetupTLSClient(
s.cryptoStream,
s.connectionID,
hostname,
handshakeEvent,
tls,
v,
)
if err != nil {
return nil, err
}
s.cryptoSetup = cs
return s, s.postSetup(initialPacketNumber)
}
func (s *session) preSetup() {
s.rttStats = &congestion.RTTStats{}
s.connFlowController = flowcontrol.NewConnectionFlowController(
protocol.ReceiveConnectionFlowControlWindow,
protocol.ByteCount(s.config.MaxReceiveConnectionFlowControlWindow),
s.rttStats,
)
s.cryptoStream = s.newCryptoStream()
}
func (s *session) postSetup(initialPacketNumber protocol.PacketNumber) error {
s.handshakeChan = make(chan error, 1)
s.receivedPackets = make(chan *receivedPacket, protocol.MaxSessionUnprocessedPackets)
s.closeChan = make(chan closeError, 1)
s.sendingScheduled = make(chan struct{}, 1)
s.undecryptablePackets = make([]*receivedPacket, 0, protocol.MaxUndecryptablePackets)
s.ctx, s.ctxCancel = context.WithCancel(context.Background())
s.timer = utils.NewTimer()
now := time.Now()
s.lastNetworkActivityTime = now
s.sessionCreationTime = now
s.sentPacketHandler = ackhandler.NewSentPacketHandler(s.rttStats)
s.receivedPacketHandler = ackhandler.NewReceivedPacketHandler(s.version)
s.streamsMap = newStreamsMap(s.newStream, s.perspective, s.version)
s.streamFramer = newStreamFramer(s.cryptoStream, s.streamsMap, s.version)
s.packer = newPacketPacker(s.connectionID,
initialPacketNumber,
s.cryptoSetup,
s.streamFramer,
s.perspective,
s.version,
)
s.windowUpdateQueue = newWindowUpdateQueue(s.streamsMap, s.cryptoStream, s.packer.QueueControlFrame)
s.unpacker = &packetUnpacker{aead: s.cryptoSetup, version: s.version}
return nil
}
// run the session main loop
func (s *session) run() error {
defer s.ctxCancel()
go func() {
if err := s.cryptoSetup.HandleCryptoStream(); err != nil {
s.Close(err)
}
}()
var closeErr closeError
handshakeEvent := s.handshakeEvent
runLoop:
for {
// Close immediately if requested
select {
case closeErr = <-s.closeChan:
break runLoop
default:
}
s.maybeResetTimer()
select {
case closeErr = <-s.closeChan:
break runLoop
case <-s.timer.Chan():
s.timer.SetRead()
// We do all the interesting stuff after the switch statement, so
// nothing to see here.
case <-s.sendingScheduled:
// We do all the interesting stuff after the switch statement, so
// nothing to see here.
case p := <-s.receivedPackets:
err := s.handlePacketImpl(p)
if err != nil {
if qErr, ok := err.(*qerr.QuicError); ok && qErr.ErrorCode == qerr.DecryptionFailure {
s.tryQueueingUndecryptablePacket(p)
continue
}
s.closeLocal(err)
continue
}
// This is a bit unclean, but works properly, since the packet always
// begins with the public header and we never copy it.
putPacketBuffer(p.header.Raw)
case p := <-s.paramsChan:
s.processTransportParameters(&p)
case _, ok := <-handshakeEvent:
if !ok { // the aeadChanged chan was closed. This means that the handshake is completed.
s.handshakeComplete = true
handshakeEvent = nil // prevent this case from ever being selected again
s.sentPacketHandler.SetHandshakeComplete()
close(s.handshakeChan)
} else {
s.tryDecryptingQueuedPackets()
}
}
now := time.Now()
if timeout := s.sentPacketHandler.GetAlarmTimeout(); !timeout.IsZero() && timeout.Before(now) {
// This could cause packets to be retransmitted, so check it before trying
// to send packets.
s.sentPacketHandler.OnAlarm()
}
if s.config.KeepAlive && s.handshakeComplete && time.Since(s.lastNetworkActivityTime) >= s.peerParams.IdleTimeout/2 {
// send the PING frame since there is no activity in the session
s.packer.QueueControlFrame(&wire.PingFrame{})
s.keepAlivePingSent = true
}
if err := s.sendPacket(); err != nil {
s.closeLocal(err)
}
if !s.receivedTooManyUndecrytablePacketsTime.IsZero() && s.receivedTooManyUndecrytablePacketsTime.Add(protocol.PublicResetTimeout).Before(now) && len(s.undecryptablePackets) != 0 {
s.closeLocal(qerr.Error(qerr.DecryptionFailure, "too many undecryptable packets received"))
}
if !s.handshakeComplete && now.Sub(s.sessionCreationTime) >= s.config.HandshakeTimeout {
s.closeLocal(qerr.Error(qerr.HandshakeTimeout, "Crypto handshake did not complete in time."))
}
if s.handshakeComplete && now.Sub(s.lastNetworkActivityTime) >= s.config.IdleTimeout {
s.closeLocal(qerr.Error(qerr.NetworkIdleTimeout, "No recent network activity."))
}
}
// only send the error the handshakeChan when the handshake is not completed yet
// otherwise this chan will already be closed
if !s.handshakeComplete {
s.handshakeChan <- closeErr.err
}
s.handleCloseError(closeErr)
return closeErr.err
}
func (s *session) Context() context.Context {
return s.ctx
}
func (s *session) maybeResetTimer() {
var deadline time.Time
if s.config.KeepAlive && s.handshakeComplete && !s.keepAlivePingSent {
deadline = s.lastNetworkActivityTime.Add(s.peerParams.IdleTimeout / 2)
} else {
deadline = s.lastNetworkActivityTime.Add(s.config.IdleTimeout)
}
if ackAlarm := s.receivedPacketHandler.GetAlarmTimeout(); !ackAlarm.IsZero() {
deadline = utils.MinTime(deadline, ackAlarm)
}
if lossTime := s.sentPacketHandler.GetAlarmTimeout(); !lossTime.IsZero() {
deadline = utils.MinTime(deadline, lossTime)
}
if !s.handshakeComplete {
handshakeDeadline := s.sessionCreationTime.Add(s.config.HandshakeTimeout)
deadline = utils.MinTime(deadline, handshakeDeadline)
}
if !s.receivedTooManyUndecrytablePacketsTime.IsZero() {
deadline = utils.MinTime(deadline, s.receivedTooManyUndecrytablePacketsTime.Add(protocol.PublicResetTimeout))
}
s.timer.Reset(deadline)
}
func (s *session) handlePacketImpl(p *receivedPacket) error {
if s.perspective == protocol.PerspectiveClient {
diversificationNonce := p.header.DiversificationNonce
if len(diversificationNonce) > 0 {
s.cryptoSetup.SetDiversificationNonce(diversificationNonce)
}
}
if p.rcvTime.IsZero() {
// To simplify testing
p.rcvTime = time.Now()
}
s.lastNetworkActivityTime = p.rcvTime
s.keepAlivePingSent = false
hdr := p.header
data := p.data
// Calculate packet number
hdr.PacketNumber = protocol.InferPacketNumber(
hdr.PacketNumberLen,
s.largestRcvdPacketNumber,
hdr.PacketNumber,
)
packet, err := s.unpacker.Unpack(hdr.Raw, hdr, data)
if utils.Debug() {
if err != nil {
utils.Debugf("<- Reading packet 0x%x (%d bytes) for connection %x", hdr.PacketNumber, len(data)+len(hdr.Raw), hdr.ConnectionID)
} else {
utils.Debugf("<- Reading packet 0x%x (%d bytes) for connection %x, %s", hdr.PacketNumber, len(data)+len(hdr.Raw), hdr.ConnectionID, packet.encryptionLevel)
}
hdr.Log()
}
// if the decryption failed, this might be a packet sent by an attacker
if err != nil {
return err
}
s.lastRcvdPacketNumber = hdr.PacketNumber
// Only do this after decrypting, so we are sure the packet is not attacker-controlled
s.largestRcvdPacketNumber = utils.MaxPacketNumber(s.largestRcvdPacketNumber, hdr.PacketNumber)
isRetransmittable := ackhandler.HasRetransmittableFrames(packet.frames)
if err = s.receivedPacketHandler.ReceivedPacket(hdr.PacketNumber, isRetransmittable); err != nil {
return err
}
return s.handleFrames(packet.frames, packet.encryptionLevel)
}
func (s *session) handleFrames(fs []wire.Frame, encLevel protocol.EncryptionLevel) error {
for _, ff := range fs {
var err error
wire.LogFrame(ff, false)
switch frame := ff.(type) {
case *wire.StreamFrame:
err = s.handleStreamFrame(frame)
case *wire.AckFrame:
err = s.handleAckFrame(frame, encLevel)
case *wire.ConnectionCloseFrame:
s.closeRemote(qerr.Error(frame.ErrorCode, frame.ReasonPhrase))
case *wire.GoawayFrame:
err = errors.New("unimplemented: handling GOAWAY frames")
case *wire.StopWaitingFrame: // ignore STOP_WAITINGs
case *wire.RstStreamFrame:
err = s.handleRstStreamFrame(frame)
case *wire.MaxDataFrame:
s.handleMaxDataFrame(frame)
case *wire.MaxStreamDataFrame:
err = s.handleMaxStreamDataFrame(frame)
case *wire.BlockedFrame:
case *wire.StreamBlockedFrame:
case *wire.StopSendingFrame:
err = s.handleStopSendingFrame(frame)
case *wire.PingFrame:
default:
return errors.New("Session BUG: unexpected frame type")
}
if err != nil {
switch err {
case ackhandler.ErrDuplicateOrOutOfOrderAck:
// Can happen e.g. when packets thought missing arrive late
default:
return err
}
}
}
return nil
}
// handlePacket is called by the server with a new packet
func (s *session) handlePacket(p *receivedPacket) {
// Discard packets once the amount of queued packets is larger than
// the channel size, protocol.MaxSessionUnprocessedPackets
select {
case s.receivedPackets <- p:
default:
}
}
func (s *session) handleStreamFrame(frame *wire.StreamFrame) error {
if frame.StreamID == s.version.CryptoStreamID() {
if frame.FinBit {
return errors.New("Received STREAM frame with FIN bit for the crypto stream")
}
return s.cryptoStream.handleStreamFrame(frame)
}
str, err := s.streamsMap.GetOrOpenStream(frame.StreamID)
if err != nil {
return err
}
if str == nil {
// Stream is closed and already garbage collected
// ignore this StreamFrame
return nil
}
return str.handleStreamFrame(frame)
}
func (s *session) handleMaxDataFrame(frame *wire.MaxDataFrame) {
s.connFlowController.UpdateSendWindow(frame.ByteOffset)
}
func (s *session) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) error {
if frame.StreamID == s.version.CryptoStreamID() {
s.cryptoStream.handleMaxStreamDataFrame(frame)
return nil
}
str, err := s.streamsMap.GetOrOpenStream(frame.StreamID)
if err != nil {
return err
}
if str == nil {
// stream is closed and already garbage collected
return nil
}
str.handleMaxStreamDataFrame(frame)
return nil
}
func (s *session) handleStopSendingFrame(frame *wire.StopSendingFrame) error {
if frame.StreamID == s.version.CryptoStreamID() {
return errors.New("Received a STOP_SENDING frame for the crypto stream")
}
str, err := s.streamsMap.GetOrOpenStream(frame.StreamID)
if err != nil {
return err
}
if str == nil {
// stream is closed and already garbage collected
return nil
}
str.handleStopSendingFrame(frame)
return nil
}
func (s *session) handleRstStreamFrame(frame *wire.RstStreamFrame) error {
if frame.StreamID == s.version.CryptoStreamID() {
return errors.New("Received RST_STREAM frame for the crypto stream")
}
str, err := s.streamsMap.GetOrOpenStream(frame.StreamID)
if err != nil {
return err
}
if str == nil {
// stream is closed and already garbage collected
return nil
}
return str.handleRstStreamFrame(frame)
}
func (s *session) handleAckFrame(frame *wire.AckFrame, encLevel protocol.EncryptionLevel) error {
if err := s.sentPacketHandler.ReceivedAck(frame, s.lastRcvdPacketNumber, encLevel, s.lastNetworkActivityTime); err != nil {
return err
}
s.receivedPacketHandler.IgnoreBelow(s.sentPacketHandler.GetLowestPacketNotConfirmedAcked())
return nil
}
func (s *session) closeLocal(e error) {
s.closeOnce.Do(func() {
s.closeChan <- closeError{err: e, remote: false}
})
}
func (s *session) closeRemote(e error) {
s.closeOnce.Do(func() {
s.closeChan <- closeError{err: e, remote: true}
})
}
// Close the connection. If err is nil it will be set to qerr.PeerGoingAway.
// It waits until the run loop has stopped before returning
func (s *session) Close(e error) error {
s.closeLocal(e)
<-s.ctx.Done()
return nil
}
func (s *session) handleCloseError(closeErr closeError) error {
if closeErr.err == nil {
closeErr.err = qerr.PeerGoingAway
}
var quicErr *qerr.QuicError
var ok bool
if quicErr, ok = closeErr.err.(*qerr.QuicError); !ok {
quicErr = qerr.ToQuicError(closeErr.err)
}
// Don't log 'normal' reasons
if quicErr.ErrorCode == qerr.PeerGoingAway || quicErr.ErrorCode == qerr.NetworkIdleTimeout {
utils.Infof("Closing connection %x", s.connectionID)
} else {
utils.Errorf("Closing session with error: %s", closeErr.err.Error())
}
s.cryptoStream.closeForShutdown(quicErr)
s.streamsMap.CloseWithError(quicErr)
if closeErr.err == errCloseSessionForNewVersion || closeErr.err == handshake.ErrCloseSessionForRetry {
return nil
}
// If this is a remote close we're done here
if closeErr.remote {
return nil
}
if quicErr.ErrorCode == qerr.DecryptionFailure ||
quicErr == handshake.ErrHOLExperiment ||
quicErr == handshake.ErrNSTPExperiment {
return s.sendPublicReset(s.lastRcvdPacketNumber)
}
return s.sendConnectionClose(quicErr)
}
func (s *session) processTransportParameters(params *handshake.TransportParameters) {
s.peerParams = params
s.streamsMap.UpdateMaxStreamLimit(params.MaxStreams)
if params.OmitConnectionID {
s.packer.SetOmitConnectionID()
}
s.connFlowController.UpdateSendWindow(params.ConnectionFlowControlWindow)
// increase the flow control windows of all streams by sending them a fake MAX_STREAM_DATA frame
s.streamsMap.Range(func(str streamI) {
str.handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{
StreamID: str.StreamID(),
ByteOffset: params.StreamFlowControlWindow,
})
})
}
func (s *session) sendPacket() error {
s.packer.SetLeastUnacked(s.sentPacketHandler.GetLeastUnacked())
if offset := s.connFlowController.GetWindowUpdate(); offset != 0 {
s.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: offset})
}
if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked {
s.packer.QueueControlFrame(&wire.BlockedFrame{Offset: offset})
}
s.windowUpdateQueue.QueueAll()
ack := s.receivedPacketHandler.GetAckFrame()
if ack != nil {
s.packer.QueueControlFrame(ack)
}
// Repeatedly try sending until we don't have any more data, or run out of the congestion window
for {
if !s.sentPacketHandler.SendingAllowed() {
if ack == nil {
return nil
}
// If we aren't allowed to send, at least try sending an ACK frame
if !s.version.UsesIETFFrameFormat() {
if swf := s.sentPacketHandler.GetStopWaitingFrame(false); swf != nil {
s.packer.QueueControlFrame(swf)
}
}
packet, err := s.packer.PackAckPacket()
if err != nil {
return err
}
return s.sendPackedPacket(packet)
}
// check for retransmissions first
for {
retransmitPacket := s.sentPacketHandler.DequeuePacketForRetransmission()
if retransmitPacket == nil {
break
}
if retransmitPacket.EncryptionLevel != protocol.EncryptionForwardSecure {
if s.handshakeComplete {
// Don't retransmit handshake packets when the handshake is complete
continue
}
utils.Debugf("\tDequeueing handshake retransmission for packet 0x%x", retransmitPacket.PacketNumber)
if !s.version.UsesIETFFrameFormat() {
s.packer.QueueControlFrame(s.sentPacketHandler.GetStopWaitingFrame(true))
}
packet, err := s.packer.PackHandshakeRetransmission(retransmitPacket)
if err != nil {
return err
}
if err = s.sendPackedPacket(packet); err != nil {
return err
}
} else {
utils.Debugf("\tDequeueing retransmission for packet 0x%x", retransmitPacket.PacketNumber)
// resend the frames that were in the packet
for _, frame := range retransmitPacket.GetFramesForRetransmission() {
// TODO: only retransmit WINDOW_UPDATEs if they actually enlarge the window
switch f := frame.(type) {
case *wire.StreamFrame:
s.streamFramer.AddFrameForRetransmission(f)
default:
s.packer.QueueControlFrame(frame)
}
}
}
}
hasRetransmission := s.streamFramer.HasFramesForRetransmission()
if !s.version.UsesIETFFrameFormat() && (ack != nil || hasRetransmission) {
if swf := s.sentPacketHandler.GetStopWaitingFrame(hasRetransmission); swf != nil {
s.packer.QueueControlFrame(swf)
}
}
// add a retransmittable frame
if s.sentPacketHandler.ShouldSendRetransmittablePacket() {
s.packer.MakeNextPacketRetransmittable()
}
packet, err := s.packer.PackPacket()
if err != nil || packet == nil {
return err
}
if err = s.sendPackedPacket(packet); err != nil {
return err
}
ack = nil
}
}
func (s *session) sendPackedPacket(packet *packedPacket) error {
defer putPacketBuffer(packet.raw)
err := s.sentPacketHandler.SentPacket(&ackhandler.Packet{
PacketNumber: packet.header.PacketNumber,
Frames: packet.frames,
Length: protocol.ByteCount(len(packet.raw)),
EncryptionLevel: packet.encryptionLevel,
})
if err != nil {
return err
}
s.logPacket(packet)
return s.conn.Write(packet.raw)
}
func (s *session) sendConnectionClose(quicErr *qerr.QuicError) error {
s.packer.SetLeastUnacked(s.sentPacketHandler.GetLeastUnacked())
packet, err := s.packer.PackConnectionClose(&wire.ConnectionCloseFrame{
ErrorCode: quicErr.ErrorCode,
ReasonPhrase: quicErr.ErrorMessage,
})
if err != nil {
return err
}
s.logPacket(packet)
return s.conn.Write(packet.raw)
}
func (s *session) logPacket(packet *packedPacket) {
if !utils.Debug() {
// We don't need to allocate the slices for calling the format functions
return
}
utils.Debugf("-> Sending packet 0x%x (%d bytes) for connection %x, %s", packet.header.PacketNumber, len(packet.raw), s.connectionID, packet.encryptionLevel)
packet.header.Log()
for _, frame := range packet.frames {
wire.LogFrame(frame, true)
}
}
// GetOrOpenStream either returns an existing stream, a newly opened stream, or nil if a stream with the provided ID is already closed.
// Newly opened streams should only originate from the client. To open a stream from the server, OpenStream should be used.
func (s *session) GetOrOpenStream(id protocol.StreamID) (Stream, error) {
str, err := s.streamsMap.GetOrOpenStream(id)
if str != nil {
return str, err
}
// make sure to return an actual nil value here, not an Stream with value nil
return nil, err
}
// AcceptStream returns the next stream openend by the peer
func (s *session) AcceptStream() (Stream, error) {
return s.streamsMap.AcceptStream()
}
// OpenStream opens a stream
func (s *session) OpenStream() (Stream, error) {
return s.streamsMap.OpenStream()
}
func (s *session) OpenStreamSync() (Stream, error) {
return s.streamsMap.OpenStreamSync()
}
func (s *session) newStream(id protocol.StreamID) streamI {
var initialSendWindow protocol.ByteCount
if s.peerParams != nil {
initialSendWindow = s.peerParams.StreamFlowControlWindow
}
flowController := flowcontrol.NewStreamFlowController(
id,
s.version.StreamContributesToConnectionFlowControl(id),
s.connFlowController,
protocol.ReceiveStreamFlowControlWindow,
protocol.ByteCount(s.config.MaxReceiveStreamFlowControlWindow),
initialSendWindow,
s.rttStats,
)
return newStream(id, s, flowController, s.version)
}
func (s *session) newCryptoStream() cryptoStreamI {
id := s.version.CryptoStreamID()
flowController := flowcontrol.NewStreamFlowController(
id,
s.version.StreamContributesToConnectionFlowControl(id),
s.connFlowController,
protocol.ReceiveStreamFlowControlWindow,
protocol.ByteCount(s.config.MaxReceiveStreamFlowControlWindow),
0,
s.rttStats,
)
return newCryptoStream(s, flowController, s.version)
}
func (s *session) sendPublicReset(rejectedPacketNumber protocol.PacketNumber) error {
utils.Infof("Sending public reset for connection %x, packet number %d", s.connectionID, rejectedPacketNumber)
return s.conn.Write(wire.WritePublicReset(s.connectionID, rejectedPacketNumber, 0))
}
// scheduleSending signals that we have data for sending
func (s *session) scheduleSending() {
select {
case s.sendingScheduled <- struct{}{}:
default:
}
}
func (s *session) tryQueueingUndecryptablePacket(p *receivedPacket) {
if s.handshakeComplete {
utils.Debugf("Received undecryptable packet from %s after the handshake: %#v, %d bytes data", p.remoteAddr.String(), p.header, len(p.data))
return
}
if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets {
// if this is the first time the undecryptablePackets runs full, start the timer to send a Public Reset
if s.receivedTooManyUndecrytablePacketsTime.IsZero() {
s.receivedTooManyUndecrytablePacketsTime = time.Now()
s.maybeResetTimer()
}
utils.Infof("Dropping undecrytable packet 0x%x (undecryptable packet queue full)", p.header.PacketNumber)
return
}
utils.Infof("Queueing packet 0x%x for later decryption", p.header.PacketNumber)
s.undecryptablePackets = append(s.undecryptablePackets, p)
}
func (s *session) tryDecryptingQueuedPackets() {
for _, p := range s.undecryptablePackets {
s.handlePacket(p)
}
s.undecryptablePackets = s.undecryptablePackets[:0]
}
func (s *session) queueControlFrame(f wire.Frame) {
s.packer.QueueControlFrame(f)
s.scheduleSending()
}
func (s *session) onHasWindowUpdate(id protocol.StreamID) {
s.windowUpdateQueue.Add(id)
s.scheduleSending()
}
func (s *session) onHasStreamData(id protocol.StreamID) {
s.streamFramer.AddActiveStream(id)
s.scheduleSending()
}
func (s *session) onStreamCompleted(id protocol.StreamID) {
if err := s.streamsMap.DeleteStream(id); err != nil {
s.Close(err)
}
}
func (s *session) LocalAddr() net.Addr {
return s.conn.LocalAddr()
}
// RemoteAddr returns the net.Addr of the client
func (s *session) RemoteAddr() net.Addr {
return s.conn.RemoteAddr()
}
func (s *session) handshakeStatus() <-chan error {
return s.handshakeChan
}
func (s *session) getCryptoStream() cryptoStreamI {
return s.cryptoStream
}
func (s *session) GetVersion() protocol.VersionNumber {
return s.version
}
| 1 | 7,223 | Can you make this a member var as all the other deadlines? Then you can drop the param to resetTimer() and simplify some of the code below iiuc. | lucas-clemente-quic-go | go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.