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 |
---|---|---|---|---|---|---|---|
@@ -173,7 +173,7 @@ public class DefaultConditionRunner implements ConditionRunner {
}
protected void log(String message) {
- logger.info(new Date() + " - " + message);
+ logger.finest(new Date() + " - " + message);
}
} | 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 com.thoughtworks.selenium.condition;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.SeleniumException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
/**
* This ConditionRunner throws a simple {@link RuntimeException} when the
* condition is not met in the {@link #waitFor(Condition)} method. More specific
* runners are preferred for different testing frameworks. E.g. JUnit tests
* would prefer to use {@link JUnitConditionRunner}.
*/
public class DefaultConditionRunner implements ConditionRunner {
private final Monitor monitor;
private final Selenium selenium;
private final int initialDelay;
private final int interval;
private final int timeout;
/**
* @param monitor the Monitor
* @param selenium the selenium to be passed to the Conditions run from within this runner.
* @param initialDelay (in millis) how long to wait before the initial test of the condition
* @param interval (in millis) when waiting for a condition, how long to wait between calls to
* {@link Condition#isTrue(com.thoughtworks.selenium.condition.ConditionRunner.Context)}
* @param timeout (in millis) when waiting for a condition, how long to wait until we give up.
*/
public DefaultConditionRunner(Monitor monitor, Selenium selenium, int initialDelay, int interval,
int timeout) {
this.monitor = monitor;
this.selenium = selenium;
this.initialDelay = initialDelay;
this.interval = interval;
this.timeout = timeout;
}
/**
* @param monitor the Monitor
* @param selenium the selenium to be passed to the Conditions run from within this runner.
* @param interval (in millis) when waiting for a condition, how long to wait between calls to
* {@link Condition#isTrue(com.thoughtworks.selenium.condition.ConditionRunner.Context)}
* @param timeout (in millis) when waiting for a condition, how long to wait until we give up.
*/
public DefaultConditionRunner(Monitor monitor, Selenium selenium, int interval, int timeout) {
this(monitor, selenium, interval, interval, timeout);
}
/**
* Constructs an instance of this class with a {@link NoOpMonitor}.
*
* @see DefaultConditionRunner#DefaultConditionRunner(Monitor, Selenium, int, int)
* @param selenium the selenium to be passed to the Conditions run from within this runner.
* @param initialDelay (in millis) how long to wait before the initial test of the condition
* @param interval (in millis) when waiting for a condition, how long to wait between calls to
* {@link Condition#isTrue(com.thoughtworks.selenium.condition.ConditionRunner.Context)}
* @param timeout (in millis) when waiting for a condition, how long to wait until we give up.
*/
public DefaultConditionRunner(Selenium selenium, int initialDelay, int interval, int timeout) {
this(new NoOpMonitor(), selenium, initialDelay, interval, timeout);
}
/**
* Constructs an instance of this class with a {@link NoOpMonitor}.
*
* @see DefaultConditionRunner#DefaultConditionRunner(Monitor, Selenium, int, int)
* @param selenium the selenium to be passed to the Conditions run from within this runner.
* @param interval (in millis) when waiting for a condition, how long to wait between calls to
* {@link Condition#isTrue(com.thoughtworks.selenium.condition.ConditionRunner.Context)}
* @param timeout (in millis) when waiting for a condition, how long to wait until we give up.
*/
public DefaultConditionRunner(Selenium selenium, int interval, int timeout) {
this(new NoOpMonitor(), selenium, interval, timeout);
}
/**
* Constructs an instance of this class with reasonable defaults.
*
* @see DefaultConditionRunner#DefaultConditionRunner(Monitor, Selenium, int, int)
* @param selenium the selenium to be passed to the Conditions run from within this runner.
*/
public DefaultConditionRunner(Selenium selenium) {
this(new NoOpMonitor(), selenium, 500, 45 * 1000);
}
/**
* A {@link Monitor} can be installed in {@link DefaultConditionRunner} as an open ended way of
* being notified of certain events.
*/
public interface Monitor {
/**
* Called whenever a {@link DefaultConditionRunner#waitFor(Condition)} has begun, and is being
* tracked with the given {@code condition}.
*
* @param condition condition that waiting is about to begin
* @param context context on with the condition will be run
*/
void waitHasBegun(ConditionRunner.Context context, Condition condition);
/**
* Called whenever a {@link DefaultConditionRunner#waitFor(Condition)} is successful (i.e.
* {@link Condition#isTrue(com.thoughtworks.selenium.condition.ConditionRunner.Context)}
* returned true within the timeout}.
* @param condition condition that waiting completed
* @param context context for the condition
*/
void conditionWasReached(ConditionRunner.Context context, Condition condition);
void conditionFailed(ConditionRunner.Context context, Condition condition, String message);
}
/**
* A no-op implementation of {@link Monitor}.
*/
public static final class NoOpMonitor implements Monitor {
@Override
public void waitHasBegun(ConditionRunner.Context context, Condition condition) {
}
@Override
public void conditionWasReached(ConditionRunner.Context context, Condition condition) {
}
@Override
public void conditionFailed(Context context, Condition condition, String message) {
}
}
/**
* A Log4j implementation of {@link Monitor}.
*/
public static final class Log4jMonitor implements Monitor {
private static final Logger logger =
Logger.getLogger(DefaultConditionRunner.class.getName());
@Override
public void conditionWasReached(ConditionRunner.Context context, Condition condition) {
log("Reached " + condition.toString());
}
@Override
public void waitHasBegun(ConditionRunner.Context context, Condition condition) {
log("Waiting for " + condition.toString());
}
@Override
public void conditionFailed(ConditionRunner.Context context, Condition condition, String message) {
log(message);
}
protected void log(String message) {
logger.info(new Date() + " - " + message);
}
}
@Override
public void waitFor(Condition condition) {
waitFor("", condition);
}
@Override
public void waitFor(String narrative, Condition condition) {
ContextImpl context = new ContextImpl();
SeleniumException seleniumException = null;
try {
monitor.waitHasBegun(context, condition);
threadSleep(initialDelay);
while (context.elapsed() < context.timeout()) {
seleniumException = null;
try {
if (condition.isTrue(context)) {
monitor.conditionWasReached(context, condition);
return;
}
} catch (SeleniumException se) {
seleniumException = se;
}
threadSleep(interval);
}
} catch (RuntimeException e) {
throwAssertionException("Exception while waiting for '" + condition.toString() + "'", e);
}
if (seleniumException != null) {
throwAssertionException("SeleniumException while waiting for '" + condition.toString() +
"' (otherwise timed out)", seleniumException);
}
// Note that AssertionFailedError will pass right through
String message = context.failureMessage(narrative, condition);
monitor.conditionFailed(context, condition, message);
throwAssertionException(message);
}
private void threadSleep(int interval) {
try {
Thread.sleep(interval);
} catch (InterruptedException ignore) {
}
}
protected void throwAssertionException(String message) {
throw new RuntimeException(message);
}
protected void throwAssertionException(String message, Throwable throwable) {
throw new RuntimeException(message, throwable);
}
private final class ContextImpl implements ConditionRunner.Context {
private final long start;
private List<String> info = new ArrayList<>();
private String lastInfo;
public ContextImpl() {
this.start = now();
}
private long now() {
return System.currentTimeMillis();
}
@Override
public void info(String info) {
if (!info.equals(lastInfo)) {
this.info.add(info);
}
lastInfo = info;
}
@Override
public long elapsed() {
return now() - start;
}
@Override
public Selenium getSelenium() {
return selenium;
}
@Override
public ConditionRunner getConditionRunner() {
return DefaultConditionRunner.this;
}
private String failureMessage(String narrative, Condition condition) {
String message = condition.toString() +
" failed to become true within " + timeout() + " msec";
message += narrative.equals("") ? "" : "; " + narrative;
if (!info.isEmpty()) {
message += "; " + info;
}
return message;
}
private int timeout() {
return timeout;
}
}
}
| 1 | 16,441 | This method is designed to allow the condition runner to tell users something interesting. The current `INFO` log level is correct. | SeleniumHQ-selenium | js |
@@ -36,7 +36,7 @@ type Info struct {
SSLRequired bool `json:"ssl_required"` // DEPRECATED: ssl json used for older clients
TLSRequired bool `json:"tls_required"`
TLSVerify bool `json:"tls_verify"`
- MaxPayload int `json:"max_payload"`
+ MaxPayload int64 `json:"max_payload"`
IP string `json:"ip,omitempty"`
ClientConnectURLs []string `json:"connect_urls,omitempty"` // Contains URLs a client can connect to.
| 1 | // Copyright 2012-2016 Apcera Inc. All rights reserved.
package server
import (
"bufio"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
// Allow dynamic profiling.
_ "net/http/pprof"
"github.com/nats-io/gnatsd/util"
)
// Info is the information sent to clients to help them understand information
// about this server.
type Info struct {
ID string `json:"server_id"`
Version string `json:"version"`
GoVersion string `json:"go"`
Host string `json:"host"`
Port int `json:"port"`
AuthRequired bool `json:"auth_required"`
SSLRequired bool `json:"ssl_required"` // DEPRECATED: ssl json used for older clients
TLSRequired bool `json:"tls_required"`
TLSVerify bool `json:"tls_verify"`
MaxPayload int `json:"max_payload"`
IP string `json:"ip,omitempty"`
ClientConnectURLs []string `json:"connect_urls,omitempty"` // Contains URLs a client can connect to.
// Used internally for quick look-ups.
clientConnectURLs map[string]struct{}
}
// Server is our main struct.
type Server struct {
gcid uint64
grid uint64
stats
mu sync.Mutex
info Info
infoJSON []byte
sl *Sublist
configFile string
optsMu sync.RWMutex
opts *Options
running bool
shutdown bool
listener net.Listener
clients map[uint64]*client
routes map[uint64]*client
remotes map[string]*client
users map[string]*User
totalClients uint64
done chan bool
start time.Time
http net.Listener
httpHandler http.Handler
profiler net.Listener
httpReqStats map[string]uint64
routeListener net.Listener
routeInfo Info
routeInfoJSON []byte
rcQuit chan bool
grMu sync.Mutex
grTmpClients map[uint64]*client
grRunning bool
grWG sync.WaitGroup // to wait on various go routines
cproto int64 // number of clients supporting async INFO
logging struct {
sync.RWMutex
logger Logger
trace int32
debug int32
}
}
// Make sure all are 64bits for atomic use
type stats struct {
inMsgs int64
outMsgs int64
inBytes int64
outBytes int64
slowConsumers int64
}
// New will setup a new server struct after parsing the options.
func New(opts *Options) *Server {
processOptions(opts)
// Process TLS options, including whether we require client certificates.
tlsReq := opts.TLSConfig != nil
verify := (tlsReq && opts.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert)
info := Info{
ID: genID(),
Version: VERSION,
GoVersion: runtime.Version(),
Host: opts.Host,
Port: opts.Port,
AuthRequired: false,
TLSRequired: tlsReq,
SSLRequired: tlsReq,
TLSVerify: verify,
MaxPayload: opts.MaxPayload,
clientConnectURLs: make(map[string]struct{}),
}
s := &Server{
configFile: opts.ConfigFile,
info: info,
sl: NewSublist(),
opts: opts,
done: make(chan bool, 1),
start: time.Now(),
}
s.mu.Lock()
defer s.mu.Unlock()
// For tracking clients
s.clients = make(map[uint64]*client)
// For tracking connections that are not yet registered
// in s.routes, but for which readLoop has started.
s.grTmpClients = make(map[uint64]*client)
// For tracking routes and their remote ids
s.routes = make(map[uint64]*client)
s.remotes = make(map[string]*client)
// Used to kick out all of the route
// connect Go routines.
s.rcQuit = make(chan bool)
// Used to setup Authorization.
s.configureAuthorization()
s.generateServerInfoJSON()
s.handleSignals()
return s
}
func (s *Server) getOpts() *Options {
s.optsMu.RLock()
opts := s.opts
s.optsMu.RUnlock()
return opts
}
func (s *Server) setOpts(opts *Options) {
s.optsMu.Lock()
s.opts = opts
s.optsMu.Unlock()
}
func (s *Server) generateServerInfoJSON() {
// Generate the info json
b, err := json.Marshal(s.info)
if err != nil {
s.Fatalf("Error marshaling INFO JSON: %+v\n", err)
return
}
s.infoJSON = []byte(fmt.Sprintf("INFO %s %s", b, CR_LF))
}
func (s *Server) generateRouteInfoJSON() {
b, err := json.Marshal(s.routeInfo)
if err != nil {
s.Fatalf("Error marshaling route INFO JSON: %+v\n", err)
return
}
s.routeInfoJSON = []byte(fmt.Sprintf(InfoProto, b))
}
// PrintAndDie is exported for access in other packages.
func PrintAndDie(msg string) {
fmt.Fprintf(os.Stderr, "%s\n", msg)
os.Exit(1)
}
// PrintServerAndExit will print our version and exit.
func PrintServerAndExit() {
fmt.Printf("nats-server version %s\n", VERSION)
os.Exit(0)
}
// ProcessCommandLineArgs takes the command line arguments
// validating and setting flags for handling in case any
// sub command was present.
func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error) {
if len(cmd.Args()) > 0 {
arg := cmd.Args()[0]
switch strings.ToLower(arg) {
case "version":
return true, false, nil
case "help":
return false, true, nil
default:
return false, false, fmt.Errorf("Unrecognized command: %q\n", arg)
}
}
return false, false, nil
}
// Protected check on running state
func (s *Server) isRunning() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.running
}
func (s *Server) logPid() {
pidStr := strconv.Itoa(os.Getpid())
err := ioutil.WriteFile(s.getOpts().PidFile, []byte(pidStr), 0660)
if err != nil {
PrintAndDie(fmt.Sprintf("Could not write pidfile: %v\n", err))
}
}
// Start up the server, this will block.
// Start via a Go routine if needed.
func (s *Server) Start() {
s.Noticef("Starting nats-server version %s", VERSION)
s.Debugf("Go build version %s", s.info.GoVersion)
// Avoid RACE between Start() and Shutdown()
s.mu.Lock()
s.running = true
s.mu.Unlock()
s.grMu.Lock()
s.grRunning = true
s.grMu.Unlock()
// Snapshot server options.
opts := s.getOpts()
// Log the pid to a file
if opts.PidFile != _EMPTY_ {
s.logPid()
}
// Start monitoring if needed
if err := s.StartMonitoring(); err != nil {
s.Fatalf("Can't start monitoring: %v", err)
return
}
// The Routing routine needs to wait for the client listen
// port to be opened and potential ephemeral port selected.
clientListenReady := make(chan struct{})
// Start up routing as well if needed.
if opts.Cluster.Port != 0 {
s.startGoRoutine(func() {
s.StartRouting(clientListenReady)
})
}
// Pprof http endpoint for the profiler.
if opts.ProfPort != 0 {
s.StartProfiler()
}
// Wait for clients.
s.AcceptLoop(clientListenReady)
}
// Shutdown will shutdown the server instance by kicking out the AcceptLoop
// and closing all associated clients.
func (s *Server) Shutdown() {
s.mu.Lock()
// Prevent issues with multiple calls.
if s.shutdown {
s.mu.Unlock()
return
}
s.shutdown = true
s.running = false
s.grMu.Lock()
s.grRunning = false
s.grMu.Unlock()
conns := make(map[uint64]*client)
// Copy off the clients
for i, c := range s.clients {
conns[i] = c
}
// Copy off the connections that are not yet registered
// in s.routes, but for which the readLoop has started
s.grMu.Lock()
for i, c := range s.grTmpClients {
conns[i] = c
}
s.grMu.Unlock()
// Copy off the routes
for i, r := range s.routes {
conns[i] = r
}
// Number of done channel responses we expect.
doneExpected := 0
// Kick client AcceptLoop()
if s.listener != nil {
doneExpected++
s.listener.Close()
s.listener = nil
}
// Kick route AcceptLoop()
if s.routeListener != nil {
doneExpected++
s.routeListener.Close()
s.routeListener = nil
}
// Kick HTTP monitoring if its running
if s.http != nil {
doneExpected++
s.http.Close()
s.http = nil
}
// Kick Profiling if its running
if s.profiler != nil {
doneExpected++
s.profiler.Close()
}
// Release the solicited routes connect go routines.
close(s.rcQuit)
s.mu.Unlock()
// Close client and route connections
for _, c := range conns {
c.closeConnection()
}
// Block until the accept loops exit
for doneExpected > 0 {
<-s.done
doneExpected--
}
// Wait for go routines to be done.
s.grWG.Wait()
}
// AcceptLoop is exported for easier testing.
func (s *Server) AcceptLoop(clr chan struct{}) {
// If we were to exit before the listener is setup properly,
// make sure we close the channel.
defer func() {
if clr != nil {
close(clr)
}
}()
// Snapshot server options.
opts := s.getOpts()
hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
l, e := net.Listen("tcp", hp)
if e != nil {
s.Fatalf("Error listening on port: %s, %q", hp, e)
return
}
s.Noticef("Listening for client connections on %s",
net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
// Alert of TLS enabled.
if opts.TLSConfig != nil {
s.Noticef("TLS required for client connections")
}
s.Debugf("Server id is %s", s.info.ID)
s.Noticef("Server is ready")
// Setup state that can enable shutdown
s.mu.Lock()
s.listener = l
// If server was started with RANDOM_PORT (-1), opts.Port would be equal
// to 0 at the beginning this function. So we need to get the actual port
if opts.Port == 0 {
// Write resolved port back to options.
_, port, err := net.SplitHostPort(l.Addr().String())
if err != nil {
s.Fatalf("Error parsing server address (%s): %s", l.Addr().String(), e)
s.mu.Unlock()
return
}
portNum, err := strconv.Atoi(port)
if err != nil {
s.Fatalf("Error parsing server address (%s): %s", l.Addr().String(), e)
s.mu.Unlock()
return
}
opts.Port = portNum
}
s.mu.Unlock()
// Let the caller know that we are ready
close(clr)
clr = nil
tmpDelay := ACCEPT_MIN_SLEEP
for s.isRunning() {
conn, err := l.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
s.Debugf("Temporary Client Accept Error(%v), sleeping %dms",
ne, tmpDelay/time.Millisecond)
time.Sleep(tmpDelay)
tmpDelay *= 2
if tmpDelay > ACCEPT_MAX_SLEEP {
tmpDelay = ACCEPT_MAX_SLEEP
}
} else if s.isRunning() {
s.Noticef("Accept error: %v", err)
}
continue
}
tmpDelay = ACCEPT_MIN_SLEEP
s.startGoRoutine(func() {
s.createClient(conn)
s.grWG.Done()
})
}
s.Noticef("Server Exiting..")
s.done <- true
}
// StartProfiler is called to enable dynamic profiling.
func (s *Server) StartProfiler() {
// Snapshot server options.
opts := s.getOpts()
port := opts.ProfPort
// Check for Random Port
if port == -1 {
port = 0
}
hp := net.JoinHostPort(opts.Host, strconv.Itoa(port))
l, err := net.Listen("tcp", hp)
s.Noticef("profiling port: %d", l.Addr().(*net.TCPAddr).Port)
if err != nil {
s.Fatalf("error starting profiler: %s", err)
}
srv := &http.Server{
Addr: hp,
Handler: http.DefaultServeMux,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.profiler = l
s.mu.Unlock()
go func() {
// if this errors out, it's probably because the server is being shutdown
err := srv.Serve(l)
if err != nil {
s.Fatalf("error starting profiler: %s", err)
}
s.done <- true
}()
}
// StartHTTPMonitoring will enable the HTTP monitoring port.
// DEPRECATED: Should use StartMonitoring.
func (s *Server) StartHTTPMonitoring() {
s.startMonitoring(false)
}
// StartHTTPSMonitoring will enable the HTTPS monitoring port.
// DEPRECATED: Should use StartMonitoring.
func (s *Server) StartHTTPSMonitoring() {
s.startMonitoring(true)
}
// StartMonitoring starts the HTTP or HTTPs server if needed.
func (s *Server) StartMonitoring() error {
// Snapshot server options.
opts := s.getOpts()
// Specifying both HTTP and HTTPS ports is a misconfiguration
if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
}
var err error
if opts.HTTPPort != 0 {
err = s.startMonitoring(false)
} else if opts.HTTPSPort != 0 {
if opts.TLSConfig == nil {
return fmt.Errorf("TLS cert and key required for HTTPS")
}
err = s.startMonitoring(true)
}
return err
}
// HTTP endpoints
const (
RootPath = "/"
VarzPath = "/varz"
ConnzPath = "/connz"
RoutezPath = "/routez"
SubszPath = "/subsz"
StackszPath = "/stacksz"
)
// Start the monitoring server
func (s *Server) startMonitoring(secure bool) error {
// Snapshot server options.
opts := s.getOpts()
// Used to track HTTP requests
s.httpReqStats = map[string]uint64{
RootPath: 0,
VarzPath: 0,
ConnzPath: 0,
RoutezPath: 0,
SubszPath: 0,
}
var (
hp string
err error
httpListener net.Listener
port int
)
monitorProtocol := "http"
if secure {
monitorProtocol += "s"
port = opts.HTTPSPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
config := util.CloneTLSConfig(opts.TLSConfig)
config.ClientAuth = tls.NoClientCert
httpListener, err = tls.Listen("tcp", hp, config)
} else {
port = opts.HTTPPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
httpListener, err = net.Listen("tcp", hp)
}
if err != nil {
return fmt.Errorf("can't listen to the monitor port: %v", err)
}
s.Noticef("Starting %s monitor on %s", monitorProtocol,
net.JoinHostPort(opts.HTTPHost, strconv.Itoa(httpListener.Addr().(*net.TCPAddr).Port)))
mux := http.NewServeMux()
// Root
mux.HandleFunc(RootPath, s.HandleRoot)
// Varz
mux.HandleFunc(VarzPath, s.HandleVarz)
// Connz
mux.HandleFunc(ConnzPath, s.HandleConnz)
// Routez
mux.HandleFunc(RoutezPath, s.HandleRoutez)
// Subz
mux.HandleFunc(SubszPath, s.HandleSubsz)
// Subz alias for backwards compatibility
mux.HandleFunc("/subscriptionsz", s.HandleSubsz)
// Stacksz
mux.HandleFunc(StackszPath, s.HandleStacksz)
srv := &http.Server{
Addr: hp,
Handler: mux,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.http = httpListener
s.httpHandler = mux
s.mu.Unlock()
go func() {
srv.Serve(httpListener)
srv.Handler = nil
s.mu.Lock()
s.httpHandler = nil
s.mu.Unlock()
s.done <- true
}()
return nil
}
// HTTPHandler returns the http.Handler object used to handle monitoring
// endpoints. It will return nil if the server is not configured for
// monitoring, or if the server has not been started yet (Server.Start()).
func (s *Server) HTTPHandler() http.Handler {
s.mu.Lock()
defer s.mu.Unlock()
return s.httpHandler
}
func (s *Server) createClient(conn net.Conn) *client {
c := &client{srv: s, nc: conn, opts: defaultOpts, mpay: s.info.MaxPayload, start: time.Now()}
// Grab JSON info string
s.mu.Lock()
info := s.infoJSON
authRequired := s.info.AuthRequired
tlsRequired := s.info.TLSRequired
s.totalClients++
s.mu.Unlock()
// Grab lock
c.mu.Lock()
// Initialize
c.initClient()
c.Debugf("Client connection created")
// Send our information.
c.sendInfo(info)
// Unlock to register
c.mu.Unlock()
// Register with the server.
s.mu.Lock()
// If server is not running, Shutdown() may have already gathered the
// list of connections to close. It won't contain this one, so we need
// to bail out now otherwise the readLoop started down there would not
// be interrupted.
if !s.running {
s.mu.Unlock()
return c
}
// Snapshot server options.
opts := s.getOpts()
// If there is a max connections specified, check that adding
// this new client would not push us over the max
if opts.MaxConn > 0 && len(s.clients) >= opts.MaxConn {
s.mu.Unlock()
c.maxConnExceeded()
return nil
}
s.clients[c.cid] = c
s.mu.Unlock()
// Re-Grab lock
c.mu.Lock()
// Check for TLS
if tlsRequired {
c.Debugf("Starting TLS client connection handshake")
c.nc = tls.Server(c.nc, opts.TLSConfig)
conn := c.nc.(*tls.Conn)
// Setup the timeout
ttl := secondsToDuration(opts.TLSTimeout)
time.AfterFunc(ttl, func() { tlsTimeout(c, conn) })
conn.SetReadDeadline(time.Now().Add(ttl))
// Force handshake
c.mu.Unlock()
if err := conn.Handshake(); err != nil {
c.Debugf("TLS handshake error: %v", err)
c.sendErr("Secure Connection - TLS Required")
c.closeConnection()
return nil
}
// Reset the read deadline
conn.SetReadDeadline(time.Time{})
// Re-Grab lock
c.mu.Lock()
}
// The connection may have been closed
if c.nc == nil {
c.mu.Unlock()
return c
}
// Check for Auth. We schedule this timer after the TLS handshake to avoid
// the race where the timer fires during the handshake and causes the
// server to write bad data to the socket. See issue #432.
if authRequired {
c.setAuthTimer(secondsToDuration(opts.AuthTimeout))
}
if tlsRequired {
// Rewrap bw
c.bw = bufio.NewWriterSize(c.nc, startBufSize)
}
// Do final client initialization
// Set the Ping timer
c.setPingTimer()
// Spin up the read loop.
s.startGoRoutine(func() { c.readLoop() })
if tlsRequired {
c.Debugf("TLS handshake complete")
cs := c.nc.(*tls.Conn).ConnectionState()
c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tlsCipher(cs.CipherSuite))
}
c.mu.Unlock()
return c
}
// updateServerINFO updates the server's Info object with the given
// array of URLs and re-generate the infoJSON byte array, only if the
// given URLs were not already recorded and if the feature is not
// disabled.
// Returns a boolean indicating if server's Info was updated.
func (s *Server) updateServerINFO(urls []string) bool {
s.mu.Lock()
defer s.mu.Unlock()
// Feature disabled, do not update.
if s.getOpts().Cluster.NoAdvertise {
return false
}
// Will be set to true if we alter the server's Info object.
wasUpdated := false
for _, url := range urls {
if _, present := s.info.clientConnectURLs[url]; !present {
s.info.clientConnectURLs[url] = struct{}{}
s.info.ClientConnectURLs = append(s.info.ClientConnectURLs, url)
wasUpdated = true
}
}
if wasUpdated {
s.generateServerInfoJSON()
}
return wasUpdated
}
// Handle closing down a connection when the handshake has timedout.
func tlsTimeout(c *client, conn *tls.Conn) {
c.mu.Lock()
nc := c.nc
c.mu.Unlock()
// Check if already closed
if nc == nil {
return
}
cs := conn.ConnectionState()
if !cs.HandshakeComplete {
c.Debugf("TLS handshake timeout")
c.sendErr("Secure Connection - TLS Required")
c.closeConnection()
}
}
// Seems silly we have to write these
func tlsVersion(ver uint16) string {
switch ver {
case tls.VersionTLS10:
return "1.0"
case tls.VersionTLS11:
return "1.1"
case tls.VersionTLS12:
return "1.2"
}
return fmt.Sprintf("Unknown [%x]", ver)
}
// We use hex here so we don't need multiple versions
func tlsCipher(cs uint16) string {
switch cs {
case 0x0005:
return "TLS_RSA_WITH_RC4_128_SHA"
case 0x000a:
return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"
case 0x002f:
return "TLS_RSA_WITH_AES_128_CBC_SHA"
case 0x0035:
return "TLS_RSA_WITH_AES_256_CBC_SHA"
case 0xc007:
return "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"
case 0xc009:
return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"
case 0xc00a:
return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"
case 0xc011:
return "TLS_ECDHE_RSA_WITH_RC4_128_SHA"
case 0xc012:
return "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"
case 0xc013:
return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
case 0xc014:
return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
case 0xc02f:
return "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
case 0xc02b:
return "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"
case 0xc030:
return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
case 0xc02c:
return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
}
return fmt.Sprintf("Unknown [%x]", cs)
}
// Remove a client or route from our internal accounting.
func (s *Server) removeClient(c *client) {
var rID string
c.mu.Lock()
cid := c.cid
typ := c.typ
r := c.route
if r != nil {
rID = r.remoteID
}
updateProtoInfoCount := false
if typ == CLIENT && c.opts.Protocol >= ClientProtoInfo {
updateProtoInfoCount = true
}
c.mu.Unlock()
s.mu.Lock()
switch typ {
case CLIENT:
delete(s.clients, cid)
if updateProtoInfoCount {
s.cproto--
}
case ROUTER:
delete(s.routes, cid)
if r != nil {
rc, ok := s.remotes[rID]
// Only delete it if it is us..
if ok && c == rc {
delete(s.remotes, rID)
}
}
}
s.mu.Unlock()
}
/////////////////////////////////////////////////////////////////
// These are some helpers for accounting in functional tests.
/////////////////////////////////////////////////////////////////
// NumRoutes will report the number of registered routes.
func (s *Server) NumRoutes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.routes)
}
// NumRemotes will report number of registered remotes.
func (s *Server) NumRemotes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.remotes)
}
// NumClients will report the number of registered clients.
func (s *Server) NumClients() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.clients)
}
// NumSubscriptions will report how many subscriptions are active.
func (s *Server) NumSubscriptions() uint32 {
s.mu.Lock()
subs := s.sl.Count()
s.mu.Unlock()
return subs
}
// Addr will return the net.Addr object for the current listener.
func (s *Server) Addr() net.Addr {
s.mu.Lock()
defer s.mu.Unlock()
if s.listener == nil {
return nil
}
return s.listener.Addr()
}
// MonitorAddr will return the net.Addr object for the monitoring listener.
func (s *Server) MonitorAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.http == nil {
return nil
}
return s.http.Addr().(*net.TCPAddr)
}
// RouteAddr returns the net.Addr object for the route listener.
func (s *Server) ClusterAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.routeListener == nil {
return nil
}
return s.routeListener.Addr().(*net.TCPAddr)
}
// ReadyForConnections returns `true` if the server is ready to accept client
// and, if routing is enabled, route connections. If after the duration
// `dur` the server is still not ready, returns `false`.
func (s *Server) ReadyForConnections(dur time.Duration) bool {
// Snapshot server options.
opts := s.getOpts()
end := time.Now().Add(dur)
for time.Now().Before(end) {
s.mu.Lock()
ok := s.listener != nil && (opts.Cluster.Port == 0 || s.routeListener != nil)
s.mu.Unlock()
if ok {
return true
}
time.Sleep(25 * time.Millisecond)
}
return false
}
// ID returns the server's ID
func (s *Server) ID() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.info.ID
}
func (s *Server) startGoRoutine(f func()) {
s.grMu.Lock()
if s.grRunning {
s.grWG.Add(1)
go f()
}
s.grMu.Unlock()
}
// getClientConnectURLs returns suitable URLs for clients to connect to the listen
// port based on the server options' Host and Port. If the Host corresponds to
// "any" interfaces, this call returns the list of resolved IP addresses.
func (s *Server) getClientConnectURLs() []string {
// Snapshot server options.
opts := s.getOpts()
s.mu.Lock()
defer s.mu.Unlock()
sPort := strconv.Itoa(opts.Port)
urls := make([]string, 0, 1)
ipAddr, err := net.ResolveIPAddr("ip", opts.Host)
// If the host is "any" (0.0.0.0 or ::), get specific IPs from available
// interfaces.
if err == nil && ipAddr.IP.IsUnspecified() {
var ip net.IP
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
// Skip non global unicast addresses
if !ip.IsGlobalUnicast() || ip.IsUnspecified() {
ip = nil
continue
}
urls = append(urls, net.JoinHostPort(ip.String(), sPort))
}
}
}
if err != nil || len(urls) == 0 {
// We are here if s.opts.Host is not "0.0.0.0" nor "::", or if for some
// reason we could not add any URL in the loop above.
// We had a case where a Windows VM was hosed and would have err == nil
// and not add any address in the array in the loop above, and we
// ended-up returning 0.0.0.0, which is problematic for Windows clients.
// Check for 0.0.0.0 or :: specifically, and ignore if that's the case.
if opts.Host == "0.0.0.0" || opts.Host == "::" {
s.Errorf("Address %q can not be resolved properly", opts.Host)
} else {
urls = append(urls, net.JoinHostPort(opts.Host, sPort))
}
}
return urls
}
| 1 | 7,133 | Again, would not change that. | nats-io-nats-server | go |
@@ -98,4 +98,16 @@ public enum Status {
return false;
}
}
+
+ public static boolean isStatusFailed(Status status) {
+ switch (status) {
+ case FAILED:
+ case KILLED:
+ case CANCELLED:
+ case FAILED_FINISHING:
+ return true;
+ default:
+ return false;
+ }
+ }
} | 1 | /*
* Copyright 2014 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;
public enum Status {
READY(10),
PREPARING(20),
RUNNING(30),
PAUSED(40),
SUCCEEDED(50),
KILLED(60),
FAILED(70),
FAILED_FINISHING(80),
SKIPPED(90),
DISABLED(100),
QUEUED(110),
FAILED_SUCCEEDED(120),
CANCELLED(130);
private int numVal;
Status(int numVal) {
this.numVal = numVal;
}
public int getNumVal() {
return numVal;
}
public static Status fromInteger(int x) {
switch (x) {
case 10:
return READY;
case 20:
return PREPARING;
case 30:
return RUNNING;
case 40:
return PAUSED;
case 50:
return SUCCEEDED;
case 60:
return KILLED;
case 70:
return FAILED;
case 80:
return FAILED_FINISHING;
case 90:
return SKIPPED;
case 100:
return DISABLED;
case 110:
return QUEUED;
case 120:
return FAILED_SUCCEEDED;
case 130:
return CANCELLED;
default:
return READY;
}
}
public static boolean isStatusFinished(Status status) {
switch (status) {
case FAILED:
case KILLED:
case SUCCEEDED:
case SKIPPED:
case FAILED_SUCCEEDED:
case CANCELLED:
return true;
default:
return false;
}
}
public static boolean isStatusRunning(Status status) {
switch (status) {
case RUNNING:
case FAILED_FINISHING:
case QUEUED:
return true;
default:
return false;
}
}
}
| 1 | 12,346 | Is canceled considered failed? | azkaban-azkaban | java |
@@ -300,7 +300,7 @@ func TestBrowseJson(t *testing.T) {
req.Header.Set("Accept", "application/json")
rec := httptest.NewRecorder()
- code, err := b.ServeHTTP(rec, req)
+ code, _ := b.ServeHTTP(rec, req)
if code != http.StatusOK {
t.Fatalf("In test %d: Wrong status, expected %d, got %d", i, http.StatusOK, code) | 1 | package browse
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"sort"
"testing"
"text/template"
"time"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
func TestSort(t *testing.T) {
// making up []fileInfo with bogus values;
// to be used to make up our "listing"
fileInfos := []FileInfo{
{
Name: "fizz",
Size: 4,
ModTime: time.Now().AddDate(-1, 1, 0),
},
{
Name: "buzz",
Size: 2,
ModTime: time.Now().AddDate(0, -3, 3),
},
{
Name: "bazz",
Size: 1,
ModTime: time.Now().AddDate(0, -2, -23),
},
{
Name: "jazz",
Size: 3,
ModTime: time.Now(),
},
}
listing := Listing{
Name: "foobar",
Path: "/fizz/buzz",
CanGoUp: false,
Items: fileInfos,
}
// sort by name
listing.Sort = "name"
listing.applySort()
if !sort.IsSorted(byName(listing)) {
t.Errorf("The listing isn't name sorted: %v", listing.Items)
}
// sort by size
listing.Sort = "size"
listing.applySort()
if !sort.IsSorted(bySize(listing)) {
t.Errorf("The listing isn't size sorted: %v", listing.Items)
}
// sort by Time
listing.Sort = "time"
listing.applySort()
if !sort.IsSorted(byTime(listing)) {
t.Errorf("The listing isn't time sorted: %v", listing.Items)
}
// reverse by name
listing.Sort = "name"
listing.Order = "desc"
listing.applySort()
if !isReversed(byName(listing)) {
t.Errorf("The listing isn't reversed by name: %v", listing.Items)
}
// reverse by size
listing.Sort = "size"
listing.Order = "desc"
listing.applySort()
if !isReversed(bySize(listing)) {
t.Errorf("The listing isn't reversed by size: %v", listing.Items)
}
// reverse by time
listing.Sort = "time"
listing.Order = "desc"
listing.applySort()
if !isReversed(byTime(listing)) {
t.Errorf("The listing isn't reversed by time: %v", listing.Items)
}
}
func TestBrowseHTTPMethods(t *testing.T) {
tmpl, err := template.ParseFiles("testdata/photos.tpl")
if err != nil {
t.Fatalf("An error occured while parsing the template: %v", err)
}
b := Browse{
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return http.StatusTeapot, nil // not t.Fatalf, or we will not see what other methods yield
}),
Configs: []Config{
{
PathScope: "/photos",
Root: http.Dir("./testdata"),
Template: tmpl,
},
},
}
rec := httptest.NewRecorder()
for method, expected := range map[string]int{
http.MethodGet: http.StatusOK,
http.MethodHead: http.StatusOK,
http.MethodOptions: http.StatusNotImplemented,
"PROPFIND": http.StatusNotImplemented,
} {
req, err := http.NewRequest(method, "/photos/", nil)
if err != nil {
t.Fatalf("Test: Could not create HTTP request: %v", err)
}
code, _ := b.ServeHTTP(rec, req)
if code != expected {
t.Errorf("Wrong status with HTTP Method %s: expected %d, got %d", method, expected, code)
}
}
}
func TestBrowseTemplate(t *testing.T) {
tmpl, err := template.ParseFiles("testdata/photos.tpl")
if err != nil {
t.Fatalf("An error occured while parsing the template: %v", err)
}
b := Browse{
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
t.Fatalf("Next shouldn't be called")
return 0, nil
}),
Configs: []Config{
{
PathScope: "/photos",
Root: http.Dir("./testdata"),
Template: tmpl,
},
},
}
req, err := http.NewRequest("GET", "/photos/", nil)
if err != nil {
t.Fatalf("Test: Could not create HTTP request: %v", err)
}
rec := httptest.NewRecorder()
code, _ := b.ServeHTTP(rec, req)
if code != http.StatusOK {
t.Fatalf("Wrong status, expected %d, got %d", http.StatusOK, code)
}
respBody := rec.Body.String()
expectedBody := `<!DOCTYPE html>
<html>
<head>
<title>Template</title>
</head>
<body>
<h1>Header</h1>
<h1>/photos/</h1>
<a href="./test.html">test.html</a><br>
<a href="./test2.html">test2.html</a><br>
<a href="./test3.html">test3.html</a><br>
</body>
</html>
`
if respBody != expectedBody {
t.Fatalf("Expected body: %v got: %v", expectedBody, respBody)
}
}
func TestBrowseJson(t *testing.T) {
b := Browse{
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
t.Fatalf("Next shouldn't be called")
return 0, nil
}),
Configs: []Config{
{
PathScope: "/photos/",
Root: http.Dir("./testdata"),
},
},
}
//Getting the listing from the ./testdata/photos, the listing returned will be used to validate test results
testDataPath := filepath.Join("./testdata", "photos")
file, err := os.Open(testDataPath)
if err != nil {
if os.IsPermission(err) {
t.Fatalf("Os Permission Error")
}
}
defer file.Close()
files, err := file.Readdir(-1)
if err != nil {
t.Fatalf("Unable to Read Contents of the directory")
}
var fileinfos []FileInfo
for i, f := range files {
name := f.Name()
// Tests fail in CI environment because all file mod times are the same for
// some reason, making the sorting unpredictable. To hack around this,
// we ensure here that each file has a different mod time.
chTime := f.ModTime().UTC().Add(-(time.Duration(i) * time.Second))
if err := os.Chtimes(filepath.Join(testDataPath, name), chTime, chTime); err != nil {
t.Fatal(err)
}
if f.IsDir() {
name += "/"
}
url := url.URL{Path: "./" + name}
fileinfos = append(fileinfos, FileInfo{
IsDir: f.IsDir(),
Name: f.Name(),
Size: f.Size(),
URL: url.String(),
ModTime: chTime,
Mode: f.Mode(),
})
}
listing := Listing{Items: fileinfos} // this listing will be used for validation inside the tests
tests := []struct {
QueryURL string
SortBy string
OrderBy string
Limit int
shouldErr bool
expectedResult []FileInfo
}{
//test case 1: testing for default sort and order and without the limit parameter, default sort is by name and the default order is ascending
//without the limit query entire listing will be produced
{"/", "", "", -1, false, listing.Items},
//test case 2: limit is set to 1, orderBy and sortBy is default
{"/?limit=1", "", "", 1, false, listing.Items[:1]},
//test case 3 : if the listing request is bigger than total size of listing then it should return everything
{"/?limit=100000000", "", "", 100000000, false, listing.Items},
//test case 4 : testing for negative limit
{"/?limit=-1", "", "", -1, false, listing.Items},
//test case 5 : testing with limit set to -1 and order set to descending
{"/?limit=-1&order=desc", "", "desc", -1, false, listing.Items},
//test case 6 : testing with limit set to 2 and order set to descending
{"/?limit=2&order=desc", "", "desc", 2, false, listing.Items},
//test case 7 : testing with limit set to 3 and order set to descending
{"/?limit=3&order=desc", "", "desc", 3, false, listing.Items},
//test case 8 : testing with limit set to 3 and order set to ascending
{"/?limit=3&order=asc", "", "asc", 3, false, listing.Items},
//test case 9 : testing with limit set to 1111111 and order set to ascending
{"/?limit=1111111&order=asc", "", "asc", 1111111, false, listing.Items},
//test case 10 : testing with limit set to default and order set to ascending and sorting by size
{"/?order=asc&sort=size", "size", "asc", -1, false, listing.Items},
//test case 11 : testing with limit set to default and order set to ascending and sorting by last modified
{"/?order=asc&sort=time", "time", "asc", -1, false, listing.Items},
//test case 12 : testing with limit set to 1 and order set to ascending and sorting by last modified
{"/?order=asc&sort=time&limit=1", "time", "asc", 1, false, listing.Items},
//test case 13 : testing with limit set to -100 and order set to ascending and sorting by last modified
{"/?order=asc&sort=time&limit=-100", "time", "asc", -100, false, listing.Items},
//test case 14 : testing with limit set to -100 and order set to ascending and sorting by size
{"/?order=asc&sort=size&limit=-100", "size", "asc", -100, false, listing.Items},
}
for i, test := range tests {
var marsh []byte
req, err := http.NewRequest("GET", "/photos"+test.QueryURL, nil)
if err == nil && test.shouldErr {
t.Errorf("Test %d didn't error, but it should have", i)
} else if err != nil && !test.shouldErr {
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
}
req.Header.Set("Accept", "application/json")
rec := httptest.NewRecorder()
code, err := b.ServeHTTP(rec, req)
if code != http.StatusOK {
t.Fatalf("In test %d: Wrong status, expected %d, got %d", i, http.StatusOK, code)
}
if rec.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {
t.Fatalf("Expected Content type to be application/json; charset=utf-8, but got %s ", rec.HeaderMap.Get("Content-Type"))
}
actualJSONResponse := rec.Body.String()
copyOflisting := listing
if test.SortBy == "" {
copyOflisting.Sort = "name"
} else {
copyOflisting.Sort = test.SortBy
}
if test.OrderBy == "" {
copyOflisting.Order = "asc"
} else {
copyOflisting.Order = test.OrderBy
}
copyOflisting.applySort()
limit := test.Limit
if limit <= len(copyOflisting.Items) && limit > 0 {
marsh, err = json.Marshal(copyOflisting.Items[:limit])
} else { // if the 'limit' query is empty, or has the wrong value, list everything
marsh, err = json.Marshal(copyOflisting.Items)
}
if err != nil {
t.Fatalf("Unable to Marshal the listing ")
}
expectedJSON := string(marsh)
if actualJSONResponse != expectedJSON {
t.Errorf("JSON response doesn't match the expected for test number %d with sort=%s, order=%s\nExpected response %s\nActual response = %s\n",
i+1, test.SortBy, test.OrderBy, expectedJSON, actualJSONResponse)
}
}
}
// "sort" package has "IsSorted" function, but no "IsReversed";
func isReversed(data sort.Interface) bool {
n := data.Len()
for i := n - 1; i > 0; i-- {
if !data.Less(i, i-1) {
return false
}
}
return true
}
| 1 | 8,966 | These ineffectual assignment changes intrigue me. Our CI tests have been checking for these for months; how come the tests haven't been failing? How did you catch these? | caddyserver-caddy | go |
@@ -103,10 +103,15 @@ func TestMintX509CA(t *testing.T) {
wrapper := Wrap(upstreamCA)
// Request Mint to wrapper
- resp, err := wrapper.MintX509CA(ctx, &MintX509CARequest{
+ stream, err := wrapper.MintX509CA(ctx, &MintX509CARequest{
Csr: testCase.csr,
PreferredTtl: testCase.preferredTTL,
})
+ // Stream returned, and no error expected
+ require.NoError(t, err)
+ require.NotNil(t, stream)
+
+ resp, err := stream.Recv()
// if test case expect an error validates it has expected code and message
if testCase.err != "" { | 1 | package upstreamauthority
import (
"context"
"encoding/pem"
"errors"
"testing"
"github.com/spiffe/spire/pkg/server/plugin/upstreamca"
"github.com/spiffe/spire/test/spiretest"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
)
var (
ctx = context.Background()
ca1 = pemBytes([]byte(`-----BEGIN CERTIFICATE-----
MIIBVzCB4gIJAJur7ujAmyDhMA0GCSqGSIb3DQEBCwUAMBMxETAPBgNVBAMMCFRF
U1RST09UMB4XDTE4MTAxNTE4NDQxMVoXDTE5MTAxNTE4NDQxMVowEzERMA8GA1UE
AwwIVEVTVFJPT1QwfDANBgkqhkiG9w0BAQEFAANrADBoAmEAoYPq4DlrjDhanDM4
gDbEefDYi4IOmwUkQPAiJgQ2+CRm/pb/qc2zuj5FQZps1jxt3VtoDJnwfJuX6B4M
Zq0dHJF0ykfVonfxJbQsynge7yYA1avCLjlOv72Sk9/U8UQhAgMBAAEwDQYJKoZI
hvcNAQELBQADYQAXWlJO3EoYW3Uss0QjlqJJCC2M21HkF1AkWP6mUDgQ0PtbH2Vu
P58nzUo3Kzc3mfg3hocdt7vCDm75zdhjoDTLrT9IgU2XbDcbZF+yg51HZstonDiM
3JzUe9WQUljuQlM=
-----END CERTIFICATE-----
`))
ca2 = pemBytes([]byte(`-----BEGIN CERTIFICATE-----
MIIBWTCB5AIJAOIaaEWcPCB2MA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNVBAMMCVRF
U1RST09UMjAeFw0xODEwMTUxODQ0MjdaFw0xOTEwMTUxODQ0MjdaMBQxEjAQBgNV
BAMMCVRFU1RST09UMjB8MA0GCSqGSIb3DQEBAQUAA2sAMGgCYQCmsAlaUc8YCFs5
hl44gZ3CJvpR0Yc4DAQkgSfed06iN0rmBuQzeCl3hiJ9ogqw4va2ciVQ8hTPeMw6
047YCMKOkmhDa4dFgGzk9GlvUQF5qft1MTWYlCI6/jEfx4Zsd4ECAwEAATANBgkq
hkiG9w0BAQsFAANhADQochC62F37uubcBDR70qhJlC7Bsz/KgxtduQR4pSOj4uZh
zFHHu+k8dS32+KooMqtUp71bhMgtlvYIRay4OMD6VurfP70caOHkCVFPxibAW9o9
NbyKVndd7aGvTed1PQ==
-----END CERTIFICATE-----
`))
)
func TestMintX509CA(t *testing.T) {
testCases := []struct {
// Test case name
name string
// Expected error
err string
// Certificate signing request presented to upstreamCA
csr []byte
// Preferred TTL presented to upstreamCA
preferredTTL int32
// Error returned from upstreamCA
upstreamErr error
// Cert chain returned by upstreamCA
certChain [][]byte
// Bundle returned by upstreamCA
bundle [][]byte
}{
{
name: "upstream success",
csr: []byte("some csr"),
preferredTTL: 1,
certChain: [][]byte{ca1, ca2},
bundle: [][]byte{ca1, ca2},
},
{
name: "upstreamca returns error",
csr: []byte("some csr"),
err: "upstreamauthority-wrapper: unable to submit csr: some error",
upstreamErr: errors.New("some error"),
},
{
name: "upstreamca invalid cert chain",
csr: []byte("some csr"),
err: "upstreamauthority-wrapper: unable to parse cert chain",
certChain: [][]byte{[]byte("some invalid certchain")},
bundle: [][]byte{ca1},
},
{
name: "upstreamca invalid bundle",
csr: []byte("some csr"),
err: "upstreamauthority-wrapper: unable to parse bundle",
certChain: [][]byte{ca2},
bundle: [][]byte{[]byte("some invalid certchain")},
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
// Create a fake upstream, it will return error or CAs depending expected result
upstreamCA := &fakeUpstreamCA{
t: t,
csr: testCase.csr,
preferredTTL: testCase.preferredTTL,
err: testCase.upstreamErr,
certChain: testCase.certChain,
bundle: testCase.bundle,
}
// Create wrapper using fake UpstreamCA
wrapper := Wrap(upstreamCA)
// Request Mint to wrapper
resp, err := wrapper.MintX509CA(ctx, &MintX509CARequest{
Csr: testCase.csr,
PreferredTtl: testCase.preferredTTL,
})
// if test case expect an error validates it has expected code and message
if testCase.err != "" {
spiretest.RequireGRPCStatusContains(t, err, codes.Internal, testCase.err)
return
}
// No error expected and response must not be nil
require.NoError(t, err)
require.NotNil(t, resp)
// Mint must return an array of []byte, instead of a single []byte
require.Equal(t, testCase.certChain, resp.X509CaChain)
require.Equal(t, testCase.bundle, resp.UpstreamX509Roots)
})
}
}
func TestPublishJWTKey(t *testing.T) {
wrapper := Wrap(&fakeUpstreamCA{})
resp, err := wrapper.PublishJWTKey(ctx, &PublishJWTKeyRequest{})
require.Nil(t, resp, "no response expected")
spiretest.RequireGRPCStatus(t, err, codes.Unimplemented, "upstreamauthority-wrapper: publishing upstream is unsupported")
}
// fakeUpstreamCA is a custom UpstreamCA that returns error or response depending on its configurations
type fakeUpstreamCA struct {
t *testing.T
// request parameters
csr []byte
preferredTTL int32
// fake will return error as response of SubmitCSR in case it is defined
err error
certChain [][]byte
bundle [][]byte
}
// SubmitCSR process fake configurations in order to return an error or certChain and bundle in a single []byte
// it validates if request provided expected values
func (f *fakeUpstreamCA) SubmitCSR(ctx context.Context, req *upstreamca.SubmitCSRRequest) (*upstreamca.SubmitCSRResponse, error) {
// Returns error if it is expected
if f.err != nil {
return nil, f.err
}
// Validates request
require.Equal(f.t, f.csr, req.Csr)
require.Equal(f.t, f.preferredTTL, req.PreferredTtl)
// Concatenate certChain into a single []byte
var certChain []byte
for _, b := range f.certChain {
certChain = append(certChain, b...)
}
// Concatenate certChain into a single []byte
var bundle []byte
for _, b := range f.bundle {
bundle = append(bundle, b...)
}
return &upstreamca.SubmitCSRResponse{
SignedCertificate: &upstreamca.SignedCertificate{
CertChain: certChain,
Bundle: bundle,
},
}, nil
}
func pemBytes(p []byte) []byte {
b, _ := pem.Decode(p)
if b != nil {
return b.Bytes
}
return nil
}
| 1 | 12,991 | We should add an additional call to Recv() somewhere after here that we assert returns io.EOF. | spiffe-spire | go |
@@ -35,7 +35,8 @@ func setupJournalBlockServerTest(t *testing.T) (
// Clean up the config if the rest of the setup fails.
defer func() {
if !setupSucceeded {
- CheckConfigAndShutdown(t, config)
+ ctx := context.Background()
+ CheckConfigAndShutdown(ctx, t, config)
}
}()
| 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
import (
"os"
"testing"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/ioutil"
"github.com/keybase/kbfs/tlf"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
)
func setupJournalBlockServerTest(t *testing.T) (
tempdir string, config *ConfigLocal, jServer *JournalServer) {
tempdir, err := ioutil.TempDir(os.TempDir(), "journal_block_server")
require.NoError(t, err)
// Clean up the tempdir if the rest of the setup fails.
setupSucceeded := false
defer func() {
if !setupSucceeded {
err := ioutil.RemoveAll(tempdir)
assert.NoError(t, err)
}
}()
config = MakeTestConfigOrBust(t, "test_user")
// Clean up the config if the rest of the setup fails.
defer func() {
if !setupSucceeded {
CheckConfigAndShutdown(t, config)
}
}()
config.EnableJournaling(tempdir, TLFJournalBackgroundWorkEnabled)
jServer, err = GetJournalServer(config)
require.NoError(t, err)
blockServer := jServer.blockServer()
// Turn this on for testing.
blockServer.enableAddBlockReference = true
config.SetBlockServer(blockServer)
setupSucceeded = true
return tempdir, config, jServer
}
func teardownJournalBlockServerTest(
t *testing.T, tempdir string, config Config) {
CheckConfigAndShutdown(t, config)
err := ioutil.RemoveAll(tempdir)
assert.NoError(t, err)
}
type shutdownOnlyBlockServer struct{ BlockServer }
func (shutdownOnlyBlockServer) Shutdown() {}
func TestJournalBlockServerPutGetAddReference(t *testing.T) {
tempdir, config, jServer := setupJournalBlockServerTest(t)
defer teardownJournalBlockServerTest(t, tempdir, config)
// Use a shutdown-only BlockServer so that it errors if the
// journal tries to access it.
jServer.delegateBlockServer = shutdownOnlyBlockServer{}
ctx := context.Background()
tlfID := tlf.FakeID(2, false)
err := jServer.Enable(ctx, tlfID, TLFJournalBackgroundWorkPaused)
require.NoError(t, err)
blockServer := config.BlockServer()
crypto := config.Crypto()
uid1 := keybase1.MakeTestUID(1)
bCtx := BlockContext{uid1, "", ZeroBlockRefNonce}
data := []byte{1, 2, 3, 4}
bID, err := crypto.MakePermanentBlockID(data)
require.NoError(t, err)
// Put a block.
serverHalf, err := crypto.MakeRandomBlockCryptKeyServerHalf()
require.NoError(t, err)
err = blockServer.Put(ctx, tlfID, bID, bCtx, data, serverHalf)
require.NoError(t, err)
// Now get the same block back.
buf, key, err := blockServer.Get(ctx, tlfID, bID, bCtx)
require.NoError(t, err)
require.Equal(t, data, buf)
require.Equal(t, serverHalf, key)
// Add a reference.
uid2 := keybase1.MakeTestUID(2)
nonce, err := crypto.MakeBlockRefNonce()
require.NoError(t, err)
bCtx2 := BlockContext{uid1, uid2, nonce}
err = blockServer.AddBlockReference(ctx, tlfID, bID, bCtx2)
require.NoError(t, err)
// Now get the same block back.
buf, key, err = blockServer.Get(ctx, tlfID, bID, bCtx2)
require.NoError(t, err)
require.Equal(t, data, buf)
require.Equal(t, serverHalf, key)
}
| 1 | 15,020 | Why not return a `ctx` from `setupJournalBlockServerTest` and use it everywhere, like in the other test files? And maybe put a test timeout on it while you're at it? (Same for the other journal test files below.) | keybase-kbfs | go |
@@ -33,7 +33,17 @@
// ObjectTracker undestroyed objects validation function
-bool ObjectLifetimes::ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {
+bool ObjectLifetimes::ReportUndestroyedInstanceObjects(VkInstance instance, const std::string& error_code) {
+ bool skip = false;
+ skip |= InstanceReportUndestroyedObjects(instance, kVulkanObjectTypeSurfaceKHR, error_code);
+ skip |= InstanceReportUndestroyedObjects(instance, kVulkanObjectTypeSwapchainKHR, error_code);
+ skip |= InstanceReportUndestroyedObjects(instance, kVulkanObjectTypeDisplayKHR, error_code);
+ skip |= InstanceReportUndestroyedObjects(instance, kVulkanObjectTypeDisplayModeKHR, error_code);
+ skip |= InstanceReportUndestroyedObjects(instance, kVulkanObjectTypeDebugReportCallbackEXT, error_code);
+ skip |= InstanceReportUndestroyedObjects(instance, kVulkanObjectTypeDebugUtilsMessengerEXT, error_code);
+ return skip;
+}
+bool ObjectLifetimes::ReportUndestroyedDeviceObjects(VkDevice device, const std::string& error_code) {
bool skip = false;
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeSemaphore, error_code); | 1 | // *** THIS FILE IS GENERATED - DO NOT EDIT ***
// See object_tracker_generator.py for modifications
/***************************************************************************
*
* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
* Copyright (c) 2015-2019 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.
*
* Author: Mark Lobodzinski <mark@lunarg.com>
* Author: Dave Houlton <daveh@lunarg.com>
*
****************************************************************************/
#include "chassis.h"
#include "object_lifetime_validation.h"
// ObjectTracker undestroyed objects validation function
bool ObjectLifetimes::ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {
bool skip = false;
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeSemaphore, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeFence, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDeviceMemory, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeBuffer, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeImage, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeEvent, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeQueryPool, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeBufferView, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeImageView, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeShaderModule, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypePipelineCache, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypePipelineLayout, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeRenderPass, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypePipeline, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDescriptorSetLayout, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeSampler, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDescriptorPool, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDescriptorSet, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeFramebuffer, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandPool, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeSamplerYcbcrConversion, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDescriptorUpdateTemplate, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeSurfaceKHR, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeSwapchainKHR, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDisplayKHR, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDisplayModeKHR, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDebugReportCallbackEXT, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeObjectTableNVX, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeIndirectCommandsLayoutNVX, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeDebugUtilsMessengerEXT, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeValidationCacheEXT, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeAccelerationStructureNV, error_code);
skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypePerformanceConfigurationINTEL, error_code);
return skip;
}
void ObjectLifetimes::DestroyUndestroyedObjects(VkDevice device) {
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeSemaphore);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeFence);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDeviceMemory);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeBuffer);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeImage);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeEvent);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeQueryPool);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeBufferView);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeImageView);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeShaderModule);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypePipelineCache);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypePipelineLayout);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeRenderPass);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypePipeline);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDescriptorSetLayout);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeSampler);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDescriptorPool);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDescriptorSet);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeFramebuffer);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandPool);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeSamplerYcbcrConversion);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDescriptorUpdateTemplate);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeSurfaceKHR);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeSwapchainKHR);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDisplayKHR);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDisplayModeKHR);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDebugReportCallbackEXT);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeObjectTableNVX);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeIndirectCommandsLayoutNVX);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeDebugUtilsMessengerEXT);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeValidationCacheEXT);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeAccelerationStructureNV);
DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypePerformanceConfigurationINTEL);
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceFeatures(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceFeatures* pFeatures) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceFeatures-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties* pFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceFormatProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceImageFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkImageType type,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkImageFormatProperties* pImageFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceImageFormatProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceProperties(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceMemoryProperties(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties* pMemoryProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceMemoryProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetInstanceProcAddr(
VkInstance instance,
const char* pName) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, true, "VUID-vkGetInstanceProcAddr-instance-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDeviceProcAddr(
VkDevice device,
const char* pName) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceProcAddr-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateDevice(
VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDevice* pDevice) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkCreateDevice-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDevice(
VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDevice* pDevice,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(physicalDevice, *pDevice, kVulkanObjectTypeDevice, pAllocator);
}
bool ObjectLifetimes::PreCallValidateEnumerateDeviceExtensionProperties(
VkPhysicalDevice physicalDevice,
const char* pLayerName,
uint32_t* pPropertyCount,
VkExtensionProperties* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkEnumerateDeviceExtensionProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateEnumerateDeviceLayerProperties(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkLayerProperties* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkEnumerateDeviceLayerProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateQueueSubmit(
VkQueue queue,
uint32_t submitCount,
const VkSubmitInfo* pSubmits,
VkFence fence) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueueSubmit-queue-parameter", "VUID-vkQueueSubmit-commonparent");
if (pSubmits) {
for (uint32_t index0 = 0; index0 < submitCount; ++index0) {
if (pSubmits[index0].pWaitSemaphores) {
for (uint32_t index1 = 0; index1 < pSubmits[index0].waitSemaphoreCount; ++index1) {
skip |= ValidateObject(queue, pSubmits[index0].pWaitSemaphores[index1], kVulkanObjectTypeSemaphore, false, "VUID-VkSubmitInfo-pWaitSemaphores-parameter", "VUID-VkSubmitInfo-commonparent");
}
}
if (pSubmits[index0].pCommandBuffers) {
for (uint32_t index1 = 0; index1 < pSubmits[index0].commandBufferCount; ++index1) {
skip |= ValidateObject(queue, pSubmits[index0].pCommandBuffers[index1], kVulkanObjectTypeCommandBuffer, false, "VUID-VkSubmitInfo-pCommandBuffers-parameter", "VUID-VkSubmitInfo-commonparent");
}
}
if (pSubmits[index0].pSignalSemaphores) {
for (uint32_t index1 = 0; index1 < pSubmits[index0].signalSemaphoreCount; ++index1) {
skip |= ValidateObject(queue, pSubmits[index0].pSignalSemaphores[index1], kVulkanObjectTypeSemaphore, false, "VUID-VkSubmitInfo-pSignalSemaphores-parameter", "VUID-VkSubmitInfo-commonparent");
}
}
}
}
skip |= ValidateObject(queue, fence, kVulkanObjectTypeFence, true, "VUID-vkQueueSubmit-fence-parameter", "VUID-vkQueueSubmit-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateQueueWaitIdle(
VkQueue queue) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueueWaitIdle-queue-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateDeviceWaitIdle(
VkDevice device) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDeviceWaitIdle-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateAllocateMemory(
VkDevice device,
const VkMemoryAllocateInfo* pAllocateInfo,
const VkAllocationCallbacks* pAllocator,
VkDeviceMemory* pMemory) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkAllocateMemory-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordAllocateMemory(
VkDevice device,
const VkMemoryAllocateInfo* pAllocateInfo,
const VkAllocationCallbacks* pAllocator,
VkDeviceMemory* pMemory,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pMemory, kVulkanObjectTypeDeviceMemory, pAllocator);
}
bool ObjectLifetimes::PreCallValidateFreeMemory(
VkDevice device,
VkDeviceMemory memory,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkFreeMemory-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, true, "VUID-vkFreeMemory-memory-parameter", "VUID-vkFreeMemory-memory-parent");
skip |= ValidateDestroyObject(device, memory, kVulkanObjectTypeDeviceMemory, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordFreeMemory(
VkDevice device,
VkDeviceMemory memory,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, memory, kVulkanObjectTypeDeviceMemory);
}
bool ObjectLifetimes::PreCallValidateMapMemory(
VkDevice device,
VkDeviceMemory memory,
VkDeviceSize offset,
VkDeviceSize size,
VkMemoryMapFlags flags,
void** ppData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkMapMemory-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, false, "VUID-vkMapMemory-memory-parameter", "VUID-vkMapMemory-memory-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateUnmapMemory(
VkDevice device,
VkDeviceMemory memory) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkUnmapMemory-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, false, "VUID-vkUnmapMemory-memory-parameter", "VUID-vkUnmapMemory-memory-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateFlushMappedMemoryRanges(
VkDevice device,
uint32_t memoryRangeCount,
const VkMappedMemoryRange* pMemoryRanges) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkFlushMappedMemoryRanges-device-parameter", kVUIDUndefined);
if (pMemoryRanges) {
for (uint32_t index0 = 0; index0 < memoryRangeCount; ++index0) {
skip |= ValidateObject(device, pMemoryRanges[index0].memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkMappedMemoryRange-memory-parameter", kVUIDUndefined);
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateInvalidateMappedMemoryRanges(
VkDevice device,
uint32_t memoryRangeCount,
const VkMappedMemoryRange* pMemoryRanges) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkInvalidateMappedMemoryRanges-device-parameter", kVUIDUndefined);
if (pMemoryRanges) {
for (uint32_t index0 = 0; index0 < memoryRangeCount; ++index0) {
skip |= ValidateObject(device, pMemoryRanges[index0].memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkMappedMemoryRange-memory-parameter", kVUIDUndefined);
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDeviceMemoryCommitment(
VkDevice device,
VkDeviceMemory memory,
VkDeviceSize* pCommittedMemoryInBytes) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceMemoryCommitment-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, false, "VUID-vkGetDeviceMemoryCommitment-memory-parameter", "VUID-vkGetDeviceMemoryCommitment-memory-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateBindBufferMemory(
VkDevice device,
VkBuffer buffer,
VkDeviceMemory memory,
VkDeviceSize memoryOffset) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindBufferMemory-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkBindBufferMemory-buffer-parameter", "VUID-vkBindBufferMemory-buffer-parent");
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, false, "VUID-vkBindBufferMemory-memory-parameter", "VUID-vkBindBufferMemory-memory-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateBindImageMemory(
VkDevice device,
VkImage image,
VkDeviceMemory memory,
VkDeviceSize memoryOffset) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindImageMemory-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, image, kVulkanObjectTypeImage, false, "VUID-vkBindImageMemory-image-parameter", "VUID-vkBindImageMemory-image-parent");
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, false, "VUID-vkBindImageMemory-memory-parameter", "VUID-vkBindImageMemory-memory-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetBufferMemoryRequirements(
VkDevice device,
VkBuffer buffer,
VkMemoryRequirements* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetBufferMemoryRequirements-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkGetBufferMemoryRequirements-buffer-parameter", "VUID-vkGetBufferMemoryRequirements-buffer-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageMemoryRequirements(
VkDevice device,
VkImage image,
VkMemoryRequirements* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageMemoryRequirements-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, image, kVulkanObjectTypeImage, false, "VUID-vkGetImageMemoryRequirements-image-parameter", "VUID-vkGetImageMemoryRequirements-image-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageSparseMemoryRequirements(
VkDevice device,
VkImage image,
uint32_t* pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements* pSparseMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageSparseMemoryRequirements-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, image, kVulkanObjectTypeImage, false, "VUID-vkGetImageSparseMemoryRequirements-image-parameter", "VUID-vkGetImageSparseMemoryRequirements-image-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSparseImageFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkImageType type,
VkSampleCountFlagBits samples,
VkImageUsageFlags usage,
VkImageTiling tiling,
uint32_t* pPropertyCount,
VkSparseImageFormatProperties* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSparseImageFormatProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateQueueBindSparse(
VkQueue queue,
uint32_t bindInfoCount,
const VkBindSparseInfo* pBindInfo,
VkFence fence) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueueBindSparse-queue-parameter", "VUID-vkQueueBindSparse-commonparent");
if (pBindInfo) {
for (uint32_t index0 = 0; index0 < bindInfoCount; ++index0) {
if (pBindInfo[index0].pWaitSemaphores) {
for (uint32_t index1 = 0; index1 < pBindInfo[index0].waitSemaphoreCount; ++index1) {
skip |= ValidateObject(queue, pBindInfo[index0].pWaitSemaphores[index1], kVulkanObjectTypeSemaphore, false, "VUID-VkBindSparseInfo-pWaitSemaphores-parameter", "VUID-VkBindSparseInfo-commonparent");
}
}
if (pBindInfo[index0].pBufferBinds) {
for (uint32_t index1 = 0; index1 < pBindInfo[index0].bufferBindCount; ++index1) {
skip |= ValidateObject(queue, pBindInfo[index0].pBufferBinds[index1].buffer, kVulkanObjectTypeBuffer, false, "VUID-VkSparseBufferMemoryBindInfo-buffer-parameter", kVUIDUndefined);
if (pBindInfo[index0].pBufferBinds[index1].pBinds) {
for (uint32_t index2 = 0; index2 < pBindInfo[index0].pBufferBinds[index1].bindCount; ++index2) {
skip |= ValidateObject(queue, pBindInfo[index0].pBufferBinds[index1].pBinds[index2].memory, kVulkanObjectTypeDeviceMemory, true, "VUID-VkSparseMemoryBind-memory-parameter", kVUIDUndefined);
}
}
}
}
if (pBindInfo[index0].pImageOpaqueBinds) {
for (uint32_t index1 = 0; index1 < pBindInfo[index0].imageOpaqueBindCount; ++index1) {
skip |= ValidateObject(queue, pBindInfo[index0].pImageOpaqueBinds[index1].image, kVulkanObjectTypeImage, false, "VUID-VkSparseImageOpaqueMemoryBindInfo-image-parameter", kVUIDUndefined);
if (pBindInfo[index0].pImageOpaqueBinds[index1].pBinds) {
for (uint32_t index2 = 0; index2 < pBindInfo[index0].pImageOpaqueBinds[index1].bindCount; ++index2) {
skip |= ValidateObject(queue, pBindInfo[index0].pImageOpaqueBinds[index1].pBinds[index2].memory, kVulkanObjectTypeDeviceMemory, true, "VUID-VkSparseMemoryBind-memory-parameter", kVUIDUndefined);
}
}
}
}
if (pBindInfo[index0].pImageBinds) {
for (uint32_t index1 = 0; index1 < pBindInfo[index0].imageBindCount; ++index1) {
skip |= ValidateObject(queue, pBindInfo[index0].pImageBinds[index1].image, kVulkanObjectTypeImage, false, "VUID-VkSparseImageMemoryBindInfo-image-parameter", kVUIDUndefined);
if (pBindInfo[index0].pImageBinds[index1].pBinds) {
for (uint32_t index2 = 0; index2 < pBindInfo[index0].pImageBinds[index1].bindCount; ++index2) {
skip |= ValidateObject(queue, pBindInfo[index0].pImageBinds[index1].pBinds[index2].memory, kVulkanObjectTypeDeviceMemory, true, "VUID-VkSparseImageMemoryBind-memory-parameter", kVUIDUndefined);
}
}
}
}
if (pBindInfo[index0].pSignalSemaphores) {
for (uint32_t index1 = 0; index1 < pBindInfo[index0].signalSemaphoreCount; ++index1) {
skip |= ValidateObject(queue, pBindInfo[index0].pSignalSemaphores[index1], kVulkanObjectTypeSemaphore, false, "VUID-VkBindSparseInfo-pSignalSemaphores-parameter", "VUID-VkBindSparseInfo-commonparent");
}
}
}
}
skip |= ValidateObject(queue, fence, kVulkanObjectTypeFence, true, "VUID-vkQueueBindSparse-fence-parameter", "VUID-vkQueueBindSparse-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateFence(
VkDevice device,
const VkFenceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateFence-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateFence(
VkDevice device,
const VkFenceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pFence, kVulkanObjectTypeFence, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyFence(
VkDevice device,
VkFence fence,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyFence-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, fence, kVulkanObjectTypeFence, true, "VUID-vkDestroyFence-fence-parameter", "VUID-vkDestroyFence-fence-parent");
skip |= ValidateDestroyObject(device, fence, kVulkanObjectTypeFence, pAllocator, "VUID-vkDestroyFence-fence-01121", "VUID-vkDestroyFence-fence-01122");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyFence(
VkDevice device,
VkFence fence,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, fence, kVulkanObjectTypeFence);
}
bool ObjectLifetimes::PreCallValidateResetFences(
VkDevice device,
uint32_t fenceCount,
const VkFence* pFences) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkResetFences-device-parameter", kVUIDUndefined);
if (pFences) {
for (uint32_t index0 = 0; index0 < fenceCount; ++index0) {
skip |= ValidateObject(device, pFences[index0], kVulkanObjectTypeFence, false, "VUID-vkResetFences-pFences-parameter", "VUID-vkResetFences-pFences-parent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetFenceStatus(
VkDevice device,
VkFence fence) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetFenceStatus-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, fence, kVulkanObjectTypeFence, false, "VUID-vkGetFenceStatus-fence-parameter", "VUID-vkGetFenceStatus-fence-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateWaitForFences(
VkDevice device,
uint32_t fenceCount,
const VkFence* pFences,
VkBool32 waitAll,
uint64_t timeout) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkWaitForFences-device-parameter", kVUIDUndefined);
if (pFences) {
for (uint32_t index0 = 0; index0 < fenceCount; ++index0) {
skip |= ValidateObject(device, pFences[index0], kVulkanObjectTypeFence, false, "VUID-vkWaitForFences-pFences-parameter", "VUID-vkWaitForFences-pFences-parent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateSemaphore(
VkDevice device,
const VkSemaphoreCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSemaphore* pSemaphore) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateSemaphore-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateSemaphore(
VkDevice device,
const VkSemaphoreCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSemaphore* pSemaphore,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pSemaphore, kVulkanObjectTypeSemaphore, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroySemaphore(
VkDevice device,
VkSemaphore semaphore,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroySemaphore-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, semaphore, kVulkanObjectTypeSemaphore, true, "VUID-vkDestroySemaphore-semaphore-parameter", "VUID-vkDestroySemaphore-semaphore-parent");
skip |= ValidateDestroyObject(device, semaphore, kVulkanObjectTypeSemaphore, pAllocator, "VUID-vkDestroySemaphore-semaphore-01138", "VUID-vkDestroySemaphore-semaphore-01139");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroySemaphore(
VkDevice device,
VkSemaphore semaphore,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, semaphore, kVulkanObjectTypeSemaphore);
}
bool ObjectLifetimes::PreCallValidateCreateEvent(
VkDevice device,
const VkEventCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkEvent* pEvent) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateEvent-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateEvent(
VkDevice device,
const VkEventCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkEvent* pEvent,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pEvent, kVulkanObjectTypeEvent, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyEvent(
VkDevice device,
VkEvent event,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyEvent-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, event, kVulkanObjectTypeEvent, true, "VUID-vkDestroyEvent-event-parameter", "VUID-vkDestroyEvent-event-parent");
skip |= ValidateDestroyObject(device, event, kVulkanObjectTypeEvent, pAllocator, "VUID-vkDestroyEvent-event-01146", "VUID-vkDestroyEvent-event-01147");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyEvent(
VkDevice device,
VkEvent event,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, event, kVulkanObjectTypeEvent);
}
bool ObjectLifetimes::PreCallValidateGetEventStatus(
VkDevice device,
VkEvent event) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetEventStatus-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, event, kVulkanObjectTypeEvent, false, "VUID-vkGetEventStatus-event-parameter", "VUID-vkGetEventStatus-event-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateSetEvent(
VkDevice device,
VkEvent event) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkSetEvent-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, event, kVulkanObjectTypeEvent, false, "VUID-vkSetEvent-event-parameter", "VUID-vkSetEvent-event-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateResetEvent(
VkDevice device,
VkEvent event) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkResetEvent-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, event, kVulkanObjectTypeEvent, false, "VUID-vkResetEvent-event-parameter", "VUID-vkResetEvent-event-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateQueryPool(
VkDevice device,
const VkQueryPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkQueryPool* pQueryPool) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateQueryPool-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateQueryPool(
VkDevice device,
const VkQueryPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkQueryPool* pQueryPool,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pQueryPool, kVulkanObjectTypeQueryPool, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyQueryPool(
VkDevice device,
VkQueryPool queryPool,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyQueryPool-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, queryPool, kVulkanObjectTypeQueryPool, true, "VUID-vkDestroyQueryPool-queryPool-parameter", "VUID-vkDestroyQueryPool-queryPool-parent");
skip |= ValidateDestroyObject(device, queryPool, kVulkanObjectTypeQueryPool, pAllocator, "VUID-vkDestroyQueryPool-queryPool-00794", "VUID-vkDestroyQueryPool-queryPool-00795");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyQueryPool(
VkDevice device,
VkQueryPool queryPool,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, queryPool, kVulkanObjectTypeQueryPool);
}
bool ObjectLifetimes::PreCallValidateGetQueryPoolResults(
VkDevice device,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount,
size_t dataSize,
void* pData,
VkDeviceSize stride,
VkQueryResultFlags flags) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetQueryPoolResults-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkGetQueryPoolResults-queryPool-parameter", "VUID-vkGetQueryPoolResults-queryPool-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateBuffer(
VkDevice device,
const VkBufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBuffer* pBuffer) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateBuffer-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateBuffer(
VkDevice device,
const VkBufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBuffer* pBuffer,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pBuffer, kVulkanObjectTypeBuffer, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyBuffer(
VkDevice device,
VkBuffer buffer,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyBuffer-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, buffer, kVulkanObjectTypeBuffer, true, "VUID-vkDestroyBuffer-buffer-parameter", "VUID-vkDestroyBuffer-buffer-parent");
skip |= ValidateDestroyObject(device, buffer, kVulkanObjectTypeBuffer, pAllocator, "VUID-vkDestroyBuffer-buffer-00923", "VUID-vkDestroyBuffer-buffer-00924");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyBuffer(
VkDevice device,
VkBuffer buffer,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, buffer, kVulkanObjectTypeBuffer);
}
bool ObjectLifetimes::PreCallValidateCreateBufferView(
VkDevice device,
const VkBufferViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBufferView* pView) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateBufferView-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
skip |= ValidateObject(device, pCreateInfo->buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBufferViewCreateInfo-buffer-parameter", kVUIDUndefined);
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateBufferView(
VkDevice device,
const VkBufferViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBufferView* pView,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pView, kVulkanObjectTypeBufferView, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyBufferView(
VkDevice device,
VkBufferView bufferView,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyBufferView-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, bufferView, kVulkanObjectTypeBufferView, true, "VUID-vkDestroyBufferView-bufferView-parameter", "VUID-vkDestroyBufferView-bufferView-parent");
skip |= ValidateDestroyObject(device, bufferView, kVulkanObjectTypeBufferView, pAllocator, "VUID-vkDestroyBufferView-bufferView-00937", "VUID-vkDestroyBufferView-bufferView-00938");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyBufferView(
VkDevice device,
VkBufferView bufferView,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, bufferView, kVulkanObjectTypeBufferView);
}
bool ObjectLifetimes::PreCallValidateCreateImage(
VkDevice device,
const VkImageCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImage* pImage) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateImage-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateImage(
VkDevice device,
const VkImageCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImage* pImage,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pImage, kVulkanObjectTypeImage, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyImage(
VkDevice device,
VkImage image,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyImage-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, image, kVulkanObjectTypeImage, true, "VUID-vkDestroyImage-image-parameter", "VUID-vkDestroyImage-image-parent");
skip |= ValidateDestroyObject(device, image, kVulkanObjectTypeImage, pAllocator, "VUID-vkDestroyImage-image-01001", "VUID-vkDestroyImage-image-01002");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyImage(
VkDevice device,
VkImage image,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, image, kVulkanObjectTypeImage);
}
bool ObjectLifetimes::PreCallValidateGetImageSubresourceLayout(
VkDevice device,
VkImage image,
const VkImageSubresource* pSubresource,
VkSubresourceLayout* pLayout) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageSubresourceLayout-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, image, kVulkanObjectTypeImage, false, "VUID-vkGetImageSubresourceLayout-image-parameter", "VUID-vkGetImageSubresourceLayout-image-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateImageView(
VkDevice device,
const VkImageViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImageView* pView) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateImageView-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
skip |= ValidateObject(device, pCreateInfo->image, kVulkanObjectTypeImage, false, "VUID-VkImageViewCreateInfo-image-parameter", kVUIDUndefined);
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateImageView(
VkDevice device,
const VkImageViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImageView* pView,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pView, kVulkanObjectTypeImageView, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyImageView(
VkDevice device,
VkImageView imageView,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyImageView-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, imageView, kVulkanObjectTypeImageView, true, "VUID-vkDestroyImageView-imageView-parameter", "VUID-vkDestroyImageView-imageView-parent");
skip |= ValidateDestroyObject(device, imageView, kVulkanObjectTypeImageView, pAllocator, "VUID-vkDestroyImageView-imageView-01027", "VUID-vkDestroyImageView-imageView-01028");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyImageView(
VkDevice device,
VkImageView imageView,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, imageView, kVulkanObjectTypeImageView);
}
bool ObjectLifetimes::PreCallValidateCreateShaderModule(
VkDevice device,
const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkShaderModule* pShaderModule) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateShaderModule-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateShaderModule(
VkDevice device,
const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkShaderModule* pShaderModule,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pShaderModule, kVulkanObjectTypeShaderModule, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyShaderModule(
VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyShaderModule-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, shaderModule, kVulkanObjectTypeShaderModule, true, "VUID-vkDestroyShaderModule-shaderModule-parameter", "VUID-vkDestroyShaderModule-shaderModule-parent");
skip |= ValidateDestroyObject(device, shaderModule, kVulkanObjectTypeShaderModule, pAllocator, "VUID-vkDestroyShaderModule-shaderModule-01092", "VUID-vkDestroyShaderModule-shaderModule-01093");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyShaderModule(
VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, shaderModule, kVulkanObjectTypeShaderModule);
}
bool ObjectLifetimes::PreCallValidateCreatePipelineCache(
VkDevice device,
const VkPipelineCacheCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineCache* pPipelineCache) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreatePipelineCache-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreatePipelineCache(
VkDevice device,
const VkPipelineCacheCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineCache* pPipelineCache,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pPipelineCache, kVulkanObjectTypePipelineCache, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyPipelineCache(
VkDevice device,
VkPipelineCache pipelineCache,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyPipelineCache-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipelineCache, kVulkanObjectTypePipelineCache, true, "VUID-vkDestroyPipelineCache-pipelineCache-parameter", "VUID-vkDestroyPipelineCache-pipelineCache-parent");
skip |= ValidateDestroyObject(device, pipelineCache, kVulkanObjectTypePipelineCache, pAllocator, "VUID-vkDestroyPipelineCache-pipelineCache-00771", "VUID-vkDestroyPipelineCache-pipelineCache-00772");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyPipelineCache(
VkDevice device,
VkPipelineCache pipelineCache,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, pipelineCache, kVulkanObjectTypePipelineCache);
}
bool ObjectLifetimes::PreCallValidateGetPipelineCacheData(
VkDevice device,
VkPipelineCache pipelineCache,
size_t* pDataSize,
void* pData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetPipelineCacheData-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipelineCache, kVulkanObjectTypePipelineCache, false, "VUID-vkGetPipelineCacheData-pipelineCache-parameter", "VUID-vkGetPipelineCacheData-pipelineCache-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateMergePipelineCaches(
VkDevice device,
VkPipelineCache dstCache,
uint32_t srcCacheCount,
const VkPipelineCache* pSrcCaches) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkMergePipelineCaches-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, dstCache, kVulkanObjectTypePipelineCache, false, "VUID-vkMergePipelineCaches-dstCache-parameter", "VUID-vkMergePipelineCaches-dstCache-parent");
if (pSrcCaches) {
for (uint32_t index0 = 0; index0 < srcCacheCount; ++index0) {
skip |= ValidateObject(device, pSrcCaches[index0], kVulkanObjectTypePipelineCache, false, "VUID-vkMergePipelineCaches-pSrcCaches-parameter", "VUID-vkMergePipelineCaches-pSrcCaches-parent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateGraphicsPipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateGraphicsPipelines-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipelineCache, kVulkanObjectTypePipelineCache, true, "VUID-vkCreateGraphicsPipelines-pipelineCache-parameter", "VUID-vkCreateGraphicsPipelines-pipelineCache-parent");
if (pCreateInfos) {
for (uint32_t index0 = 0; index0 < createInfoCount; ++index0) {
if (pCreateInfos[index0].pStages) {
for (uint32_t index1 = 0; index1 < pCreateInfos[index0].stageCount; ++index1) {
skip |= ValidateObject(device, pCreateInfos[index0].pStages[index1].module, kVulkanObjectTypeShaderModule, false, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", kVUIDUndefined);
}
}
skip |= ValidateObject(device, pCreateInfos[index0].layout, kVulkanObjectTypePipelineLayout, false, "VUID-VkGraphicsPipelineCreateInfo-layout-parameter", "VUID-VkGraphicsPipelineCreateInfo-commonparent");
skip |= ValidateObject(device, pCreateInfos[index0].renderPass, kVulkanObjectTypeRenderPass, false, "VUID-VkGraphicsPipelineCreateInfo-renderPass-parameter", "VUID-VkGraphicsPipelineCreateInfo-commonparent");
skip |= ValidateObject(device, pCreateInfos[index0].basePipelineHandle, kVulkanObjectTypePipeline, true, kVUIDUndefined, "VUID-VkGraphicsPipelineCreateInfo-commonparent");
}
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateGraphicsPipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result) {
if (VK_ERROR_VALIDATION_FAILED_EXT == result) return;
if (pPipelines) {
for (uint32_t index = 0; index < createInfoCount; index++) {
if (!pPipelines[index]) continue;
CreateObject(device, pPipelines[index], kVulkanObjectTypePipeline, pAllocator);
}
}
}
bool ObjectLifetimes::PreCallValidateCreateComputePipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateComputePipelines-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipelineCache, kVulkanObjectTypePipelineCache, true, "VUID-vkCreateComputePipelines-pipelineCache-parameter", "VUID-vkCreateComputePipelines-pipelineCache-parent");
if (pCreateInfos) {
for (uint32_t index0 = 0; index0 < createInfoCount; ++index0) {
skip |= ValidateObject(device, pCreateInfos[index0].stage.module, kVulkanObjectTypeShaderModule, false, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pCreateInfos[index0].layout, kVulkanObjectTypePipelineLayout, false, "VUID-VkComputePipelineCreateInfo-layout-parameter", "VUID-VkComputePipelineCreateInfo-commonparent");
skip |= ValidateObject(device, pCreateInfos[index0].basePipelineHandle, kVulkanObjectTypePipeline, true, kVUIDUndefined, "VUID-VkComputePipelineCreateInfo-commonparent");
}
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateComputePipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result) {
if (VK_ERROR_VALIDATION_FAILED_EXT == result) return;
if (pPipelines) {
for (uint32_t index = 0; index < createInfoCount; index++) {
if (!pPipelines[index]) continue;
CreateObject(device, pPipelines[index], kVulkanObjectTypePipeline, pAllocator);
}
}
}
bool ObjectLifetimes::PreCallValidateDestroyPipeline(
VkDevice device,
VkPipeline pipeline,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyPipeline-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipeline, kVulkanObjectTypePipeline, true, "VUID-vkDestroyPipeline-pipeline-parameter", "VUID-vkDestroyPipeline-pipeline-parent");
skip |= ValidateDestroyObject(device, pipeline, kVulkanObjectTypePipeline, pAllocator, "VUID-vkDestroyPipeline-pipeline-00766", "VUID-vkDestroyPipeline-pipeline-00767");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyPipeline(
VkDevice device,
VkPipeline pipeline,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, pipeline, kVulkanObjectTypePipeline);
}
bool ObjectLifetimes::PreCallValidateCreatePipelineLayout(
VkDevice device,
const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreatePipelineLayout-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
if (pCreateInfo->pSetLayouts) {
for (uint32_t index1 = 0; index1 < pCreateInfo->setLayoutCount; ++index1) {
skip |= ValidateObject(device, pCreateInfo->pSetLayouts[index1], kVulkanObjectTypeDescriptorSetLayout, false, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter", kVUIDUndefined);
}
}
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreatePipelineLayout(
VkDevice device,
const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pPipelineLayout, kVulkanObjectTypePipelineLayout, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyPipelineLayout(
VkDevice device,
VkPipelineLayout pipelineLayout,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyPipelineLayout-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipelineLayout, kVulkanObjectTypePipelineLayout, true, "VUID-vkDestroyPipelineLayout-pipelineLayout-parameter", "VUID-vkDestroyPipelineLayout-pipelineLayout-parent");
skip |= ValidateDestroyObject(device, pipelineLayout, kVulkanObjectTypePipelineLayout, pAllocator, "VUID-vkDestroyPipelineLayout-pipelineLayout-00299", "VUID-vkDestroyPipelineLayout-pipelineLayout-00300");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyPipelineLayout(
VkDevice device,
VkPipelineLayout pipelineLayout,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, pipelineLayout, kVulkanObjectTypePipelineLayout);
}
bool ObjectLifetimes::PreCallValidateCreateSampler(
VkDevice device,
const VkSamplerCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSampler* pSampler) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateSampler-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateSampler(
VkDevice device,
const VkSamplerCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSampler* pSampler,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pSampler, kVulkanObjectTypeSampler, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroySampler(
VkDevice device,
VkSampler sampler,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroySampler-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, sampler, kVulkanObjectTypeSampler, true, "VUID-vkDestroySampler-sampler-parameter", "VUID-vkDestroySampler-sampler-parent");
skip |= ValidateDestroyObject(device, sampler, kVulkanObjectTypeSampler, pAllocator, "VUID-vkDestroySampler-sampler-01083", "VUID-vkDestroySampler-sampler-01084");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroySampler(
VkDevice device,
VkSampler sampler,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, sampler, kVulkanObjectTypeSampler);
}
bool ObjectLifetimes::PreCallValidateDestroyDescriptorSetLayout(
VkDevice device,
VkDescriptorSetLayout descriptorSetLayout,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyDescriptorSetLayout-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorSetLayout, kVulkanObjectTypeDescriptorSetLayout, true, "VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-parameter", "VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-parent");
skip |= ValidateDestroyObject(device, descriptorSetLayout, kVulkanObjectTypeDescriptorSetLayout, pAllocator, "VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284", "VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyDescriptorSetLayout(
VkDevice device,
VkDescriptorSetLayout descriptorSetLayout,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, descriptorSetLayout, kVulkanObjectTypeDescriptorSetLayout);
}
bool ObjectLifetimes::PreCallValidateCreateDescriptorPool(
VkDevice device,
const VkDescriptorPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorPool* pDescriptorPool) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateDescriptorPool-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDescriptorPool(
VkDevice device,
const VkDescriptorPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorPool* pDescriptorPool,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pDescriptorPool, kVulkanObjectTypeDescriptorPool, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyFramebuffer(
VkDevice device,
VkFramebuffer framebuffer,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyFramebuffer-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, framebuffer, kVulkanObjectTypeFramebuffer, true, "VUID-vkDestroyFramebuffer-framebuffer-parameter", "VUID-vkDestroyFramebuffer-framebuffer-parent");
skip |= ValidateDestroyObject(device, framebuffer, kVulkanObjectTypeFramebuffer, pAllocator, "VUID-vkDestroyFramebuffer-framebuffer-00893", "VUID-vkDestroyFramebuffer-framebuffer-00894");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyFramebuffer(
VkDevice device,
VkFramebuffer framebuffer,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, framebuffer, kVulkanObjectTypeFramebuffer);
}
bool ObjectLifetimes::PreCallValidateCreateRenderPass(
VkDevice device,
const VkRenderPassCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateRenderPass-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateRenderPass(
VkDevice device,
const VkRenderPassCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pRenderPass, kVulkanObjectTypeRenderPass, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyRenderPass(
VkDevice device,
VkRenderPass renderPass,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyRenderPass-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, renderPass, kVulkanObjectTypeRenderPass, true, "VUID-vkDestroyRenderPass-renderPass-parameter", "VUID-vkDestroyRenderPass-renderPass-parent");
skip |= ValidateDestroyObject(device, renderPass, kVulkanObjectTypeRenderPass, pAllocator, "VUID-vkDestroyRenderPass-renderPass-00874", "VUID-vkDestroyRenderPass-renderPass-00875");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyRenderPass(
VkDevice device,
VkRenderPass renderPass,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, renderPass, kVulkanObjectTypeRenderPass);
}
bool ObjectLifetimes::PreCallValidateGetRenderAreaGranularity(
VkDevice device,
VkRenderPass renderPass,
VkExtent2D* pGranularity) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetRenderAreaGranularity-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, renderPass, kVulkanObjectTypeRenderPass, false, "VUID-vkGetRenderAreaGranularity-renderPass-parameter", "VUID-vkGetRenderAreaGranularity-renderPass-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateCommandPool(
VkDevice device,
const VkCommandPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkCommandPool* pCommandPool) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateCommandPool-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateCommandPool(
VkDevice device,
const VkCommandPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkCommandPool* pCommandPool,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pCommandPool, kVulkanObjectTypeCommandPool, pAllocator);
}
bool ObjectLifetimes::PreCallValidateResetCommandPool(
VkDevice device,
VkCommandPool commandPool,
VkCommandPoolResetFlags flags) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkResetCommandPool-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, commandPool, kVulkanObjectTypeCommandPool, false, "VUID-vkResetCommandPool-commandPool-parameter", "VUID-vkResetCommandPool-commandPool-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateEndCommandBuffer(
VkCommandBuffer commandBuffer) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkEndCommandBuffer-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateResetCommandBuffer(
VkCommandBuffer commandBuffer,
VkCommandBufferResetFlags flags) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkResetCommandBuffer-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBindPipeline(
VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipeline pipeline) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBindPipeline-commandBuffer-parameter", "VUID-vkCmdBindPipeline-commonparent");
skip |= ValidateObject(commandBuffer, pipeline, kVulkanObjectTypePipeline, false, "VUID-vkCmdBindPipeline-pipeline-parameter", "VUID-vkCmdBindPipeline-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetViewport(
VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkViewport* pViewports) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetViewport-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetScissor(
VkCommandBuffer commandBuffer,
uint32_t firstScissor,
uint32_t scissorCount,
const VkRect2D* pScissors) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetScissor-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetLineWidth(
VkCommandBuffer commandBuffer,
float lineWidth) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetLineWidth-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetDepthBias(
VkCommandBuffer commandBuffer,
float depthBiasConstantFactor,
float depthBiasClamp,
float depthBiasSlopeFactor) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetDepthBias-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetBlendConstants(
VkCommandBuffer commandBuffer,
const float blendConstants[4]) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetBlendConstants-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetDepthBounds(
VkCommandBuffer commandBuffer,
float minDepthBounds,
float maxDepthBounds) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetDepthBounds-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetStencilCompareMask(
VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t compareMask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetStencilCompareMask-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetStencilWriteMask(
VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t writeMask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetStencilWriteMask-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetStencilReference(
VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t reference) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetStencilReference-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBindDescriptorSets(
VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout,
uint32_t firstSet,
uint32_t descriptorSetCount,
const VkDescriptorSet* pDescriptorSets,
uint32_t dynamicOffsetCount,
const uint32_t* pDynamicOffsets) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBindDescriptorSets-commandBuffer-parameter", "VUID-vkCmdBindDescriptorSets-commonparent");
skip |= ValidateObject(commandBuffer, layout, kVulkanObjectTypePipelineLayout, false, "VUID-vkCmdBindDescriptorSets-layout-parameter", "VUID-vkCmdBindDescriptorSets-commonparent");
if (pDescriptorSets) {
for (uint32_t index0 = 0; index0 < descriptorSetCount; ++index0) {
skip |= ValidateObject(commandBuffer, pDescriptorSets[index0], kVulkanObjectTypeDescriptorSet, false, "VUID-vkCmdBindDescriptorSets-pDescriptorSets-parameter", "VUID-vkCmdBindDescriptorSets-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBindIndexBuffer(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkIndexType indexType) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBindIndexBuffer-commandBuffer-parameter", "VUID-vkCmdBindIndexBuffer-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdBindIndexBuffer-buffer-parameter", "VUID-vkCmdBindIndexBuffer-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBindVertexBuffers(
VkCommandBuffer commandBuffer,
uint32_t firstBinding,
uint32_t bindingCount,
const VkBuffer* pBuffers,
const VkDeviceSize* pOffsets) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBindVertexBuffers-commandBuffer-parameter", "VUID-vkCmdBindVertexBuffers-commonparent");
if (pBuffers) {
for (uint32_t index0 = 0; index0 < bindingCount; ++index0) {
skip |= ValidateObject(commandBuffer, pBuffers[index0], kVulkanObjectTypeBuffer, false, "VUID-vkCmdBindVertexBuffers-pBuffers-parameter", "VUID-vkCmdBindVertexBuffers-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDraw(
VkCommandBuffer commandBuffer,
uint32_t vertexCount,
uint32_t instanceCount,
uint32_t firstVertex,
uint32_t firstInstance) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDraw-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndexed(
VkCommandBuffer commandBuffer,
uint32_t indexCount,
uint32_t instanceCount,
uint32_t firstIndex,
int32_t vertexOffset,
uint32_t firstInstance) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndexed-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndirect(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndirect-commandBuffer-parameter", "VUID-vkCmdDrawIndirect-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndirect-buffer-parameter", "VUID-vkCmdDrawIndirect-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndexedIndirect(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndexedIndirect-commandBuffer-parameter", "VUID-vkCmdDrawIndexedIndirect-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndexedIndirect-buffer-parameter", "VUID-vkCmdDrawIndexedIndirect-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDispatch(
VkCommandBuffer commandBuffer,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDispatch-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDispatchIndirect(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDispatchIndirect-commandBuffer-parameter", "VUID-vkCmdDispatchIndirect-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDispatchIndirect-buffer-parameter", "VUID-vkCmdDispatchIndirect-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdCopyBuffer(
VkCommandBuffer commandBuffer,
VkBuffer srcBuffer,
VkBuffer dstBuffer,
uint32_t regionCount,
const VkBufferCopy* pRegions) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdCopyBuffer-commandBuffer-parameter", "VUID-vkCmdCopyBuffer-commonparent");
skip |= ValidateObject(commandBuffer, srcBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdCopyBuffer-srcBuffer-parameter", "VUID-vkCmdCopyBuffer-commonparent");
skip |= ValidateObject(commandBuffer, dstBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdCopyBuffer-dstBuffer-parameter", "VUID-vkCmdCopyBuffer-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdCopyImage(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageCopy* pRegions) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdCopyImage-commandBuffer-parameter", "VUID-vkCmdCopyImage-commonparent");
skip |= ValidateObject(commandBuffer, srcImage, kVulkanObjectTypeImage, false, "VUID-vkCmdCopyImage-srcImage-parameter", "VUID-vkCmdCopyImage-commonparent");
skip |= ValidateObject(commandBuffer, dstImage, kVulkanObjectTypeImage, false, "VUID-vkCmdCopyImage-dstImage-parameter", "VUID-vkCmdCopyImage-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBlitImage(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageBlit* pRegions,
VkFilter filter) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBlitImage-commandBuffer-parameter", "VUID-vkCmdBlitImage-commonparent");
skip |= ValidateObject(commandBuffer, srcImage, kVulkanObjectTypeImage, false, "VUID-vkCmdBlitImage-srcImage-parameter", "VUID-vkCmdBlitImage-commonparent");
skip |= ValidateObject(commandBuffer, dstImage, kVulkanObjectTypeImage, false, "VUID-vkCmdBlitImage-dstImage-parameter", "VUID-vkCmdBlitImage-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdCopyBufferToImage(
VkCommandBuffer commandBuffer,
VkBuffer srcBuffer,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkBufferImageCopy* pRegions) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdCopyBufferToImage-commandBuffer-parameter", "VUID-vkCmdCopyBufferToImage-commonparent");
skip |= ValidateObject(commandBuffer, srcBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdCopyBufferToImage-srcBuffer-parameter", "VUID-vkCmdCopyBufferToImage-commonparent");
skip |= ValidateObject(commandBuffer, dstImage, kVulkanObjectTypeImage, false, "VUID-vkCmdCopyBufferToImage-dstImage-parameter", "VUID-vkCmdCopyBufferToImage-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdCopyImageToBuffer(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkBuffer dstBuffer,
uint32_t regionCount,
const VkBufferImageCopy* pRegions) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdCopyImageToBuffer-commandBuffer-parameter", "VUID-vkCmdCopyImageToBuffer-commonparent");
skip |= ValidateObject(commandBuffer, srcImage, kVulkanObjectTypeImage, false, "VUID-vkCmdCopyImageToBuffer-srcImage-parameter", "VUID-vkCmdCopyImageToBuffer-commonparent");
skip |= ValidateObject(commandBuffer, dstBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdCopyImageToBuffer-dstBuffer-parameter", "VUID-vkCmdCopyImageToBuffer-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdUpdateBuffer(
VkCommandBuffer commandBuffer,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize dataSize,
const void* pData) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdUpdateBuffer-commandBuffer-parameter", "VUID-vkCmdUpdateBuffer-commonparent");
skip |= ValidateObject(commandBuffer, dstBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdUpdateBuffer-dstBuffer-parameter", "VUID-vkCmdUpdateBuffer-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdFillBuffer(
VkCommandBuffer commandBuffer,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize size,
uint32_t data) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdFillBuffer-commandBuffer-parameter", "VUID-vkCmdFillBuffer-commonparent");
skip |= ValidateObject(commandBuffer, dstBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdFillBuffer-dstBuffer-parameter", "VUID-vkCmdFillBuffer-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdClearColorImage(
VkCommandBuffer commandBuffer,
VkImage image,
VkImageLayout imageLayout,
const VkClearColorValue* pColor,
uint32_t rangeCount,
const VkImageSubresourceRange* pRanges) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdClearColorImage-commandBuffer-parameter", "VUID-vkCmdClearColorImage-commonparent");
skip |= ValidateObject(commandBuffer, image, kVulkanObjectTypeImage, false, "VUID-vkCmdClearColorImage-image-parameter", "VUID-vkCmdClearColorImage-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdClearDepthStencilImage(
VkCommandBuffer commandBuffer,
VkImage image,
VkImageLayout imageLayout,
const VkClearDepthStencilValue* pDepthStencil,
uint32_t rangeCount,
const VkImageSubresourceRange* pRanges) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdClearDepthStencilImage-commandBuffer-parameter", "VUID-vkCmdClearDepthStencilImage-commonparent");
skip |= ValidateObject(commandBuffer, image, kVulkanObjectTypeImage, false, "VUID-vkCmdClearDepthStencilImage-image-parameter", "VUID-vkCmdClearDepthStencilImage-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdClearAttachments(
VkCommandBuffer commandBuffer,
uint32_t attachmentCount,
const VkClearAttachment* pAttachments,
uint32_t rectCount,
const VkClearRect* pRects) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdClearAttachments-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdResolveImage(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageResolve* pRegions) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdResolveImage-commandBuffer-parameter", "VUID-vkCmdResolveImage-commonparent");
skip |= ValidateObject(commandBuffer, srcImage, kVulkanObjectTypeImage, false, "VUID-vkCmdResolveImage-srcImage-parameter", "VUID-vkCmdResolveImage-commonparent");
skip |= ValidateObject(commandBuffer, dstImage, kVulkanObjectTypeImage, false, "VUID-vkCmdResolveImage-dstImage-parameter", "VUID-vkCmdResolveImage-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetEvent(
VkCommandBuffer commandBuffer,
VkEvent event,
VkPipelineStageFlags stageMask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetEvent-commandBuffer-parameter", "VUID-vkCmdSetEvent-commonparent");
skip |= ValidateObject(commandBuffer, event, kVulkanObjectTypeEvent, false, "VUID-vkCmdSetEvent-event-parameter", "VUID-vkCmdSetEvent-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdResetEvent(
VkCommandBuffer commandBuffer,
VkEvent event,
VkPipelineStageFlags stageMask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdResetEvent-commandBuffer-parameter", "VUID-vkCmdResetEvent-commonparent");
skip |= ValidateObject(commandBuffer, event, kVulkanObjectTypeEvent, false, "VUID-vkCmdResetEvent-event-parameter", "VUID-vkCmdResetEvent-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdWaitEvents(
VkCommandBuffer commandBuffer,
uint32_t eventCount,
const VkEvent* pEvents,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
uint32_t memoryBarrierCount,
const VkMemoryBarrier* pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const VkBufferMemoryBarrier* pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier* pImageMemoryBarriers) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdWaitEvents-commandBuffer-parameter", "VUID-vkCmdWaitEvents-commonparent");
if (pEvents) {
for (uint32_t index0 = 0; index0 < eventCount; ++index0) {
skip |= ValidateObject(commandBuffer, pEvents[index0], kVulkanObjectTypeEvent, false, "VUID-vkCmdWaitEvents-pEvents-parameter", "VUID-vkCmdWaitEvents-commonparent");
}
}
if (pBufferMemoryBarriers) {
for (uint32_t index0 = 0; index0 < bufferMemoryBarrierCount; ++index0) {
skip |= ValidateObject(commandBuffer, pBufferMemoryBarriers[index0].buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBufferMemoryBarrier-buffer-parameter", kVUIDUndefined);
}
}
if (pImageMemoryBarriers) {
for (uint32_t index0 = 0; index0 < imageMemoryBarrierCount; ++index0) {
skip |= ValidateObject(commandBuffer, pImageMemoryBarriers[index0].image, kVulkanObjectTypeImage, false, "VUID-VkImageMemoryBarrier-image-parameter", kVUIDUndefined);
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdPipelineBarrier(
VkCommandBuffer commandBuffer,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
VkDependencyFlags dependencyFlags,
uint32_t memoryBarrierCount,
const VkMemoryBarrier* pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const VkBufferMemoryBarrier* pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier* pImageMemoryBarriers) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdPipelineBarrier-commandBuffer-parameter", kVUIDUndefined);
if (pBufferMemoryBarriers) {
for (uint32_t index0 = 0; index0 < bufferMemoryBarrierCount; ++index0) {
skip |= ValidateObject(commandBuffer, pBufferMemoryBarriers[index0].buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBufferMemoryBarrier-buffer-parameter", kVUIDUndefined);
}
}
if (pImageMemoryBarriers) {
for (uint32_t index0 = 0; index0 < imageMemoryBarrierCount; ++index0) {
skip |= ValidateObject(commandBuffer, pImageMemoryBarriers[index0].image, kVulkanObjectTypeImage, false, "VUID-VkImageMemoryBarrier-image-parameter", kVUIDUndefined);
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBeginQuery(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query,
VkQueryControlFlags flags) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginQuery-commandBuffer-parameter", "VUID-vkCmdBeginQuery-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdBeginQuery-queryPool-parameter", "VUID-vkCmdBeginQuery-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndQuery(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndQuery-commandBuffer-parameter", "VUID-vkCmdEndQuery-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdEndQuery-queryPool-parameter", "VUID-vkCmdEndQuery-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdResetQueryPool(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdResetQueryPool-commandBuffer-parameter", "VUID-vkCmdResetQueryPool-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdResetQueryPool-queryPool-parameter", "VUID-vkCmdResetQueryPool-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdWriteTimestamp(
VkCommandBuffer commandBuffer,
VkPipelineStageFlagBits pipelineStage,
VkQueryPool queryPool,
uint32_t query) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdWriteTimestamp-commandBuffer-parameter", "VUID-vkCmdWriteTimestamp-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdWriteTimestamp-queryPool-parameter", "VUID-vkCmdWriteTimestamp-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdCopyQueryPoolResults(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize stride,
VkQueryResultFlags flags) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdCopyQueryPoolResults-commandBuffer-parameter", "VUID-vkCmdCopyQueryPoolResults-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdCopyQueryPoolResults-queryPool-parameter", "VUID-vkCmdCopyQueryPoolResults-commonparent");
skip |= ValidateObject(commandBuffer, dstBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdCopyQueryPoolResults-dstBuffer-parameter", "VUID-vkCmdCopyQueryPoolResults-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdPushConstants(
VkCommandBuffer commandBuffer,
VkPipelineLayout layout,
VkShaderStageFlags stageFlags,
uint32_t offset,
uint32_t size,
const void* pValues) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdPushConstants-commandBuffer-parameter", "VUID-vkCmdPushConstants-commonparent");
skip |= ValidateObject(commandBuffer, layout, kVulkanObjectTypePipelineLayout, false, "VUID-vkCmdPushConstants-layout-parameter", "VUID-vkCmdPushConstants-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBeginRenderPass(
VkCommandBuffer commandBuffer,
const VkRenderPassBeginInfo* pRenderPassBegin,
VkSubpassContents contents) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginRenderPass-commandBuffer-parameter", kVUIDUndefined);
if (pRenderPassBegin) {
skip |= ValidateObject(commandBuffer, pRenderPassBegin->renderPass, kVulkanObjectTypeRenderPass, false, "VUID-VkRenderPassBeginInfo-renderPass-parameter", "VUID-VkRenderPassBeginInfo-commonparent");
skip |= ValidateObject(commandBuffer, pRenderPassBegin->framebuffer, kVulkanObjectTypeFramebuffer, false, "VUID-VkRenderPassBeginInfo-framebuffer-parameter", "VUID-VkRenderPassBeginInfo-commonparent");
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdNextSubpass(
VkCommandBuffer commandBuffer,
VkSubpassContents contents) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdNextSubpass-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndRenderPass(
VkCommandBuffer commandBuffer) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndRenderPass-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdExecuteCommands(
VkCommandBuffer commandBuffer,
uint32_t commandBufferCount,
const VkCommandBuffer* pCommandBuffers) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdExecuteCommands-commandBuffer-parameter", "VUID-vkCmdExecuteCommands-commonparent");
if (pCommandBuffers) {
for (uint32_t index0 = 0; index0 < commandBufferCount; ++index0) {
skip |= ValidateObject(commandBuffer, pCommandBuffers[index0], kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdExecuteCommands-pCommandBuffers-parameter", "VUID-vkCmdExecuteCommands-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateBindBufferMemory2(
VkDevice device,
uint32_t bindInfoCount,
const VkBindBufferMemoryInfo* pBindInfos) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindBufferMemory2-device-parameter", kVUIDUndefined);
if (pBindInfos) {
for (uint32_t index0 = 0; index0 < bindInfoCount; ++index0) {
skip |= ValidateObject(device, pBindInfos[index0].buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBindBufferMemoryInfo-buffer-parameter", "VUID-VkBindBufferMemoryInfo-commonparent");
skip |= ValidateObject(device, pBindInfos[index0].memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkBindBufferMemoryInfo-memory-parameter", "VUID-VkBindBufferMemoryInfo-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateBindImageMemory2(
VkDevice device,
uint32_t bindInfoCount,
const VkBindImageMemoryInfo* pBindInfos) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindImageMemory2-device-parameter", kVUIDUndefined);
if (pBindInfos) {
for (uint32_t index0 = 0; index0 < bindInfoCount; ++index0) {
skip |= ValidateObject(device, pBindInfos[index0].image, kVulkanObjectTypeImage, false, "VUID-VkBindImageMemoryInfo-image-parameter", "VUID-VkBindImageMemoryInfo-commonparent");
skip |= ValidateObject(device, pBindInfos[index0].memory, kVulkanObjectTypeDeviceMemory, true, kVUIDUndefined, "VUID-VkBindImageMemoryInfo-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDeviceGroupPeerMemoryFeatures(
VkDevice device,
uint32_t heapIndex,
uint32_t localDeviceIndex,
uint32_t remoteDeviceIndex,
VkPeerMemoryFeatureFlags* pPeerMemoryFeatures) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceGroupPeerMemoryFeatures-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetDeviceMask(
VkCommandBuffer commandBuffer,
uint32_t deviceMask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetDeviceMask-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDispatchBase(
VkCommandBuffer commandBuffer,
uint32_t baseGroupX,
uint32_t baseGroupY,
uint32_t baseGroupZ,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDispatchBase-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateEnumeratePhysicalDeviceGroups(
VkInstance instance,
uint32_t* pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkEnumeratePhysicalDeviceGroups-instance-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageMemoryRequirements2(
VkDevice device,
const VkImageMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageMemoryRequirements2-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->image, kVulkanObjectTypeImage, false, "VUID-VkImageMemoryRequirementsInfo2-image-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetBufferMemoryRequirements2(
VkDevice device,
const VkBufferMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetBufferMemoryRequirements2-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBufferMemoryRequirementsInfo2-buffer-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageSparseMemoryRequirements2(
VkDevice device,
const VkImageSparseMemoryRequirementsInfo2* pInfo,
uint32_t* pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements2* pSparseMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageSparseMemoryRequirements2-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->image, kVulkanObjectTypeImage, false, "VUID-VkImageSparseMemoryRequirementsInfo2-image-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceFeatures2(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceFeatures2* pFeatures) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceFeatures2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceProperties2(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties2* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceFormatProperties2(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties2* pFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceFormatProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceImageFormatProperties2(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo,
VkImageFormatProperties2* pImageFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceImageFormatProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceMemoryProperties2(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties2* pMemoryProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceMemoryProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSparseImageFormatProperties2(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo,
uint32_t* pPropertyCount,
VkSparseImageFormatProperties2* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSparseImageFormatProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateTrimCommandPool(
VkDevice device,
VkCommandPool commandPool,
VkCommandPoolTrimFlags flags) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkTrimCommandPool-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, commandPool, kVulkanObjectTypeCommandPool, false, "VUID-vkTrimCommandPool-commandPool-parameter", "VUID-vkTrimCommandPool-commandPool-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateSamplerYcbcrConversion(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateSamplerYcbcrConversion-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateSamplerYcbcrConversion(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pYcbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroySamplerYcbcrConversion(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroySamplerYcbcrConversion-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, ycbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion, true, "VUID-vkDestroySamplerYcbcrConversion-ycbcrConversion-parameter", "VUID-vkDestroySamplerYcbcrConversion-ycbcrConversion-parent");
skip |= ValidateDestroyObject(device, ycbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroySamplerYcbcrConversion(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, ycbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion);
}
bool ObjectLifetimes::PreCallValidateCreateDescriptorUpdateTemplate(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateDescriptorUpdateTemplate-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
skip |= ValidateObject(device, pCreateInfo->descriptorSetLayout, kVulkanObjectTypeDescriptorSetLayout, true, "VUID-VkDescriptorUpdateTemplateCreateInfo-descriptorSetLayout-parameter", "VUID-VkDescriptorUpdateTemplateCreateInfo-commonparent");
skip |= ValidateObject(device, pCreateInfo->pipelineLayout, kVulkanObjectTypePipelineLayout, true, kVUIDUndefined, "VUID-VkDescriptorUpdateTemplateCreateInfo-commonparent");
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDescriptorUpdateTemplate(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pDescriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyDescriptorUpdateTemplate(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyDescriptorUpdateTemplate-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, true, "VUID-vkDestroyDescriptorUpdateTemplate-descriptorUpdateTemplate-parameter", "VUID-vkDestroyDescriptorUpdateTemplate-descriptorUpdateTemplate-parent");
skip |= ValidateDestroyObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, pAllocator, "VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356", "VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyDescriptorUpdateTemplate(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate);
}
bool ObjectLifetimes::PreCallValidateUpdateDescriptorSetWithTemplate(
VkDevice device,
VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void* pData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkUpdateDescriptorSetWithTemplate-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorSet, kVulkanObjectTypeDescriptorSet, false, "VUID-vkUpdateDescriptorSetWithTemplate-descriptorSet-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, false, "VUID-vkUpdateDescriptorSetWithTemplate-descriptorUpdateTemplate-parameter", "VUID-vkUpdateDescriptorSetWithTemplate-descriptorUpdateTemplate-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalBufferProperties(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo,
VkExternalBufferProperties* pExternalBufferProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalBufferProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalFenceProperties(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo,
VkExternalFenceProperties* pExternalFenceProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalFenceProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalSemaphoreProperties(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo,
VkExternalSemaphoreProperties* pExternalSemaphoreProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalSemaphoreProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateDestroySurfaceKHR(
VkInstance instance,
VkSurfaceKHR surface,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkDestroySurfaceKHR-instance-parameter", kVUIDUndefined);
skip |= ValidateObject(instance, surface, kVulkanObjectTypeSurfaceKHR, true, "VUID-vkDestroySurfaceKHR-surface-parameter", "VUID-vkDestroySurfaceKHR-surface-parent");
skip |= ValidateDestroyObject(instance, surface, kVulkanObjectTypeSurfaceKHR, pAllocator, "VUID-vkDestroySurfaceKHR-surface-01267", "VUID-vkDestroySurfaceKHR-surface-01268");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroySurfaceKHR(
VkInstance instance,
VkSurfaceKHR surface,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(instance, surface, kVulkanObjectTypeSurfaceKHR);
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfaceSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
VkSurfaceKHR surface,
VkBool32* pSupported) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfaceSupportKHR-physicalDevice-parameter", "VUID-vkGetPhysicalDeviceSurfaceSupportKHR-commonparent");
skip |= ValidateObject(physicalDevice, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetPhysicalDeviceSurfaceSupportKHR-surface-parameter", "VUID-vkGetPhysicalDeviceSurfaceSupportKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfaceCapabilitiesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
VkSurfaceCapabilitiesKHR* pSurfaceCapabilities) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfaceCapabilitiesKHR-physicalDevice-parameter", "VUID-vkGetPhysicalDeviceSurfaceCapabilitiesKHR-commonparent");
skip |= ValidateObject(physicalDevice, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetPhysicalDeviceSurfaceCapabilitiesKHR-surface-parameter", "VUID-vkGetPhysicalDeviceSurfaceCapabilitiesKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pSurfaceFormatCount,
VkSurfaceFormatKHR* pSurfaceFormats) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfaceFormatsKHR-physicalDevice-parameter", "VUID-vkGetPhysicalDeviceSurfaceFormatsKHR-commonparent");
skip |= ValidateObject(physicalDevice, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetPhysicalDeviceSurfaceFormatsKHR-surface-parameter", "VUID-vkGetPhysicalDeviceSurfaceFormatsKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfacePresentModesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pPresentModeCount,
VkPresentModeKHR* pPresentModes) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfacePresentModesKHR-physicalDevice-parameter", "VUID-vkGetPhysicalDeviceSurfacePresentModesKHR-commonparent");
skip |= ValidateObject(physicalDevice, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetPhysicalDeviceSurfacePresentModesKHR-surface-parameter", "VUID-vkGetPhysicalDeviceSurfacePresentModesKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateSwapchainKHR(
VkDevice device,
const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchain) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateSwapchainKHR-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
skip |= ValidateObject(device, pCreateInfo->surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-VkSwapchainCreateInfoKHR-surface-parameter", "VUID-VkSwapchainCreateInfoKHR-commonparent");
skip |= ValidateObject(device, pCreateInfo->oldSwapchain, kVulkanObjectTypeSwapchainKHR, true, "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parameter", "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parent");
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateSwapchainKHR(
VkDevice device,
const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchain,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pSwapchain, kVulkanObjectTypeSwapchainKHR, pAllocator);
}
bool ObjectLifetimes::PreCallValidateAcquireNextImageKHR(
VkDevice device,
VkSwapchainKHR swapchain,
uint64_t timeout,
VkSemaphore semaphore,
VkFence fence,
uint32_t* pImageIndex) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkAcquireNextImageKHR-device-parameter", "VUID-vkAcquireNextImageKHR-commonparent");
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkAcquireNextImageKHR-swapchain-parameter", "VUID-vkAcquireNextImageKHR-commonparent");
skip |= ValidateObject(device, semaphore, kVulkanObjectTypeSemaphore, true, "VUID-vkAcquireNextImageKHR-semaphore-parameter", "VUID-vkAcquireNextImageKHR-semaphore-parent");
skip |= ValidateObject(device, fence, kVulkanObjectTypeFence, true, "VUID-vkAcquireNextImageKHR-fence-parameter", "VUID-vkAcquireNextImageKHR-fence-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateQueuePresentKHR(
VkQueue queue,
const VkPresentInfoKHR* pPresentInfo) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueuePresentKHR-queue-parameter", kVUIDUndefined);
if (pPresentInfo) {
if (pPresentInfo->pWaitSemaphores) {
for (uint32_t index1 = 0; index1 < pPresentInfo->waitSemaphoreCount; ++index1) {
skip |= ValidateObject(queue, pPresentInfo->pWaitSemaphores[index1], kVulkanObjectTypeSemaphore, false, "VUID-VkPresentInfoKHR-pWaitSemaphores-parameter", "VUID-VkPresentInfoKHR-commonparent");
}
}
if (pPresentInfo->pSwapchains) {
for (uint32_t index1 = 0; index1 < pPresentInfo->swapchainCount; ++index1) {
skip |= ValidateObject(queue, pPresentInfo->pSwapchains[index1], kVulkanObjectTypeSwapchainKHR, false, "VUID-VkPresentInfoKHR-pSwapchains-parameter", "VUID-VkPresentInfoKHR-commonparent");
}
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDeviceGroupPresentCapabilitiesKHR(
VkDevice device,
VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceGroupPresentCapabilitiesKHR-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDeviceGroupSurfacePresentModesKHR(
VkDevice device,
VkSurfaceKHR surface,
VkDeviceGroupPresentModeFlagsKHR* pModes) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceGroupSurfacePresentModesKHR-device-parameter", "VUID-vkGetDeviceGroupSurfacePresentModesKHR-commonparent");
skip |= ValidateObject(device, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetDeviceGroupSurfacePresentModesKHR-surface-parameter", "VUID-vkGetDeviceGroupSurfacePresentModesKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDevicePresentRectanglesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pRectCount,
VkRect2D* pRects) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDevicePresentRectanglesKHR-physicalDevice-parameter", "VUID-vkGetPhysicalDevicePresentRectanglesKHR-commonparent");
skip |= ValidateObject(physicalDevice, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-parameter", "VUID-vkGetPhysicalDevicePresentRectanglesKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateAcquireNextImage2KHR(
VkDevice device,
const VkAcquireNextImageInfoKHR* pAcquireInfo,
uint32_t* pImageIndex) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkAcquireNextImage2KHR-device-parameter", kVUIDUndefined);
if (pAcquireInfo) {
skip |= ValidateObject(device, pAcquireInfo->swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-VkAcquireNextImageInfoKHR-swapchain-parameter", "VUID-VkAcquireNextImageInfoKHR-commonparent");
skip |= ValidateObject(device, pAcquireInfo->semaphore, kVulkanObjectTypeSemaphore, true, "VUID-VkAcquireNextImageInfoKHR-semaphore-parameter", "VUID-VkAcquireNextImageInfoKHR-commonparent");
skip |= ValidateObject(device, pAcquireInfo->fence, kVulkanObjectTypeFence, true, "VUID-VkAcquireNextImageInfoKHR-fence-parameter", "VUID-VkAcquireNextImageInfoKHR-commonparent");
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceDisplayPlanePropertiesKHR(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkDisplayPlanePropertiesKHR* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceDisplayPlanePropertiesKHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(
VkPhysicalDevice physicalDevice,
uint32_t planeIndex,
uint32_t* pDisplayCount,
VkDisplayKHR* pDisplays) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetDisplayPlaneSupportedDisplaysKHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordGetDisplayPlaneSupportedDisplaysKHR(
VkPhysicalDevice physicalDevice,
uint32_t planeIndex,
uint32_t* pDisplayCount,
VkDisplayKHR* pDisplays,
VkResult result) {
if (result != VK_SUCCESS) return;
if (pDisplays) {
for (uint32_t index = 0; index < *pDisplayCount; index++) {
CreateObject(physicalDevice, pDisplays[index], kVulkanObjectTypeDisplayKHR, nullptr);
}
}
}
bool ObjectLifetimes::PreCallValidateCreateDisplayModeKHR(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display,
const VkDisplayModeCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDisplayModeKHR* pMode) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkCreateDisplayModeKHR-physicalDevice-parameter", kVUIDUndefined);
skip |= ValidateObject(physicalDevice, display, kVulkanObjectTypeDisplayKHR, false, "VUID-vkCreateDisplayModeKHR-display-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDisplayModeKHR(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display,
const VkDisplayModeCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDisplayModeKHR* pMode,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(physicalDevice, *pMode, kVulkanObjectTypeDisplayModeKHR, pAllocator);
}
bool ObjectLifetimes::PreCallValidateGetDisplayPlaneCapabilitiesKHR(
VkPhysicalDevice physicalDevice,
VkDisplayModeKHR mode,
uint32_t planeIndex,
VkDisplayPlaneCapabilitiesKHR* pCapabilities) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetDisplayPlaneCapabilitiesKHR-physicalDevice-parameter", kVUIDUndefined);
skip |= ValidateObject(physicalDevice, mode, kVulkanObjectTypeDisplayModeKHR, false, "VUID-vkGetDisplayPlaneCapabilitiesKHR-mode-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateDisplayPlaneSurfaceKHR(
VkInstance instance,
const VkDisplaySurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateDisplayPlaneSurfaceKHR-instance-parameter", kVUIDUndefined);
if (pCreateInfo) {
skip |= ValidateObject(instance, pCreateInfo->displayMode, kVulkanObjectTypeDisplayModeKHR, false, "VUID-VkDisplaySurfaceCreateInfoKHR-displayMode-parameter", kVUIDUndefined);
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDisplayPlaneSurfaceKHR(
VkInstance instance,
const VkDisplaySurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
bool ObjectLifetimes::PreCallValidateCreateSharedSwapchainsKHR(
VkDevice device,
uint32_t swapchainCount,
const VkSwapchainCreateInfoKHR* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchains) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateSharedSwapchainsKHR-device-parameter", kVUIDUndefined);
if (pCreateInfos) {
for (uint32_t index0 = 0; index0 < swapchainCount; ++index0) {
skip |= ValidateObject(device, pCreateInfos[index0].surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-VkSwapchainCreateInfoKHR-surface-parameter", "VUID-VkSwapchainCreateInfoKHR-commonparent");
skip |= ValidateObject(device, pCreateInfos[index0].oldSwapchain, kVulkanObjectTypeSwapchainKHR, true, "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parameter", "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parent");
}
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateSharedSwapchainsKHR(
VkDevice device,
uint32_t swapchainCount,
const VkSwapchainCreateInfoKHR* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchains,
VkResult result) {
if (result != VK_SUCCESS) return;
if (pSwapchains) {
for (uint32_t index = 0; index < swapchainCount; index++) {
CreateObject(device, pSwapchains[index], kVulkanObjectTypeSwapchainKHR, pAllocator);
}
}
}
#ifdef VK_USE_PLATFORM_XLIB_KHR
bool ObjectLifetimes::PreCallValidateCreateXlibSurfaceKHR(
VkInstance instance,
const VkXlibSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateXlibSurfaceKHR-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateXlibSurfaceKHR(
VkInstance instance,
const VkXlibSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_XLIB_KHR
#ifdef VK_USE_PLATFORM_XLIB_KHR
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceXlibPresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
Display* dpy,
VisualID visualID) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceXlibPresentationSupportKHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_XLIB_KHR
#ifdef VK_USE_PLATFORM_XCB_KHR
bool ObjectLifetimes::PreCallValidateCreateXcbSurfaceKHR(
VkInstance instance,
const VkXcbSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateXcbSurfaceKHR-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateXcbSurfaceKHR(
VkInstance instance,
const VkXcbSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_XCB_KHR
#ifdef VK_USE_PLATFORM_XCB_KHR
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceXcbPresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
xcb_connection_t* connection,
xcb_visualid_t visual_id) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceXcbPresentationSupportKHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_XCB_KHR
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
bool ObjectLifetimes::PreCallValidateCreateWaylandSurfaceKHR(
VkInstance instance,
const VkWaylandSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateWaylandSurfaceKHR-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateWaylandSurfaceKHR(
VkInstance instance,
const VkWaylandSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_WAYLAND_KHR
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceWaylandPresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
struct wl_display* display) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceWaylandPresentationSupportKHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_WAYLAND_KHR
#ifdef VK_USE_PLATFORM_ANDROID_KHR
bool ObjectLifetimes::PreCallValidateCreateAndroidSurfaceKHR(
VkInstance instance,
const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateAndroidSurfaceKHR-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateAndroidSurfaceKHR(
VkInstance instance,
const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_ANDROID_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateCreateWin32SurfaceKHR(
VkInstance instance,
const VkWin32SurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateWin32SurfaceKHR-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateWin32SurfaceKHR(
VkInstance instance,
const VkWin32SurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceWin32PresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceWin32PresentationSupportKHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceFeatures2KHR(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceFeatures2* pFeatures) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceFeatures2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceProperties2KHR(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties2* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceFormatProperties2KHR(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties2* pFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceFormatProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceImageFormatProperties2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo,
VkImageFormatProperties2* pImageFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceImageFormatProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceMemoryProperties2KHR(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties2* pMemoryProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceMemoryProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSparseImageFormatProperties2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo,
uint32_t* pPropertyCount,
VkSparseImageFormatProperties2* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSparseImageFormatProperties2-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDeviceGroupPeerMemoryFeaturesKHR(
VkDevice device,
uint32_t heapIndex,
uint32_t localDeviceIndex,
uint32_t remoteDeviceIndex,
VkPeerMemoryFeatureFlags* pPeerMemoryFeatures) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceGroupPeerMemoryFeatures-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetDeviceMaskKHR(
VkCommandBuffer commandBuffer,
uint32_t deviceMask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetDeviceMask-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDispatchBaseKHR(
VkCommandBuffer commandBuffer,
uint32_t baseGroupX,
uint32_t baseGroupY,
uint32_t baseGroupZ,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDispatchBase-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateTrimCommandPoolKHR(
VkDevice device,
VkCommandPool commandPool,
VkCommandPoolTrimFlags flags) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkTrimCommandPool-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, commandPool, kVulkanObjectTypeCommandPool, false, "VUID-vkTrimCommandPool-commandPool-parameter", "VUID-vkTrimCommandPool-commandPool-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateEnumeratePhysicalDeviceGroupsKHR(
VkInstance instance,
uint32_t* pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkEnumeratePhysicalDeviceGroups-instance-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalBufferPropertiesKHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo,
VkExternalBufferProperties* pExternalBufferProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalBufferProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetMemoryWin32HandleKHR(
VkDevice device,
const VkMemoryGetWin32HandleInfoKHR* pGetWin32HandleInfo,
HANDLE* pHandle) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryWin32HandleKHR-device-parameter", kVUIDUndefined);
if (pGetWin32HandleInfo) {
skip |= ValidateObject(device, pGetWin32HandleInfo->memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkMemoryGetWin32HandleInfoKHR-memory-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetMemoryWin32HandlePropertiesKHR(
VkDevice device,
VkExternalMemoryHandleTypeFlagBits handleType,
HANDLE handle,
VkMemoryWin32HandlePropertiesKHR* pMemoryWin32HandleProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryWin32HandlePropertiesKHR-device-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetMemoryFdKHR(
VkDevice device,
const VkMemoryGetFdInfoKHR* pGetFdInfo,
int* pFd) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryFdKHR-device-parameter", kVUIDUndefined);
if (pGetFdInfo) {
skip |= ValidateObject(device, pGetFdInfo->memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkMemoryGetFdInfoKHR-memory-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetMemoryFdPropertiesKHR(
VkDevice device,
VkExternalMemoryHandleTypeFlagBits handleType,
int fd,
VkMemoryFdPropertiesKHR* pMemoryFdProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryFdPropertiesKHR-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalSemaphorePropertiesKHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo,
VkExternalSemaphoreProperties* pExternalSemaphoreProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalSemaphoreProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateImportSemaphoreWin32HandleKHR(
VkDevice device,
const VkImportSemaphoreWin32HandleInfoKHR* pImportSemaphoreWin32HandleInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkImportSemaphoreWin32HandleKHR-device-parameter", kVUIDUndefined);
if (pImportSemaphoreWin32HandleInfo) {
skip |= ValidateObject(device, pImportSemaphoreWin32HandleInfo->semaphore, kVulkanObjectTypeSemaphore, false, "VUID-VkImportSemaphoreWin32HandleInfoKHR-semaphore-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetSemaphoreWin32HandleKHR(
VkDevice device,
const VkSemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo,
HANDLE* pHandle) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetSemaphoreWin32HandleKHR-device-parameter", kVUIDUndefined);
if (pGetWin32HandleInfo) {
skip |= ValidateObject(device, pGetWin32HandleInfo->semaphore, kVulkanObjectTypeSemaphore, false, "VUID-VkSemaphoreGetWin32HandleInfoKHR-semaphore-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateImportSemaphoreFdKHR(
VkDevice device,
const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkImportSemaphoreFdKHR-device-parameter", kVUIDUndefined);
if (pImportSemaphoreFdInfo) {
skip |= ValidateObject(device, pImportSemaphoreFdInfo->semaphore, kVulkanObjectTypeSemaphore, false, "VUID-VkImportSemaphoreFdInfoKHR-semaphore-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetSemaphoreFdKHR(
VkDevice device,
const VkSemaphoreGetFdInfoKHR* pGetFdInfo,
int* pFd) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetSemaphoreFdKHR-device-parameter", kVUIDUndefined);
if (pGetFdInfo) {
skip |= ValidateObject(device, pGetFdInfo->semaphore, kVulkanObjectTypeSemaphore, false, "VUID-VkSemaphoreGetFdInfoKHR-semaphore-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdPushDescriptorSetWithTemplateKHR(
VkCommandBuffer commandBuffer,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
VkPipelineLayout layout,
uint32_t set,
const void* pData) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-parameter", "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commonparent");
skip |= ValidateObject(commandBuffer, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, false, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-descriptorUpdateTemplate-parameter", "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commonparent");
skip |= ValidateObject(commandBuffer, layout, kVulkanObjectTypePipelineLayout, false, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-layout-parameter", "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateDescriptorUpdateTemplateKHR(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateDescriptorUpdateTemplate-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
skip |= ValidateObject(device, pCreateInfo->descriptorSetLayout, kVulkanObjectTypeDescriptorSetLayout, true, "VUID-VkDescriptorUpdateTemplateCreateInfo-descriptorSetLayout-parameter", "VUID-VkDescriptorUpdateTemplateCreateInfo-commonparent");
skip |= ValidateObject(device, pCreateInfo->pipelineLayout, kVulkanObjectTypePipelineLayout, true, kVUIDUndefined, "VUID-VkDescriptorUpdateTemplateCreateInfo-commonparent");
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDescriptorUpdateTemplateKHR(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pDescriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyDescriptorUpdateTemplateKHR(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyDescriptorUpdateTemplate-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, true, "VUID-vkDestroyDescriptorUpdateTemplate-descriptorUpdateTemplate-parameter", "VUID-vkDestroyDescriptorUpdateTemplate-descriptorUpdateTemplate-parent");
skip |= ValidateDestroyObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, pAllocator, "VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356", "VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357");
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyDescriptorUpdateTemplateKHR(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate);
}
bool ObjectLifetimes::PreCallValidateUpdateDescriptorSetWithTemplateKHR(
VkDevice device,
VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void* pData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkUpdateDescriptorSetWithTemplate-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorSet, kVulkanObjectTypeDescriptorSet, false, "VUID-vkUpdateDescriptorSetWithTemplate-descriptorSet-parameter", kVUIDUndefined);
skip |= ValidateObject(device, descriptorUpdateTemplate, kVulkanObjectTypeDescriptorUpdateTemplate, false, "VUID-vkUpdateDescriptorSetWithTemplate-descriptorUpdateTemplate-parameter", "VUID-vkUpdateDescriptorSetWithTemplate-descriptorUpdateTemplate-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateRenderPass2KHR(
VkDevice device,
const VkRenderPassCreateInfo2KHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateRenderPass2KHR-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateRenderPass2KHR(
VkDevice device,
const VkRenderPassCreateInfo2KHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pRenderPass, kVulkanObjectTypeRenderPass, pAllocator);
}
bool ObjectLifetimes::PreCallValidateCmdBeginRenderPass2KHR(
VkCommandBuffer commandBuffer,
const VkRenderPassBeginInfo* pRenderPassBegin,
const VkSubpassBeginInfoKHR* pSubpassBeginInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginRenderPass2KHR-commandBuffer-parameter", kVUIDUndefined);
if (pRenderPassBegin) {
skip |= ValidateObject(commandBuffer, pRenderPassBegin->renderPass, kVulkanObjectTypeRenderPass, false, "VUID-VkRenderPassBeginInfo-renderPass-parameter", "VUID-VkRenderPassBeginInfo-commonparent");
skip |= ValidateObject(commandBuffer, pRenderPassBegin->framebuffer, kVulkanObjectTypeFramebuffer, false, "VUID-VkRenderPassBeginInfo-framebuffer-parameter", "VUID-VkRenderPassBeginInfo-commonparent");
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdNextSubpass2KHR(
VkCommandBuffer commandBuffer,
const VkSubpassBeginInfoKHR* pSubpassBeginInfo,
const VkSubpassEndInfoKHR* pSubpassEndInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdNextSubpass2KHR-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndRenderPass2KHR(
VkCommandBuffer commandBuffer,
const VkSubpassEndInfoKHR* pSubpassEndInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndRenderPass2KHR-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetSwapchainStatusKHR(
VkDevice device,
VkSwapchainKHR swapchain) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetSwapchainStatusKHR-device-parameter", "VUID-vkGetSwapchainStatusKHR-commonparent");
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkGetSwapchainStatusKHR-swapchain-parameter", "VUID-vkGetSwapchainStatusKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalFencePropertiesKHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo,
VkExternalFenceProperties* pExternalFenceProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalFenceProperties-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateImportFenceWin32HandleKHR(
VkDevice device,
const VkImportFenceWin32HandleInfoKHR* pImportFenceWin32HandleInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkImportFenceWin32HandleKHR-device-parameter", kVUIDUndefined);
if (pImportFenceWin32HandleInfo) {
skip |= ValidateObject(device, pImportFenceWin32HandleInfo->fence, kVulkanObjectTypeFence, false, "VUID-VkImportFenceWin32HandleInfoKHR-fence-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetFenceWin32HandleKHR(
VkDevice device,
const VkFenceGetWin32HandleInfoKHR* pGetWin32HandleInfo,
HANDLE* pHandle) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetFenceWin32HandleKHR-device-parameter", kVUIDUndefined);
if (pGetWin32HandleInfo) {
skip |= ValidateObject(device, pGetWin32HandleInfo->fence, kVulkanObjectTypeFence, false, "VUID-VkFenceGetWin32HandleInfoKHR-fence-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateImportFenceFdKHR(
VkDevice device,
const VkImportFenceFdInfoKHR* pImportFenceFdInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkImportFenceFdKHR-device-parameter", kVUIDUndefined);
if (pImportFenceFdInfo) {
skip |= ValidateObject(device, pImportFenceFdInfo->fence, kVulkanObjectTypeFence, false, "VUID-VkImportFenceFdInfoKHR-fence-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetFenceFdKHR(
VkDevice device,
const VkFenceGetFdInfoKHR* pGetFdInfo,
int* pFd) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetFenceFdKHR-device-parameter", kVUIDUndefined);
if (pGetFdInfo) {
skip |= ValidateObject(device, pGetFdInfo->fence, kVulkanObjectTypeFence, false, "VUID-VkFenceGetFdInfoKHR-fence-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfaceCapabilities2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfaceCapabilities2KHR-physicalDevice-parameter", kVUIDUndefined);
if (pSurfaceInfo) {
skip |= ValidateObject(physicalDevice, pSurfaceInfo->surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-VkPhysicalDeviceSurfaceInfo2KHR-surface-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfaceFormats2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
uint32_t* pSurfaceFormatCount,
VkSurfaceFormat2KHR* pSurfaceFormats) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfaceFormats2KHR-physicalDevice-parameter", kVUIDUndefined);
if (pSurfaceInfo) {
skip |= ValidateObject(physicalDevice, pSurfaceInfo->surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-VkPhysicalDeviceSurfaceInfo2KHR-surface-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceDisplayPlaneProperties2KHR(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkDisplayPlaneProperties2KHR* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceDisplayPlaneProperties2KHR-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetDisplayPlaneCapabilities2KHR(
VkPhysicalDevice physicalDevice,
const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
VkDisplayPlaneCapabilities2KHR* pCapabilities) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetDisplayPlaneCapabilities2KHR-physicalDevice-parameter", kVUIDUndefined);
if (pDisplayPlaneInfo) {
skip |= ValidateObject(physicalDevice, pDisplayPlaneInfo->mode, kVulkanObjectTypeDisplayModeKHR, false, "VUID-VkDisplayPlaneInfo2KHR-mode-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageMemoryRequirements2KHR(
VkDevice device,
const VkImageMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageMemoryRequirements2-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->image, kVulkanObjectTypeImage, false, "VUID-VkImageMemoryRequirementsInfo2-image-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetBufferMemoryRequirements2KHR(
VkDevice device,
const VkBufferMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetBufferMemoryRequirements2-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBufferMemoryRequirementsInfo2-buffer-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageSparseMemoryRequirements2KHR(
VkDevice device,
const VkImageSparseMemoryRequirementsInfo2* pInfo,
uint32_t* pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements2* pSparseMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageSparseMemoryRequirements2-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->image, kVulkanObjectTypeImage, false, "VUID-VkImageSparseMemoryRequirementsInfo2-image-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateSamplerYcbcrConversionKHR(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateSamplerYcbcrConversion-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateSamplerYcbcrConversionKHR(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pYcbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroySamplerYcbcrConversionKHR(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroySamplerYcbcrConversion-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, ycbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion, true, "VUID-vkDestroySamplerYcbcrConversion-ycbcrConversion-parameter", "VUID-vkDestroySamplerYcbcrConversion-ycbcrConversion-parent");
skip |= ValidateDestroyObject(device, ycbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroySamplerYcbcrConversionKHR(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, ycbcrConversion, kVulkanObjectTypeSamplerYcbcrConversion);
}
bool ObjectLifetimes::PreCallValidateBindBufferMemory2KHR(
VkDevice device,
uint32_t bindInfoCount,
const VkBindBufferMemoryInfo* pBindInfos) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindBufferMemory2-device-parameter", kVUIDUndefined);
if (pBindInfos) {
for (uint32_t index0 = 0; index0 < bindInfoCount; ++index0) {
skip |= ValidateObject(device, pBindInfos[index0].buffer, kVulkanObjectTypeBuffer, false, "VUID-VkBindBufferMemoryInfo-buffer-parameter", "VUID-VkBindBufferMemoryInfo-commonparent");
skip |= ValidateObject(device, pBindInfos[index0].memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkBindBufferMemoryInfo-memory-parameter", "VUID-VkBindBufferMemoryInfo-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateBindImageMemory2KHR(
VkDevice device,
uint32_t bindInfoCount,
const VkBindImageMemoryInfo* pBindInfos) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindImageMemory2-device-parameter", kVUIDUndefined);
if (pBindInfos) {
for (uint32_t index0 = 0; index0 < bindInfoCount; ++index0) {
skip |= ValidateObject(device, pBindInfos[index0].image, kVulkanObjectTypeImage, false, "VUID-VkBindImageMemoryInfo-image-parameter", "VUID-VkBindImageMemoryInfo-commonparent");
skip |= ValidateObject(device, pBindInfos[index0].memory, kVulkanObjectTypeDeviceMemory, true, kVUIDUndefined, "VUID-VkBindImageMemoryInfo-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndirectCountKHR(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndirectCountKHR-commandBuffer-parameter", "VUID-vkCmdDrawIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndirectCountKHR-buffer-parameter", "VUID-vkCmdDrawIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, countBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndirectCountKHR-countBuffer-parameter", "VUID-vkCmdDrawIndirectCountKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndexedIndirectCountKHR(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndexedIndirectCountKHR-commandBuffer-parameter", "VUID-vkCmdDrawIndexedIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndexedIndirectCountKHR-buffer-parameter", "VUID-vkCmdDrawIndexedIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, countBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndexedIndirectCountKHR-countBuffer-parameter", "VUID-vkCmdDrawIndexedIndirectCountKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPipelineExecutablePropertiesKHR(
VkDevice device,
const VkPipelineInfoKHR* pPipelineInfo,
uint32_t* pExecutableCount,
VkPipelineExecutablePropertiesKHR* pProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetPipelineExecutablePropertiesKHR-device-parameter", kVUIDUndefined);
if (pPipelineInfo) {
skip |= ValidateObject(device, pPipelineInfo->pipeline, kVulkanObjectTypePipeline, false, "VUID-VkPipelineInfoKHR-pipeline-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPipelineExecutableStatisticsKHR(
VkDevice device,
const VkPipelineExecutableInfoKHR* pExecutableInfo,
uint32_t* pStatisticCount,
VkPipelineExecutableStatisticKHR* pStatistics) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetPipelineExecutableStatisticsKHR-device-parameter", kVUIDUndefined);
if (pExecutableInfo) {
skip |= ValidateObject(device, pExecutableInfo->pipeline, kVulkanObjectTypePipeline, false, "VUID-VkPipelineExecutableInfoKHR-pipeline-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPipelineExecutableInternalRepresentationsKHR(
VkDevice device,
const VkPipelineExecutableInfoKHR* pExecutableInfo,
uint32_t* pInternalRepresentationCount,
VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetPipelineExecutableInternalRepresentationsKHR-device-parameter", kVUIDUndefined);
if (pExecutableInfo) {
skip |= ValidateObject(device, pExecutableInfo->pipeline, kVulkanObjectTypePipeline, false, "VUID-VkPipelineExecutableInfoKHR-pipeline-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateDebugReportCallbackEXT(
VkInstance instance,
const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugReportCallbackEXT* pCallback) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateDebugReportCallbackEXT-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDebugReportCallbackEXT(
VkInstance instance,
const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugReportCallbackEXT* pCallback,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pCallback, kVulkanObjectTypeDebugReportCallbackEXT, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyDebugReportCallbackEXT(
VkInstance instance,
VkDebugReportCallbackEXT callback,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkDestroyDebugReportCallbackEXT-instance-parameter", kVUIDUndefined);
skip |= ValidateObject(instance, callback, kVulkanObjectTypeDebugReportCallbackEXT, false, "VUID-vkDestroyDebugReportCallbackEXT-callback-parameter", "VUID-vkDestroyDebugReportCallbackEXT-callback-parent");
skip |= ValidateDestroyObject(instance, callback, kVulkanObjectTypeDebugReportCallbackEXT, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyDebugReportCallbackEXT(
VkInstance instance,
VkDebugReportCallbackEXT callback,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(instance, callback, kVulkanObjectTypeDebugReportCallbackEXT);
}
bool ObjectLifetimes::PreCallValidateDebugReportMessageEXT(
VkInstance instance,
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t location,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkDebugReportMessageEXT-instance-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateDebugMarkerSetObjectTagEXT(
VkDevice device,
const VkDebugMarkerObjectTagInfoEXT* pTagInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDebugMarkerSetObjectTagEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateDebugMarkerSetObjectNameEXT(
VkDevice device,
const VkDebugMarkerObjectNameInfoEXT* pNameInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDebugMarkerSetObjectNameEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDebugMarkerBeginEXT(
VkCommandBuffer commandBuffer,
const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDebugMarkerBeginEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDebugMarkerEndEXT(
VkCommandBuffer commandBuffer) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDebugMarkerEndEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDebugMarkerInsertEXT(
VkCommandBuffer commandBuffer,
const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDebugMarkerInsertEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBindTransformFeedbackBuffersEXT(
VkCommandBuffer commandBuffer,
uint32_t firstBinding,
uint32_t bindingCount,
const VkBuffer* pBuffers,
const VkDeviceSize* pOffsets,
const VkDeviceSize* pSizes) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBindTransformFeedbackBuffersEXT-commandBuffer-parameter", "VUID-vkCmdBindTransformFeedbackBuffersEXT-commonparent");
if (pBuffers) {
for (uint32_t index0 = 0; index0 < bindingCount; ++index0) {
skip |= ValidateObject(commandBuffer, pBuffers[index0], kVulkanObjectTypeBuffer, false, "VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-parameter", "VUID-vkCmdBindTransformFeedbackBuffersEXT-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBeginTransformFeedbackEXT(
VkCommandBuffer commandBuffer,
uint32_t firstCounterBuffer,
uint32_t counterBufferCount,
const VkBuffer* pCounterBuffers,
const VkDeviceSize* pCounterBufferOffsets) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginTransformFeedbackEXT-commandBuffer-parameter", "VUID-vkCmdBeginTransformFeedbackEXT-commonparent");
if (pCounterBuffers) {
for (uint32_t index0 = 0; index0 < counterBufferCount; ++index0) {
skip |= ValidateObject(commandBuffer, pCounterBuffers[index0], kVulkanObjectTypeBuffer, true, kVUIDUndefined, "VUID-vkCmdBeginTransformFeedbackEXT-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndTransformFeedbackEXT(
VkCommandBuffer commandBuffer,
uint32_t firstCounterBuffer,
uint32_t counterBufferCount,
const VkBuffer* pCounterBuffers,
const VkDeviceSize* pCounterBufferOffsets) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndTransformFeedbackEXT-commandBuffer-parameter", "VUID-vkCmdEndTransformFeedbackEXT-commonparent");
if (pCounterBuffers) {
for (uint32_t index0 = 0; index0 < counterBufferCount; ++index0) {
skip |= ValidateObject(commandBuffer, pCounterBuffers[index0], kVulkanObjectTypeBuffer, true, kVUIDUndefined, "VUID-vkCmdEndTransformFeedbackEXT-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBeginQueryIndexedEXT(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query,
VkQueryControlFlags flags,
uint32_t index) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginQueryIndexedEXT-commandBuffer-parameter", "VUID-vkCmdBeginQueryIndexedEXT-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdBeginQueryIndexedEXT-queryPool-parameter", "VUID-vkCmdBeginQueryIndexedEXT-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndQueryIndexedEXT(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query,
uint32_t index) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndQueryIndexedEXT-commandBuffer-parameter", "VUID-vkCmdEndQueryIndexedEXT-commonparent");
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdEndQueryIndexedEXT-queryPool-parameter", "VUID-vkCmdEndQueryIndexedEXT-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndirectByteCountEXT(
VkCommandBuffer commandBuffer,
uint32_t instanceCount,
uint32_t firstInstance,
VkBuffer counterBuffer,
VkDeviceSize counterBufferOffset,
uint32_t counterOffset,
uint32_t vertexStride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndirectByteCountEXT-commandBuffer-parameter", "VUID-vkCmdDrawIndirectByteCountEXT-commonparent");
skip |= ValidateObject(commandBuffer, counterBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndirectByteCountEXT-counterBuffer-parameter", "VUID-vkCmdDrawIndirectByteCountEXT-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageViewHandleNVX(
VkDevice device,
const VkImageViewHandleInfoNVX* pInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageViewHandleNVX-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndirectCountAMD(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndirectCountKHR-commandBuffer-parameter", "VUID-vkCmdDrawIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndirectCountKHR-buffer-parameter", "VUID-vkCmdDrawIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, countBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndirectCountKHR-countBuffer-parameter", "VUID-vkCmdDrawIndirectCountKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawIndexedIndirectCountAMD(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawIndexedIndirectCountKHR-commandBuffer-parameter", "VUID-vkCmdDrawIndexedIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndexedIndirectCountKHR-buffer-parameter", "VUID-vkCmdDrawIndexedIndirectCountKHR-commonparent");
skip |= ValidateObject(commandBuffer, countBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawIndexedIndirectCountKHR-countBuffer-parameter", "VUID-vkCmdDrawIndexedIndirectCountKHR-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetShaderInfoAMD(
VkDevice device,
VkPipeline pipeline,
VkShaderStageFlagBits shaderStage,
VkShaderInfoTypeAMD infoType,
size_t* pInfoSize,
void* pInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetShaderInfoAMD-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipeline, kVulkanObjectTypePipeline, false, "VUID-vkGetShaderInfoAMD-pipeline-parameter", "VUID-vkGetShaderInfoAMD-pipeline-parent");
return skip;
}
#ifdef VK_USE_PLATFORM_GGP
bool ObjectLifetimes::PreCallValidateCreateStreamDescriptorSurfaceGGP(
VkInstance instance,
const VkStreamDescriptorSurfaceCreateInfoGGP* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateStreamDescriptorSurfaceGGP-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateStreamDescriptorSurfaceGGP(
VkInstance instance,
const VkStreamDescriptorSurfaceCreateInfoGGP* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_GGP
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceExternalImageFormatPropertiesNV(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkImageType type,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkExternalMemoryHandleTypeFlagsNV externalHandleType,
VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceExternalImageFormatPropertiesNV-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetMemoryWin32HandleNV(
VkDevice device,
VkDeviceMemory memory,
VkExternalMemoryHandleTypeFlagsNV handleType,
HANDLE* pHandle) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryWin32HandleNV-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, memory, kVulkanObjectTypeDeviceMemory, false, "VUID-vkGetMemoryWin32HandleNV-memory-parameter", "VUID-vkGetMemoryWin32HandleNV-memory-parent");
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_VI_NN
bool ObjectLifetimes::PreCallValidateCreateViSurfaceNN(
VkInstance instance,
const VkViSurfaceCreateInfoNN* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateViSurfaceNN-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateViSurfaceNN(
VkInstance instance,
const VkViSurfaceCreateInfoNN* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_VI_NN
bool ObjectLifetimes::PreCallValidateCmdBeginConditionalRenderingEXT(
VkCommandBuffer commandBuffer,
const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginConditionalRenderingEXT-commandBuffer-parameter", kVUIDUndefined);
if (pConditionalRenderingBegin) {
skip |= ValidateObject(commandBuffer, pConditionalRenderingBegin->buffer, kVulkanObjectTypeBuffer, false, "VUID-VkConditionalRenderingBeginInfoEXT-buffer-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndConditionalRenderingEXT(
VkCommandBuffer commandBuffer) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndConditionalRenderingEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdProcessCommandsNVX(
VkCommandBuffer commandBuffer,
const VkCmdProcessCommandsInfoNVX* pProcessCommandsInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdProcessCommandsNVX-commandBuffer-parameter", kVUIDUndefined);
if (pProcessCommandsInfo) {
skip |= ValidateObject(commandBuffer, pProcessCommandsInfo->objectTable, kVulkanObjectTypeObjectTableNVX, false, "VUID-VkCmdProcessCommandsInfoNVX-objectTable-parameter", "VUID-VkCmdProcessCommandsInfoNVX-commonparent");
skip |= ValidateObject(commandBuffer, pProcessCommandsInfo->indirectCommandsLayout, kVulkanObjectTypeIndirectCommandsLayoutNVX, false, "VUID-VkCmdProcessCommandsInfoNVX-indirectCommandsLayout-parameter", "VUID-VkCmdProcessCommandsInfoNVX-commonparent");
if (pProcessCommandsInfo->pIndirectCommandsTokens) {
for (uint32_t index1 = 0; index1 < pProcessCommandsInfo->indirectCommandsTokenCount; ++index1) {
skip |= ValidateObject(commandBuffer, pProcessCommandsInfo->pIndirectCommandsTokens[index1].buffer, kVulkanObjectTypeBuffer, false, "VUID-VkIndirectCommandsTokenNVX-buffer-parameter", kVUIDUndefined);
}
}
skip |= ValidateObject(commandBuffer, pProcessCommandsInfo->targetCommandBuffer, kVulkanObjectTypeCommandBuffer, true, "VUID-VkCmdProcessCommandsInfoNVX-targetCommandBuffer-parameter", "VUID-VkCmdProcessCommandsInfoNVX-commonparent");
skip |= ValidateObject(commandBuffer, pProcessCommandsInfo->sequencesCountBuffer, kVulkanObjectTypeBuffer, true, "VUID-VkCmdProcessCommandsInfoNVX-sequencesCountBuffer-parameter", "VUID-VkCmdProcessCommandsInfoNVX-commonparent");
skip |= ValidateObject(commandBuffer, pProcessCommandsInfo->sequencesIndexBuffer, kVulkanObjectTypeBuffer, true, "VUID-VkCmdProcessCommandsInfoNVX-sequencesIndexBuffer-parameter", "VUID-VkCmdProcessCommandsInfoNVX-commonparent");
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdReserveSpaceForCommandsNVX(
VkCommandBuffer commandBuffer,
const VkCmdReserveSpaceForCommandsInfoNVX* pReserveSpaceInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdReserveSpaceForCommandsNVX-commandBuffer-parameter", kVUIDUndefined);
if (pReserveSpaceInfo) {
skip |= ValidateObject(commandBuffer, pReserveSpaceInfo->objectTable, kVulkanObjectTypeObjectTableNVX, false, "VUID-VkCmdReserveSpaceForCommandsInfoNVX-objectTable-parameter", "VUID-VkCmdReserveSpaceForCommandsInfoNVX-commonparent");
skip |= ValidateObject(commandBuffer, pReserveSpaceInfo->indirectCommandsLayout, kVulkanObjectTypeIndirectCommandsLayoutNVX, false, "VUID-VkCmdReserveSpaceForCommandsInfoNVX-indirectCommandsLayout-parameter", "VUID-VkCmdReserveSpaceForCommandsInfoNVX-commonparent");
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateIndirectCommandsLayoutNVX(
VkDevice device,
const VkIndirectCommandsLayoutCreateInfoNVX* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkIndirectCommandsLayoutNVX* pIndirectCommandsLayout) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateIndirectCommandsLayoutNVX-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateIndirectCommandsLayoutNVX(
VkDevice device,
const VkIndirectCommandsLayoutCreateInfoNVX* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkIndirectCommandsLayoutNVX* pIndirectCommandsLayout,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pIndirectCommandsLayout, kVulkanObjectTypeIndirectCommandsLayoutNVX, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyIndirectCommandsLayoutNVX(
VkDevice device,
VkIndirectCommandsLayoutNVX indirectCommandsLayout,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyIndirectCommandsLayoutNVX-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, indirectCommandsLayout, kVulkanObjectTypeIndirectCommandsLayoutNVX, false, "VUID-vkDestroyIndirectCommandsLayoutNVX-indirectCommandsLayout-parameter", "VUID-vkDestroyIndirectCommandsLayoutNVX-indirectCommandsLayout-parent");
skip |= ValidateDestroyObject(device, indirectCommandsLayout, kVulkanObjectTypeIndirectCommandsLayoutNVX, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyIndirectCommandsLayoutNVX(
VkDevice device,
VkIndirectCommandsLayoutNVX indirectCommandsLayout,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, indirectCommandsLayout, kVulkanObjectTypeIndirectCommandsLayoutNVX);
}
bool ObjectLifetimes::PreCallValidateCreateObjectTableNVX(
VkDevice device,
const VkObjectTableCreateInfoNVX* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkObjectTableNVX* pObjectTable) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateObjectTableNVX-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateObjectTableNVX(
VkDevice device,
const VkObjectTableCreateInfoNVX* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkObjectTableNVX* pObjectTable,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pObjectTable, kVulkanObjectTypeObjectTableNVX, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyObjectTableNVX(
VkDevice device,
VkObjectTableNVX objectTable,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyObjectTableNVX-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, objectTable, kVulkanObjectTypeObjectTableNVX, false, "VUID-vkDestroyObjectTableNVX-objectTable-parameter", "VUID-vkDestroyObjectTableNVX-objectTable-parent");
skip |= ValidateDestroyObject(device, objectTable, kVulkanObjectTypeObjectTableNVX, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyObjectTableNVX(
VkDevice device,
VkObjectTableNVX objectTable,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, objectTable, kVulkanObjectTypeObjectTableNVX);
}
bool ObjectLifetimes::PreCallValidateRegisterObjectsNVX(
VkDevice device,
VkObjectTableNVX objectTable,
uint32_t objectCount,
const VkObjectTableEntryNVX* const* ppObjectTableEntries,
const uint32_t* pObjectIndices) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkRegisterObjectsNVX-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, objectTable, kVulkanObjectTypeObjectTableNVX, false, "VUID-vkRegisterObjectsNVX-objectTable-parameter", "VUID-vkRegisterObjectsNVX-objectTable-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateUnregisterObjectsNVX(
VkDevice device,
VkObjectTableNVX objectTable,
uint32_t objectCount,
const VkObjectEntryTypeNVX* pObjectEntryTypes,
const uint32_t* pObjectIndices) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkUnregisterObjectsNVX-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, objectTable, kVulkanObjectTypeObjectTableNVX, false, "VUID-vkUnregisterObjectsNVX-objectTable-parameter", "VUID-vkUnregisterObjectsNVX-objectTable-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceGeneratedCommandsPropertiesNVX(
VkPhysicalDevice physicalDevice,
VkDeviceGeneratedCommandsFeaturesNVX* pFeatures,
VkDeviceGeneratedCommandsLimitsNVX* pLimits) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetViewportWScalingNV(
VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkViewportWScalingNV* pViewportWScalings) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetViewportWScalingNV-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateReleaseDisplayEXT(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkReleaseDisplayEXT-physicalDevice-parameter", kVUIDUndefined);
skip |= ValidateObject(physicalDevice, display, kVulkanObjectTypeDisplayKHR, false, "VUID-vkReleaseDisplayEXT-display-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT
bool ObjectLifetimes::PreCallValidateAcquireXlibDisplayEXT(
VkPhysicalDevice physicalDevice,
Display* dpy,
VkDisplayKHR display) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkAcquireXlibDisplayEXT-physicalDevice-parameter", kVUIDUndefined);
skip |= ValidateObject(physicalDevice, display, kVulkanObjectTypeDisplayKHR, false, "VUID-vkAcquireXlibDisplayEXT-display-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_XLIB_XRANDR_EXT
#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT
bool ObjectLifetimes::PreCallValidateGetRandROutputDisplayEXT(
VkPhysicalDevice physicalDevice,
Display* dpy,
RROutput rrOutput,
VkDisplayKHR* pDisplay) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetRandROutputDisplayEXT-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordGetRandROutputDisplayEXT(
VkPhysicalDevice physicalDevice,
Display* dpy,
RROutput rrOutput,
VkDisplayKHR* pDisplay,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(physicalDevice, *pDisplay, kVulkanObjectTypeDisplayKHR, nullptr);
}
#endif // VK_USE_PLATFORM_XLIB_XRANDR_EXT
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfaceCapabilities2EXT(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
VkSurfaceCapabilities2EXT* pSurfaceCapabilities) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfaceCapabilities2EXT-physicalDevice-parameter", "VUID-vkGetPhysicalDeviceSurfaceCapabilities2EXT-commonparent");
skip |= ValidateObject(physicalDevice, surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-vkGetPhysicalDeviceSurfaceCapabilities2EXT-surface-parameter", "VUID-vkGetPhysicalDeviceSurfaceCapabilities2EXT-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateDisplayPowerControlEXT(
VkDevice device,
VkDisplayKHR display,
const VkDisplayPowerInfoEXT* pDisplayPowerInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDisplayPowerControlEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, display, kVulkanObjectTypeDisplayKHR, false, "VUID-vkDisplayPowerControlEXT-display-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateRegisterDeviceEventEXT(
VkDevice device,
const VkDeviceEventInfoEXT* pDeviceEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkRegisterDeviceEventEXT-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordRegisterDeviceEventEXT(
VkDevice device,
const VkDeviceEventInfoEXT* pDeviceEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pFence, kVulkanObjectTypeFence, pAllocator);
}
bool ObjectLifetimes::PreCallValidateRegisterDisplayEventEXT(
VkDevice device,
VkDisplayKHR display,
const VkDisplayEventInfoEXT* pDisplayEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkRegisterDisplayEventEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, display, kVulkanObjectTypeDisplayKHR, false, "VUID-vkRegisterDisplayEventEXT-display-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordRegisterDisplayEventEXT(
VkDevice device,
VkDisplayKHR display,
const VkDisplayEventInfoEXT* pDisplayEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pFence, kVulkanObjectTypeFence, pAllocator);
}
bool ObjectLifetimes::PreCallValidateGetSwapchainCounterEXT(
VkDevice device,
VkSwapchainKHR swapchain,
VkSurfaceCounterFlagBitsEXT counter,
uint64_t* pCounterValue) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetSwapchainCounterEXT-device-parameter", "VUID-vkGetSwapchainCounterEXT-commonparent");
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkGetSwapchainCounterEXT-swapchain-parameter", "VUID-vkGetSwapchainCounterEXT-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetRefreshCycleDurationGOOGLE(
VkDevice device,
VkSwapchainKHR swapchain,
VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetRefreshCycleDurationGOOGLE-device-parameter", "VUID-vkGetRefreshCycleDurationGOOGLE-commonparent");
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkGetRefreshCycleDurationGOOGLE-swapchain-parameter", "VUID-vkGetRefreshCycleDurationGOOGLE-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPastPresentationTimingGOOGLE(
VkDevice device,
VkSwapchainKHR swapchain,
uint32_t* pPresentationTimingCount,
VkPastPresentationTimingGOOGLE* pPresentationTimings) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetPastPresentationTimingGOOGLE-device-parameter", "VUID-vkGetPastPresentationTimingGOOGLE-commonparent");
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkGetPastPresentationTimingGOOGLE-swapchain-parameter", "VUID-vkGetPastPresentationTimingGOOGLE-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetDiscardRectangleEXT(
VkCommandBuffer commandBuffer,
uint32_t firstDiscardRectangle,
uint32_t discardRectangleCount,
const VkRect2D* pDiscardRectangles) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetDiscardRectangleEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateSetHdrMetadataEXT(
VkDevice device,
uint32_t swapchainCount,
const VkSwapchainKHR* pSwapchains,
const VkHdrMetadataEXT* pMetadata) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkSetHdrMetadataEXT-device-parameter", "VUID-vkSetHdrMetadataEXT-commonparent");
if (pSwapchains) {
for (uint32_t index0 = 0; index0 < swapchainCount; ++index0) {
skip |= ValidateObject(device, pSwapchains[index0], kVulkanObjectTypeSwapchainKHR, false, "VUID-vkSetHdrMetadataEXT-pSwapchains-parameter", "VUID-vkSetHdrMetadataEXT-commonparent");
}
}
return skip;
}
#ifdef VK_USE_PLATFORM_IOS_MVK
bool ObjectLifetimes::PreCallValidateCreateIOSSurfaceMVK(
VkInstance instance,
const VkIOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateIOSSurfaceMVK-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateIOSSurfaceMVK(
VkInstance instance,
const VkIOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_IOS_MVK
#ifdef VK_USE_PLATFORM_MACOS_MVK
bool ObjectLifetimes::PreCallValidateCreateMacOSSurfaceMVK(
VkInstance instance,
const VkMacOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateMacOSSurfaceMVK-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateMacOSSurfaceMVK(
VkInstance instance,
const VkMacOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_MACOS_MVK
bool ObjectLifetimes::PreCallValidateSetDebugUtilsObjectNameEXT(
VkDevice device,
const VkDebugUtilsObjectNameInfoEXT* pNameInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkSetDebugUtilsObjectNameEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateSetDebugUtilsObjectTagEXT(
VkDevice device,
const VkDebugUtilsObjectTagInfoEXT* pTagInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkSetDebugUtilsObjectTagEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateQueueBeginDebugUtilsLabelEXT(
VkQueue queue,
const VkDebugUtilsLabelEXT* pLabelInfo) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueueBeginDebugUtilsLabelEXT-queue-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateQueueEndDebugUtilsLabelEXT(
VkQueue queue) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueueEndDebugUtilsLabelEXT-queue-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateQueueInsertDebugUtilsLabelEXT(
VkQueue queue,
const VkDebugUtilsLabelEXT* pLabelInfo) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkQueueInsertDebugUtilsLabelEXT-queue-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBeginDebugUtilsLabelEXT(
VkCommandBuffer commandBuffer,
const VkDebugUtilsLabelEXT* pLabelInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBeginDebugUtilsLabelEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdEndDebugUtilsLabelEXT(
VkCommandBuffer commandBuffer) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdEndDebugUtilsLabelEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdInsertDebugUtilsLabelEXT(
VkCommandBuffer commandBuffer,
const VkDebugUtilsLabelEXT* pLabelInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdInsertDebugUtilsLabelEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT* pMessenger) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateDebugUtilsMessengerEXT-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT* pMessenger,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pMessenger, kVulkanObjectTypeDebugUtilsMessengerEXT, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyDebugUtilsMessengerEXT(
VkInstance instance,
VkDebugUtilsMessengerEXT messenger,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkDestroyDebugUtilsMessengerEXT-instance-parameter", kVUIDUndefined);
skip |= ValidateObject(instance, messenger, kVulkanObjectTypeDebugUtilsMessengerEXT, false, "VUID-vkDestroyDebugUtilsMessengerEXT-messenger-parameter", "VUID-vkDestroyDebugUtilsMessengerEXT-messenger-parent");
skip |= ValidateDestroyObject(instance, messenger, kVulkanObjectTypeDebugUtilsMessengerEXT, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyDebugUtilsMessengerEXT(
VkInstance instance,
VkDebugUtilsMessengerEXT messenger,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(instance, messenger, kVulkanObjectTypeDebugUtilsMessengerEXT);
}
bool ObjectLifetimes::PreCallValidateSubmitDebugUtilsMessageEXT(
VkInstance instance,
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkSubmitDebugUtilsMessageEXT-instance-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_ANDROID_KHR
bool ObjectLifetimes::PreCallValidateGetAndroidHardwareBufferPropertiesANDROID(
VkDevice device,
const struct AHardwareBuffer* buffer,
VkAndroidHardwareBufferPropertiesANDROID* pProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetAndroidHardwareBufferPropertiesANDROID-device-parameter", kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_ANDROID_KHR
#ifdef VK_USE_PLATFORM_ANDROID_KHR
bool ObjectLifetimes::PreCallValidateGetMemoryAndroidHardwareBufferANDROID(
VkDevice device,
const VkMemoryGetAndroidHardwareBufferInfoANDROID* pInfo,
struct AHardwareBuffer** pBuffer) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryAndroidHardwareBufferANDROID-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-memory-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_ANDROID_KHR
bool ObjectLifetimes::PreCallValidateCmdSetSampleLocationsEXT(
VkCommandBuffer commandBuffer,
const VkSampleLocationsInfoEXT* pSampleLocationsInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetSampleLocationsEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceMultisamplePropertiesEXT(
VkPhysicalDevice physicalDevice,
VkSampleCountFlagBits samples,
VkMultisamplePropertiesEXT* pMultisampleProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceMultisamplePropertiesEXT-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetImageDrmFormatModifierPropertiesEXT(
VkDevice device,
VkImage image,
VkImageDrmFormatModifierPropertiesEXT* pProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetImageDrmFormatModifierPropertiesEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, image, kVulkanObjectTypeImage, false, "VUID-vkGetImageDrmFormatModifierPropertiesEXT-image-parameter", "VUID-vkGetImageDrmFormatModifierPropertiesEXT-image-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateValidationCacheEXT(
VkDevice device,
const VkValidationCacheCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkValidationCacheEXT* pValidationCache) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateValidationCacheEXT-device-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateValidationCacheEXT(
VkDevice device,
const VkValidationCacheCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkValidationCacheEXT* pValidationCache,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pValidationCache, kVulkanObjectTypeValidationCacheEXT, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyValidationCacheEXT(
VkDevice device,
VkValidationCacheEXT validationCache,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyValidationCacheEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, validationCache, kVulkanObjectTypeValidationCacheEXT, true, "VUID-vkDestroyValidationCacheEXT-validationCache-parameter", "VUID-vkDestroyValidationCacheEXT-validationCache-parent");
skip |= ValidateDestroyObject(device, validationCache, kVulkanObjectTypeValidationCacheEXT, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyValidationCacheEXT(
VkDevice device,
VkValidationCacheEXT validationCache,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, validationCache, kVulkanObjectTypeValidationCacheEXT);
}
bool ObjectLifetimes::PreCallValidateMergeValidationCachesEXT(
VkDevice device,
VkValidationCacheEXT dstCache,
uint32_t srcCacheCount,
const VkValidationCacheEXT* pSrcCaches) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkMergeValidationCachesEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, dstCache, kVulkanObjectTypeValidationCacheEXT, false, "VUID-vkMergeValidationCachesEXT-dstCache-parameter", "VUID-vkMergeValidationCachesEXT-dstCache-parent");
if (pSrcCaches) {
for (uint32_t index0 = 0; index0 < srcCacheCount; ++index0) {
skip |= ValidateObject(device, pSrcCaches[index0], kVulkanObjectTypeValidationCacheEXT, false, "VUID-vkMergeValidationCachesEXT-pSrcCaches-parameter", "VUID-vkMergeValidationCachesEXT-pSrcCaches-parent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateGetValidationCacheDataEXT(
VkDevice device,
VkValidationCacheEXT validationCache,
size_t* pDataSize,
void* pData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetValidationCacheDataEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, validationCache, kVulkanObjectTypeValidationCacheEXT, false, "VUID-vkGetValidationCacheDataEXT-validationCache-parameter", "VUID-vkGetValidationCacheDataEXT-validationCache-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBindShadingRateImageNV(
VkCommandBuffer commandBuffer,
VkImageView imageView,
VkImageLayout imageLayout) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBindShadingRateImageNV-commandBuffer-parameter", "VUID-vkCmdBindShadingRateImageNV-commonparent");
skip |= ValidateObject(commandBuffer, imageView, kVulkanObjectTypeImageView, true, "VUID-vkCmdBindShadingRateImageNV-imageView-parameter", "VUID-vkCmdBindShadingRateImageNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetViewportShadingRatePaletteNV(
VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkShadingRatePaletteNV* pShadingRatePalettes) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetCoarseSampleOrderNV(
VkCommandBuffer commandBuffer,
VkCoarseSampleOrderTypeNV sampleOrderType,
uint32_t customSampleOrderCount,
const VkCoarseSampleOrderCustomNV* pCustomSampleOrders) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetCoarseSampleOrderNV-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateAccelerationStructureNV(
VkDevice device,
const VkAccelerationStructureCreateInfoNV* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkAccelerationStructureNV* pAccelerationStructure) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateAccelerationStructureNV-device-parameter", kVUIDUndefined);
if (pCreateInfo) {
if (pCreateInfo->info.pGeometries) {
for (uint32_t index2 = 0; index2 < pCreateInfo->info.geometryCount; ++index2) {
skip |= ValidateObject(device, pCreateInfo->info.pGeometries[index2].geometry.triangles.vertexData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryTrianglesNV-vertexData-parameter", "VUID-VkGeometryTrianglesNV-commonparent");
skip |= ValidateObject(device, pCreateInfo->info.pGeometries[index2].geometry.triangles.indexData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryTrianglesNV-indexData-parameter", "VUID-VkGeometryTrianglesNV-commonparent");
skip |= ValidateObject(device, pCreateInfo->info.pGeometries[index2].geometry.triangles.transformData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryTrianglesNV-transformData-parameter", "VUID-VkGeometryTrianglesNV-commonparent");
skip |= ValidateObject(device, pCreateInfo->info.pGeometries[index2].geometry.aabbs.aabbData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryAABBNV-aabbData-parameter", kVUIDUndefined);
}
}
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateAccelerationStructureNV(
VkDevice device,
const VkAccelerationStructureCreateInfoNV* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkAccelerationStructureNV* pAccelerationStructure,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(device, *pAccelerationStructure, kVulkanObjectTypeAccelerationStructureNV, pAllocator);
}
bool ObjectLifetimes::PreCallValidateDestroyAccelerationStructureNV(
VkDevice device,
VkAccelerationStructureNV accelerationStructure,
const VkAllocationCallbacks* pAllocator) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkDestroyAccelerationStructureNV-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, accelerationStructure, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-vkDestroyAccelerationStructureNV-accelerationStructure-parameter", "VUID-vkDestroyAccelerationStructureNV-accelerationStructure-parent");
skip |= ValidateDestroyObject(device, accelerationStructure, kVulkanObjectTypeAccelerationStructureNV, pAllocator, kVUIDUndefined, kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PreCallRecordDestroyAccelerationStructureNV(
VkDevice device,
VkAccelerationStructureNV accelerationStructure,
const VkAllocationCallbacks* pAllocator) {
RecordDestroyObject(device, accelerationStructure, kVulkanObjectTypeAccelerationStructureNV);
}
bool ObjectLifetimes::PreCallValidateGetAccelerationStructureMemoryRequirementsNV(
VkDevice device,
const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo,
VkMemoryRequirements2KHR* pMemoryRequirements) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetAccelerationStructureMemoryRequirementsNV-device-parameter", kVUIDUndefined);
if (pInfo) {
skip |= ValidateObject(device, pInfo->accelerationStructure, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-VkAccelerationStructureMemoryRequirementsInfoNV-accelerationStructure-parameter", kVUIDUndefined);
}
return skip;
}
bool ObjectLifetimes::PreCallValidateBindAccelerationStructureMemoryNV(
VkDevice device,
uint32_t bindInfoCount,
const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkBindAccelerationStructureMemoryNV-device-parameter", kVUIDUndefined);
if (pBindInfos) {
for (uint32_t index0 = 0; index0 < bindInfoCount; ++index0) {
skip |= ValidateObject(device, pBindInfos[index0].accelerationStructure, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-VkBindAccelerationStructureMemoryInfoNV-accelerationStructure-parameter", "VUID-VkBindAccelerationStructureMemoryInfoNV-commonparent");
skip |= ValidateObject(device, pBindInfos[index0].memory, kVulkanObjectTypeDeviceMemory, false, "VUID-VkBindAccelerationStructureMemoryInfoNV-memory-parameter", "VUID-VkBindAccelerationStructureMemoryInfoNV-commonparent");
}
}
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdBuildAccelerationStructureNV(
VkCommandBuffer commandBuffer,
const VkAccelerationStructureInfoNV* pInfo,
VkBuffer instanceData,
VkDeviceSize instanceOffset,
VkBool32 update,
VkAccelerationStructureNV dst,
VkAccelerationStructureNV src,
VkBuffer scratch,
VkDeviceSize scratchOffset) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdBuildAccelerationStructureNV-commandBuffer-parameter", "VUID-vkCmdBuildAccelerationStructureNV-commonparent");
if (pInfo) {
if (pInfo->pGeometries) {
for (uint32_t index1 = 0; index1 < pInfo->geometryCount; ++index1) {
skip |= ValidateObject(commandBuffer, pInfo->pGeometries[index1].geometry.triangles.vertexData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryTrianglesNV-vertexData-parameter", "VUID-VkGeometryTrianglesNV-commonparent");
skip |= ValidateObject(commandBuffer, pInfo->pGeometries[index1].geometry.triangles.indexData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryTrianglesNV-indexData-parameter", "VUID-VkGeometryTrianglesNV-commonparent");
skip |= ValidateObject(commandBuffer, pInfo->pGeometries[index1].geometry.triangles.transformData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryTrianglesNV-transformData-parameter", "VUID-VkGeometryTrianglesNV-commonparent");
skip |= ValidateObject(commandBuffer, pInfo->pGeometries[index1].geometry.aabbs.aabbData, kVulkanObjectTypeBuffer, true, "VUID-VkGeometryAABBNV-aabbData-parameter", kVUIDUndefined);
}
}
}
skip |= ValidateObject(commandBuffer, instanceData, kVulkanObjectTypeBuffer, true, "VUID-vkCmdBuildAccelerationStructureNV-instanceData-parameter", "VUID-vkCmdBuildAccelerationStructureNV-commonparent");
skip |= ValidateObject(commandBuffer, dst, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-vkCmdBuildAccelerationStructureNV-dst-parameter", "VUID-vkCmdBuildAccelerationStructureNV-commonparent");
skip |= ValidateObject(commandBuffer, src, kVulkanObjectTypeAccelerationStructureNV, true, "VUID-vkCmdBuildAccelerationStructureNV-src-parameter", "VUID-vkCmdBuildAccelerationStructureNV-commonparent");
skip |= ValidateObject(commandBuffer, scratch, kVulkanObjectTypeBuffer, false, "VUID-vkCmdBuildAccelerationStructureNV-scratch-parameter", "VUID-vkCmdBuildAccelerationStructureNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdCopyAccelerationStructureNV(
VkCommandBuffer commandBuffer,
VkAccelerationStructureNV dst,
VkAccelerationStructureNV src,
VkCopyAccelerationStructureModeNV mode) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdCopyAccelerationStructureNV-commandBuffer-parameter", "VUID-vkCmdCopyAccelerationStructureNV-commonparent");
skip |= ValidateObject(commandBuffer, dst, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-vkCmdCopyAccelerationStructureNV-dst-parameter", "VUID-vkCmdCopyAccelerationStructureNV-commonparent");
skip |= ValidateObject(commandBuffer, src, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-vkCmdCopyAccelerationStructureNV-src-parameter", "VUID-vkCmdCopyAccelerationStructureNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdTraceRaysNV(
VkCommandBuffer commandBuffer,
VkBuffer raygenShaderBindingTableBuffer,
VkDeviceSize raygenShaderBindingOffset,
VkBuffer missShaderBindingTableBuffer,
VkDeviceSize missShaderBindingOffset,
VkDeviceSize missShaderBindingStride,
VkBuffer hitShaderBindingTableBuffer,
VkDeviceSize hitShaderBindingOffset,
VkDeviceSize hitShaderBindingStride,
VkBuffer callableShaderBindingTableBuffer,
VkDeviceSize callableShaderBindingOffset,
VkDeviceSize callableShaderBindingStride,
uint32_t width,
uint32_t height,
uint32_t depth) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdTraceRaysNV-commandBuffer-parameter", "VUID-vkCmdTraceRaysNV-commonparent");
skip |= ValidateObject(commandBuffer, raygenShaderBindingTableBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdTraceRaysNV-raygenShaderBindingTableBuffer-parameter", "VUID-vkCmdTraceRaysNV-commonparent");
skip |= ValidateObject(commandBuffer, missShaderBindingTableBuffer, kVulkanObjectTypeBuffer, true, "VUID-vkCmdTraceRaysNV-missShaderBindingTableBuffer-parameter", "VUID-vkCmdTraceRaysNV-commonparent");
skip |= ValidateObject(commandBuffer, hitShaderBindingTableBuffer, kVulkanObjectTypeBuffer, true, "VUID-vkCmdTraceRaysNV-hitShaderBindingTableBuffer-parameter", "VUID-vkCmdTraceRaysNV-commonparent");
skip |= ValidateObject(commandBuffer, callableShaderBindingTableBuffer, kVulkanObjectTypeBuffer, true, "VUID-vkCmdTraceRaysNV-callableShaderBindingTableBuffer-parameter", "VUID-vkCmdTraceRaysNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCreateRayTracingPipelinesNV(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoNV* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCreateRayTracingPipelinesNV-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipelineCache, kVulkanObjectTypePipelineCache, true, "VUID-vkCreateRayTracingPipelinesNV-pipelineCache-parameter", "VUID-vkCreateRayTracingPipelinesNV-pipelineCache-parent");
if (pCreateInfos) {
for (uint32_t index0 = 0; index0 < createInfoCount; ++index0) {
if (pCreateInfos[index0].pStages) {
for (uint32_t index1 = 0; index1 < pCreateInfos[index0].stageCount; ++index1) {
skip |= ValidateObject(device, pCreateInfos[index0].pStages[index1].module, kVulkanObjectTypeShaderModule, false, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", kVUIDUndefined);
}
}
skip |= ValidateObject(device, pCreateInfos[index0].layout, kVulkanObjectTypePipelineLayout, false, "VUID-VkRayTracingPipelineCreateInfoNV-layout-parameter", "VUID-VkRayTracingPipelineCreateInfoNV-commonparent");
skip |= ValidateObject(device, pCreateInfos[index0].basePipelineHandle, kVulkanObjectTypePipeline, true, kVUIDUndefined, "VUID-VkRayTracingPipelineCreateInfoNV-commonparent");
}
}
return skip;
}
void ObjectLifetimes::PostCallRecordCreateRayTracingPipelinesNV(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoNV* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result) {
if (VK_ERROR_VALIDATION_FAILED_EXT == result) return;
if (pPipelines) {
for (uint32_t index = 0; index < createInfoCount; index++) {
if (!pPipelines[index]) continue;
CreateObject(device, pPipelines[index], kVulkanObjectTypePipeline, pAllocator);
}
}
}
bool ObjectLifetimes::PreCallValidateGetRayTracingShaderGroupHandlesNV(
VkDevice device,
VkPipeline pipeline,
uint32_t firstGroup,
uint32_t groupCount,
size_t dataSize,
void* pData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetRayTracingShaderGroupHandlesNV-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipeline, kVulkanObjectTypePipeline, false, "VUID-vkGetRayTracingShaderGroupHandlesNV-pipeline-parameter", "VUID-vkGetRayTracingShaderGroupHandlesNV-pipeline-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetAccelerationStructureHandleNV(
VkDevice device,
VkAccelerationStructureNV accelerationStructure,
size_t dataSize,
void* pData) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetAccelerationStructureHandleNV-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, accelerationStructure, kVulkanObjectTypeAccelerationStructureNV, false, "VUID-vkGetAccelerationStructureHandleNV-accelerationStructure-parameter", "VUID-vkGetAccelerationStructureHandleNV-accelerationStructure-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdWriteAccelerationStructuresPropertiesNV(
VkCommandBuffer commandBuffer,
uint32_t accelerationStructureCount,
const VkAccelerationStructureNV* pAccelerationStructures,
VkQueryType queryType,
VkQueryPool queryPool,
uint32_t firstQuery) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-commandBuffer-parameter", "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-commonparent");
if (pAccelerationStructures) {
for (uint32_t index0 = 0; index0 < accelerationStructureCount; ++index0) {
skip |= ValidateObject(commandBuffer, pAccelerationStructures[index0], kVulkanObjectTypeAccelerationStructureNV, false, "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-pAccelerationStructures-parameter", "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-commonparent");
}
}
skip |= ValidateObject(commandBuffer, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-queryPool-parameter", "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCompileDeferredNV(
VkDevice device,
VkPipeline pipeline,
uint32_t shader) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkCompileDeferredNV-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, pipeline, kVulkanObjectTypePipeline, false, "VUID-vkCompileDeferredNV-pipeline-parameter", "VUID-vkCompileDeferredNV-pipeline-parent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetMemoryHostPointerPropertiesEXT(
VkDevice device,
VkExternalMemoryHandleTypeFlagBits handleType,
const void* pHostPointer,
VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetMemoryHostPointerPropertiesEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdWriteBufferMarkerAMD(
VkCommandBuffer commandBuffer,
VkPipelineStageFlagBits pipelineStage,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
uint32_t marker) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdWriteBufferMarkerAMD-commandBuffer-parameter", "VUID-vkCmdWriteBufferMarkerAMD-commonparent");
skip |= ValidateObject(commandBuffer, dstBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdWriteBufferMarkerAMD-dstBuffer-parameter", "VUID-vkCmdWriteBufferMarkerAMD-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceCalibrateableTimeDomainsEXT(
VkPhysicalDevice physicalDevice,
uint32_t* pTimeDomainCount,
VkTimeDomainEXT* pTimeDomains) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceCalibrateableTimeDomainsEXT-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetCalibratedTimestampsEXT(
VkDevice device,
uint32_t timestampCount,
const VkCalibratedTimestampInfoEXT* pTimestampInfos,
uint64_t* pTimestamps,
uint64_t* pMaxDeviation) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetCalibratedTimestampsEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawMeshTasksNV(
VkCommandBuffer commandBuffer,
uint32_t taskCount,
uint32_t firstTask) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawMeshTasksNV-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawMeshTasksIndirectNV(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawMeshTasksIndirectNV-commandBuffer-parameter", "VUID-vkCmdDrawMeshTasksIndirectNV-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawMeshTasksIndirectNV-buffer-parameter", "VUID-vkCmdDrawMeshTasksIndirectNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdDrawMeshTasksIndirectCountNV(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdDrawMeshTasksIndirectCountNV-commandBuffer-parameter", "VUID-vkCmdDrawMeshTasksIndirectCountNV-commonparent");
skip |= ValidateObject(commandBuffer, buffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawMeshTasksIndirectCountNV-buffer-parameter", "VUID-vkCmdDrawMeshTasksIndirectCountNV-commonparent");
skip |= ValidateObject(commandBuffer, countBuffer, kVulkanObjectTypeBuffer, false, "VUID-vkCmdDrawMeshTasksIndirectCountNV-countBuffer-parameter", "VUID-vkCmdDrawMeshTasksIndirectCountNV-commonparent");
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetExclusiveScissorNV(
VkCommandBuffer commandBuffer,
uint32_t firstExclusiveScissor,
uint32_t exclusiveScissorCount,
const VkRect2D* pExclusiveScissors) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetExclusiveScissorNV-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetCheckpointNV(
VkCommandBuffer commandBuffer,
const void* pCheckpointMarker) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetCheckpointNV-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetQueueCheckpointDataNV(
VkQueue queue,
uint32_t* pCheckpointDataCount,
VkCheckpointDataNV* pCheckpointData) {
bool skip = false;
skip |= ValidateObject(queue, queue, kVulkanObjectTypeQueue, false, "VUID-vkGetQueueCheckpointDataNV-queue-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateInitializePerformanceApiINTEL(
VkDevice device,
const VkInitializePerformanceApiInfoINTEL* pInitializeInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkInitializePerformanceApiINTEL-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateUninitializePerformanceApiINTEL(
VkDevice device) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkUninitializePerformanceApiINTEL-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetPerformanceMarkerINTEL(
VkCommandBuffer commandBuffer,
const VkPerformanceMarkerInfoINTEL* pMarkerInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetPerformanceMarkerINTEL-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetPerformanceStreamMarkerINTEL(
VkCommandBuffer commandBuffer,
const VkPerformanceStreamMarkerInfoINTEL* pMarkerInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateCmdSetPerformanceOverrideINTEL(
VkCommandBuffer commandBuffer,
const VkPerformanceOverrideInfoINTEL* pOverrideInfo) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPerformanceParameterINTEL(
VkDevice device,
VkPerformanceParameterTypeINTEL parameter,
VkPerformanceValueINTEL* pValue) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetPerformanceParameterINTEL-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateSetLocalDimmingAMD(
VkDevice device,
VkSwapchainKHR swapChain,
VkBool32 localDimmingEnable) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkSetLocalDimmingAMD-device-parameter", "VUID-vkSetLocalDimmingAMD-commonparent");
skip |= ValidateObject(device, swapChain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkSetLocalDimmingAMD-swapChain-parameter", "VUID-vkSetLocalDimmingAMD-commonparent");
return skip;
}
#ifdef VK_USE_PLATFORM_FUCHSIA
bool ObjectLifetimes::PreCallValidateCreateImagePipeSurfaceFUCHSIA(
VkInstance instance,
const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateImagePipeSurfaceFUCHSIA-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateImagePipeSurfaceFUCHSIA(
VkInstance instance,
const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_FUCHSIA
#ifdef VK_USE_PLATFORM_METAL_EXT
bool ObjectLifetimes::PreCallValidateCreateMetalSurfaceEXT(
VkInstance instance,
const VkMetalSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateMetalSurfaceEXT-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateMetalSurfaceEXT(
VkInstance instance,
const VkMetalSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
#endif // VK_USE_PLATFORM_METAL_EXT
bool ObjectLifetimes::PreCallValidateGetBufferDeviceAddressEXT(
VkDevice device,
const VkBufferDeviceAddressInfoEXT* pInfo) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetBufferDeviceAddressEXT-device-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceCooperativeMatrixPropertiesNV(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkCooperativeMatrixPropertiesNV* pProperties) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceCooperativeMatrixPropertiesNV-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV(
VkPhysicalDevice physicalDevice,
uint32_t* pCombinationCount,
VkFramebufferMixedSamplesCombinationNV* pCombinations) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV-physicalDevice-parameter", kVUIDUndefined);
return skip;
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetPhysicalDeviceSurfacePresentModes2EXT(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
uint32_t* pPresentModeCount,
VkPresentModeKHR* pPresentModes) {
bool skip = false;
skip |= ValidateObject(physicalDevice, physicalDevice, kVulkanObjectTypePhysicalDevice, false, "VUID-vkGetPhysicalDeviceSurfacePresentModes2EXT-physicalDevice-parameter", kVUIDUndefined);
if (pSurfaceInfo) {
skip |= ValidateObject(physicalDevice, pSurfaceInfo->surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-VkPhysicalDeviceSurfaceInfo2KHR-surface-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateAcquireFullScreenExclusiveModeEXT(
VkDevice device,
VkSwapchainKHR swapchain) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkAcquireFullScreenExclusiveModeEXT-device-parameter", "VUID-vkAcquireFullScreenExclusiveModeEXT-commonparent");
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, "VUID-vkAcquireFullScreenExclusiveModeEXT-swapchain-parameter", "VUID-vkAcquireFullScreenExclusiveModeEXT-commonparent");
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateReleaseFullScreenExclusiveModeEXT(
VkDevice device,
VkSwapchainKHR swapchain) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, kVUIDUndefined, kVUIDUndefined);
skip |= ValidateObject(device, swapchain, kVulkanObjectTypeSwapchainKHR, false, kVUIDUndefined, kVUIDUndefined);
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateGetDeviceGroupSurfacePresentModes2EXT(
VkDevice device,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
VkDeviceGroupPresentModeFlagsKHR* pModes) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkGetDeviceGroupSurfacePresentModes2EXT-device-parameter", kVUIDUndefined);
if (pSurfaceInfo) {
skip |= ValidateObject(device, pSurfaceInfo->surface, kVulkanObjectTypeSurfaceKHR, false, "VUID-VkPhysicalDeviceSurfaceInfo2KHR-surface-parameter", kVUIDUndefined);
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool ObjectLifetimes::PreCallValidateCreateHeadlessSurfaceEXT(
VkInstance instance,
const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) {
bool skip = false;
skip |= ValidateObject(instance, instance, kVulkanObjectTypeInstance, false, "VUID-vkCreateHeadlessSurfaceEXT-instance-parameter", kVUIDUndefined);
return skip;
}
void ObjectLifetimes::PostCallRecordCreateHeadlessSurfaceEXT(
VkInstance instance,
const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result) {
if (result != VK_SUCCESS) return;
CreateObject(instance, *pSurface, kVulkanObjectTypeSurfaceKHR, pAllocator);
}
bool ObjectLifetimes::PreCallValidateCmdSetLineStippleEXT(
VkCommandBuffer commandBuffer,
uint32_t lineStippleFactor,
uint16_t lineStipplePattern) {
bool skip = false;
skip |= ValidateObject(commandBuffer, commandBuffer, kVulkanObjectTypeCommandBuffer, false, "VUID-vkCmdSetLineStippleEXT-commandBuffer-parameter", kVUIDUndefined);
return skip;
}
bool ObjectLifetimes::PreCallValidateResetQueryPoolEXT(
VkDevice device,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount) {
bool skip = false;
skip |= ValidateObject(device, device, kVulkanObjectTypeDevice, false, "VUID-vkResetQueryPoolEXT-device-parameter", kVUIDUndefined);
skip |= ValidateObject(device, queryPool, kVulkanObjectTypeQueryPool, false, "VUID-vkResetQueryPoolEXT-queryPool-parameter", "VUID-vkResetQueryPoolEXT-queryPool-parent");
return skip;
}
| 1 | 11,765 | Do we need HeadlessSurface and DisplayPlaneSurface here too? | KhronosGroup-Vulkan-ValidationLayers | cpp |
@@ -473,7 +473,7 @@ describe('GridFS Stream', function () {
// Fail if user tries to abort an aborted stream
uploadStream.abort().then(null, function (error) {
expect(error.toString()).to.equal(
- 'MongoDriverError: Cannot call abort() on a stream twice'
+ 'MongoGridFSStreamError: Cannot call abort() on a stream twice'
);
client.close(done);
}); | 1 | 'use strict';
const { Double } = require('bson');
const stream = require('stream');
const { EJSON } = require('bson');
const fs = require('fs');
const { setupDatabase, withClient } = require('./shared');
const { expect } = require('chai');
const { GridFSBucket, ObjectId } = require('../../src');
describe('GridFS Stream', function () {
before(function () {
return setupDatabase(this.configuration);
});
/**
* Correctly stream a file from disk into GridFS using openUploadStream
*
* @example-class GridFSBucket
* @example-method openUploadStream
*/
it('should upload from file stream', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
db.dropDatabase(function (error) {
expect(error).to.not.exist;
const bucket = new GridFSBucket(db);
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const license = fs.readFileSync('./LICENSE.md');
const id = uploadStream.id;
// Wait for stream to finish
uploadStream.once('finish', function () {
const chunksColl = db.collection('fs.chunks');
const chunksQuery = chunksColl.find({ files_id: id });
// Get all the chunks
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(1);
expect(docs[0].data.toString('hex')).to.equal(license.toString('hex'));
const filesColl = db.collection('fs.files');
const filesQuery = filesColl.find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(1);
expect(docs[0]).to.not.have.property('md5');
// make sure we created indexes
filesColl.listIndexes().toArray(function (error, indexes) {
expect(error).to.not.exist;
expect(indexes.length).to.equal(2);
expect(indexes[1].name).to.equal('filename_1_uploadDate_1');
chunksColl.listIndexes().toArray(function (error, indexes) {
expect(error).to.not.exist;
expect(indexes.length).to.equal(2);
expect(indexes[1].name).to.equal('files_id_1_n_1');
client.close(done);
});
});
});
});
});
readStream.pipe(uploadStream);
});
});
}
});
it('destroy publishes provided error', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
db.dropDatabase(function (error) {
expect(error).to.not.exist;
const bucket = new GridFSBucket(db);
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const errorMessage = 'error';
uploadStream.once('error', function (e) {
expect(e).to.equal(errorMessage);
client.close(done);
});
uploadStream.once('finish', function () {
uploadStream.destroy(errorMessage);
});
readStream.pipe(uploadStream);
});
});
}
});
/**
* Correctly stream a file from disk into GridFS using openUploadStream
*
* @example-class GridFSBucket
* @example-method openUploadStreamWithId
*/
it('should upload from file stream with custom id', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
db.dropDatabase(function (error) {
expect(error).to.not.exist;
const bucket = new GridFSBucket(db);
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStreamWithId(1, 'test.dat');
const license = fs.readFileSync('./LICENSE.md');
const id = uploadStream.id;
expect(id).to.equal(1);
// Wait for stream to finish
uploadStream.once('finish', function () {
const chunksColl = db.collection('fs.chunks');
const chunksQuery = chunksColl.find({ files_id: id });
// Get all the chunks
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(1);
expect(docs[0].data.toString('hex')).to.equal(license.toString('hex'));
const filesColl = db.collection('fs.files');
const filesQuery = filesColl.find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(1);
expect(docs[0]).to.not.have.property('md5');
// make sure we created indexes
filesColl.listIndexes().toArray(function (error, indexes) {
expect(error).to.not.exist;
expect(indexes.length).to.equal(2);
expect(indexes[1].name).to.equal('filename_1_uploadDate_1');
chunksColl.listIndexes().toArray(function (error, indexes) {
expect(error).to.not.exist;
expect(indexes.length).to.equal(2);
expect(indexes[1].name).to.equal('files_id_1_n_1');
client.close(done);
});
});
});
});
});
readStream.pipe(uploadStream);
});
});
}
});
/**
* Correctly upload a file to GridFS and then retrieve it as a stream
*
* @example-class GridFSBucket
* @example-method openDownloadStream
*/
it('should download to upload stream', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const CHUNKS_COLL = 'gridfsdownload.chunks';
const FILES_COLL = 'gridfsdownload.files';
const readStream = fs.createReadStream('./LICENSE.md');
let uploadStream = bucket.openUploadStream('test.dat');
const license = fs.readFileSync('./LICENSE.md');
let id = uploadStream.id;
uploadStream.once('finish', function () {
const downloadStream = bucket.openDownloadStream(id);
uploadStream = bucket.openUploadStream('test2.dat');
id = uploadStream.id;
downloadStream.pipe(uploadStream).once('finish', function () {
const chunksQuery = db.collection(CHUNKS_COLL).find({ files_id: id });
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(1);
expect(docs[0].data.toString('hex')).to.equal(license.toString('hex'));
const filesQuery = db.collection(FILES_COLL).find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(1);
expect(docs[0]).to.not.have.property('md5');
client.close(done);
});
});
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Correctly return file not found error
*/
it('should fail to locate gridfs stream', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
// Get an unknown file
const downloadStream = bucket.openDownloadStream(new ObjectId());
downloadStream.on('data', function () {});
downloadStream.on('error', function (err) {
expect(err.code).to.equal('ENOENT');
client.close(done);
});
});
}
});
/**
* Correctly download a GridFS file by name
*
* @example-class GridFSBucket
* @example-method openDownloadStreamByName
*/
it('openDownloadStreamByName', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
uploadStream.once('finish', function () {
const downloadStream = bucket.openDownloadStreamByName('test.dat');
let gotData = false;
downloadStream.on('data', function (data) {
expect(gotData).to.equal(false);
gotData = true;
expect(data.toString('utf8').indexOf('TERMS AND CONDITIONS') !== -1).to.equal(true);
});
downloadStream.on('end', function () {
expect(gotData).to.equal(true);
client.close(done);
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Provide start and end parameters for file download to skip ahead x bytes and limit the total amount of bytes read to n
*
* @example-class GridFSBucket
* @example-method openDownloadStream
*/
it('start/end options for openDownloadStream', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, {
bucketName: 'gridfsdownload',
chunkSizeBytes: 2
});
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('teststart.dat');
uploadStream.once('finish', function () {
const downloadStream = bucket
.openDownloadStreamByName('teststart.dat', { start: 1 })
.end(6);
downloadStream.on('error', function (error) {
expect(error).to.not.exist;
});
let gotData = 0;
let str = '';
downloadStream.on('data', function (data) {
++gotData;
str += data.toString('utf8');
});
downloadStream.on('end', function () {
// Depending on different versions of node, we may get
// different amounts of 'data' events. node 0.10 gives 2,
// node >= 0.12 gives 3. Either is correct, but we just
// care that we got between 1 and 3, and got the right result
expect(gotData >= 1 && gotData <= 3).to.equal(true);
expect(str).to.equal('pache');
client.close(done);
});
});
readStream.pipe(uploadStream);
});
}
});
it('should emit close after all chunks are received', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect((err, client) => {
expect(err).to.not.exist;
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, {
bucketName: 'gridfsdownload',
chunkSizeBytes: 6000
});
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('teststart.dat');
uploadStream.once('finish', function () {
const downloadStream = bucket.openDownloadStreamByName('teststart.dat');
const events = [];
downloadStream.on('data', () => events.push('data'));
downloadStream.on('close', () => events.push('close'));
downloadStream.on('end', () => {
expect(events).to.eql(['data', 'data', 'close']);
client.close(done);
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Deleting a file from GridFS
*
* @example-class GridFSBucket
* @example-method delete
*/
it('Deleting a file', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const CHUNKS_COLL = 'gridfsdownload.chunks';
const FILES_COLL = 'gridfsdownload.files';
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
uploadStream.once('finish', function () {
bucket.delete(id, function (err) {
expect(err).to.not.exist;
const chunksQuery = db.collection(CHUNKS_COLL).find({ files_id: id });
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
const filesQuery = db.collection(FILES_COLL).find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
client.close(done);
});
});
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Aborting an upload
*
* @example-class GridFSBucketWriteStream
* @example-method abort
*/
it('Aborting an upload', {
metadata: { requires: { topology: ['single'], node: '>12.0.0' } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsabort', chunkSizeBytes: 1 });
const CHUNKS_COLL = 'gridfsabort.chunks';
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
const query = { files_id: id };
uploadStream.write('a', 'utf8', function (error) {
expect(error).to.not.exist;
db.collection(CHUNKS_COLL).count(query, function (error, c) {
expect(error).to.not.exist;
expect(c).to.equal(1);
uploadStream.abort(function (error) {
expect(error).to.not.exist;
db.collection(CHUNKS_COLL).count(query, function (error, c) {
expect(error).to.not.exist;
expect(c).to.equal(0);
uploadStream.write('b', 'utf8', function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: this stream has been aborted'
);
uploadStream.end('c', 'utf8', function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: this stream has been aborted'
);
// Fail if user tries to abort an aborted stream
uploadStream.abort().then(null, function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: Cannot call abort() on a stream twice'
);
client.close(done);
});
});
});
});
});
});
});
});
}
});
/**
* Aborting an upload
*/
it('Destroy an upload', {
metadata: { requires: { topology: ['single'], node: '>12.0.0' } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsabort', chunkSizeBytes: 1 });
const CHUNKS_COLL = 'gridfsabort.chunks';
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
const query = { files_id: id };
uploadStream.write('a', 'utf8', function (error) {
expect(error).to.not.exist;
db.collection(CHUNKS_COLL).count(query, function (error, c) {
expect(error).to.not.exist;
expect(c).to.equal(1);
uploadStream.abort(function (error) {
expect(error).to.not.exist;
db.collection(CHUNKS_COLL).count(query, function (error, c) {
expect(error).to.not.exist;
expect(c).to.equal(0);
uploadStream.write('b', 'utf8', function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: this stream has been aborted'
);
uploadStream.end('c', 'utf8', function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: this stream has been aborted'
);
// Fail if user tries to abort an aborted stream
uploadStream.abort().then(null, function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: Cannot call abort() on a stream twice'
);
client.close(done);
});
});
});
});
});
});
});
});
}
});
/**
* Calling abort() on a GridFSBucketReadStream
*
* @example-class GridFSBucketReadStream
* @example-method abort
*/
it('Destroying a download stream', {
metadata: { requires: { topology: ['single'], apiVersion: false } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdestroy', chunkSizeBytes: 10 });
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
// Wait for stream to finish
uploadStream.once('finish', function () {
const id = uploadStream.id;
const downloadStream = bucket.openDownloadStream(id);
const finished = {};
downloadStream.on('data', function () {
expect.fail('Should be unreachable');
});
downloadStream.on('error', function () {
expect.fail('Should be unreachable');
});
downloadStream.on('end', function () {
expect(downloadStream.s.cursor).to.not.exist;
if (finished.close) {
client.close(done);
return;
}
finished.end = true;
});
downloadStream.on('close', function () {
if (finished.end) {
client.close(done);
return;
}
finished.close = true;
});
downloadStream.abort(function (error) {
expect(error).to.not.exist;
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Deleting a file from GridFS using promises
*
* @example-class GridFSBucket
* @example-method delete
*/
it('Deleting a file using promises', {
metadata: {
requires: { topology: ['single'], node: '>12.0.0', sessions: { skipLeakTests: true } }
},
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const CHUNKS_COLL = 'gridfsdownload.chunks';
const FILES_COLL = 'gridfsdownload.files';
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
uploadStream.once('finish', function () {
bucket.delete(id).then(function () {
const chunksQuery = db.collection(CHUNKS_COLL).find({ files_id: id });
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
const filesQuery = db.collection(FILES_COLL).find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
client.close(done);
});
});
});
});
readStream.pipe(uploadStream);
});
}
});
it('find()', {
metadata: { requires: { topology: ['single'], sessions: { skipLeakTests: true } } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'fs' });
// We're only making sure this doesn't throw
bucket.find({
batchSize: 1,
limit: 2,
maxTimeMS: 3,
noCursorTimeout: true,
skip: 4,
sort: { _id: 1 }
});
client.close(done);
});
}
});
/**
* Drop an entire buckets files and chunks
*
* @example-class GridFSBucket
* @example-method drop
*/
it('drop example', {
metadata: { requires: { topology: ['single'], sessions: { skipLeakTests: true } } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const CHUNKS_COLL = 'gridfsdownload.chunks';
const FILES_COLL = 'gridfsdownload.files';
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
uploadStream.once('finish', function () {
bucket.drop(function (err) {
expect(err).to.not.exist;
const chunksQuery = db.collection(CHUNKS_COLL).find({ files_id: id });
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
const filesQuery = db.collection(FILES_COLL).find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
client.close(done);
});
});
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Drop an entire buckets files and chunks using promises
*
* @example-class GridFSBucket
* @example-method drop
*/
it('drop using promises', {
metadata: { requires: { topology: ['single'], node: '>12.0.0' } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const CHUNKS_COLL = 'gridfsdownload.chunks';
const FILES_COLL = 'gridfsdownload.files';
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
uploadStream.once('finish', function () {
bucket.drop().then(function () {
const chunksQuery = db.collection(CHUNKS_COLL).find({ files_id: id });
chunksQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
const filesQuery = db.collection(FILES_COLL).find({ _id: id });
filesQuery.toArray(function (error, docs) {
expect(error).to.not.exist;
expect(docs.length).to.equal(0);
client.close(done);
});
});
});
});
readStream.pipe(uploadStream);
});
}
});
/*
* Find all associates files with a bucket
*
* @example-class GridFSBucket
* @example-method find
*/
it('find example', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload_2' });
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
uploadStream.once('finish', function () {
bucket.find({}, { batchSize: 1 }).toArray(function (err, files) {
expect(err).to.not.exist;
expect(1).to.equal(files.length);
client.close(done);
});
});
readStream.pipe(uploadStream);
});
}
});
/**
* Rename a file
*
* @example-class GridFSBucket
* @example-method rename
*/
it('rename example', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload_3' });
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
uploadStream.once('finish', function () {
// Rename the file
bucket.rename(id, 'renamed_it.dat', function (err) {
expect(err).to.not.exist;
client.close(done);
});
});
readStream.pipe(uploadStream);
});
}
});
it('download empty doc', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'fs' });
db.collection('fs.files').insertMany([{ length: 0 }], function (error, result) {
expect(error).to.not.exist;
expect(Object.keys(result.insertedIds).length).to.equal(1);
const id = result.insertedIds[0];
const stream = bucket.openDownloadStream(id);
stream.on('error', function (error) {
expect(error).to.not.exist;
});
stream.on('data', function () {
expect.fail('Should be unreachable');
});
stream.on('end', function () {
// As per spec, make sure we didn't actually fire a query
// because the document length is 0
expect(stream.s.cursor).to.not.exist;
client.close(done);
});
});
});
}
});
it('should use chunkSize for download', {
metadata: { requires: { topology: ['single'] } },
test(done) {
if (typeof stream.pipeline !== 'function') {
this.skip();
}
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfs' });
const uploadStream = bucket.openUploadStream('test');
uploadStream.end(Buffer.alloc(40 * 1024 * 1024), err => {
expect(err).to.not.exist;
const range = {
start: 35191617,
end: 35192831
};
const downloadStream = bucket.openDownloadStreamByName('test', range);
const outputStream = fs.createWriteStream('output');
stream.pipeline(downloadStream, outputStream, err => {
expect(err).to.not.exist;
client.close(() => {
fs.stat('output', (err, stats) => {
expect(err).to.not.exist;
expect(range.end - range.start).to.equal(stats.size);
done();
});
});
});
});
});
}
});
const UPLOAD_SPEC = require('../spec/gridfs/gridfs-upload.json');
UPLOAD_SPEC.tests.forEach(function (specTest) {
(function (testSpec) {
it(testSpec.description, {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), {
maxPoolSize: 1
});
client.connect(function (err, client) {
const db = client.db(configuration.db);
db.dropDatabase(function (error) {
expect(error).to.not.exist;
const bucket = new GridFSBucket(db, { bucketName: 'expected' });
const res = bucket.openUploadStream(
testSpec.act.arguments.filename,
testSpec.act.arguments.options
);
const buf = Buffer.from(testSpec.act.arguments.source.$hex, 'hex');
res.on('error', function (err) {
expect(err).to.not.exist;
});
res.on('finish', function () {
const data = testSpec.assert.data;
let num = data.length;
data.forEach(function (data) {
const collection = data.insert;
db.collection(collection)
.find({})
.toArray(function (error, docs) {
expect(data.documents.length).to.equal(docs.length);
for (let i = 0; i < docs.length; ++i) {
testResultDoc(data.documents[i], docs[i], res.id);
}
if (--num === 0) {
client.close(done);
}
});
});
});
res.write(buf);
res.end();
});
});
}
});
})(specTest);
});
const DOWNLOAD_SPEC = require('../spec/gridfs/gridfs-download.json');
DOWNLOAD_SPEC.tests.forEach(function (specTest) {
(function (testSpec) {
it(testSpec.description, {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), {
maxPoolSize: 1
});
client.connect(function (err, client) {
const db = client.db(configuration.db);
db.dropDatabase(function (err) {
expect(err).to.not.exist;
const BUCKET_NAME = 'fs';
const _runTest = function () {
const bucket = new GridFSBucket(db, { bucketName: BUCKET_NAME });
let res = Buffer.alloc(0);
const download = bucket.openDownloadStream(
EJSON.parse(JSON.stringify(testSpec.act.arguments.id), { relaxed: true })
);
download.on('data', function (chunk) {
res = Buffer.concat([res, chunk]);
});
let errorReported = false;
download.on('error', function (error) {
errorReported = true;
if (!testSpec.assert.error) {
expect.fail('Should be unreached');
// We need to abort in order to close the underlying cursor,
// and by extension the implicit session used for the cursor.
// This is only necessary if the cursor is not exhausted
download.abort();
client.close(done);
}
expect(error.toString().indexOf(testSpec.assert.error) !== -1).to.equal(true);
// We need to abort in order to close the underlying cursor,
// and by extension the implicit session used for the cursor.
// This is only necessary if the cursor is not exhausted
download.abort();
client.close(done);
});
download.on('end', function () {
const result = testSpec.assert.result;
if (!result) {
if (errorReported) {
return;
}
// We need to abort in order to close the underlying cursor,
// and by extension the implicit session used for the cursor.
// This is only necessary if the cursor is not exhausted
download.abort();
client.close(done);
expect.fail('errorReported should be set');
}
expect(res.toString('hex')).to.equal(result.$hex);
// We need to abort in order to close the underlying cursor,
// and by extension the implicit session used for the cursor.
// This is only necessary if the cursor is not exhausted
download.abort();
client.close(done);
});
};
const keys = Object.keys(DOWNLOAD_SPEC.data);
let numCollections = Object.keys(DOWNLOAD_SPEC.data).length;
keys.forEach(function (collection) {
const data = DOWNLOAD_SPEC.data[collection].map(function (v) {
return deflateTestDoc(v);
});
db.collection(BUCKET_NAME + '.' + collection).insertMany(data, function (error) {
expect(error).to.not.exist;
if (--numCollections === 0) {
if (testSpec.arrange) {
// only support 1 arrange op for now
expect(testSpec.arrange.data.length).to.equal(1);
applyArrange(db, deflateTestDoc(testSpec.arrange.data[0]), function (error) {
expect(error).to.not.exist;
_runTest();
});
} else {
_runTest();
}
}
});
});
});
});
}
});
})(specTest);
});
function testResultDoc(specDoc, resDoc, result) {
const specKeys = Object.keys(specDoc)
.filter(key => key !== 'md5')
.sort();
const resKeys = Object.keys(resDoc).sort();
expect(specKeys.length === resKeys.length).to.equal(true);
for (let i = 0; i < specKeys.length; ++i) {
const key = specKeys[i];
expect(specKeys[i]).to.equal(resKeys[i]);
if (specDoc[key] === '*actual') {
expect(resDoc[key]).to.exist;
} else if (specDoc[key] === '*result') {
expect(resDoc[key].toString()).to.equal(result.toString());
} else if (specDoc[key].$hex) {
expect(resDoc[key]._bsontype === 'Binary').to.equal(true);
expect(resDoc[key].toString('hex')).to.equal(specDoc[key].$hex);
} else {
if (typeof specDoc[key] === 'object') {
expect(specDoc[key]).to.deep.equal(resDoc[key]);
} else {
expect(specDoc[key]).to.equal(resDoc[key]);
}
}
}
}
function deflateTestDoc(doc) {
const ret = EJSON.parse(JSON.stringify(doc), { relaxed: true });
convert$hexToBuffer(ret);
return ret;
}
function convert$hexToBuffer(doc) {
const keys = Object.keys(doc);
keys.forEach(function (key) {
if (doc[key] && typeof doc[key] === 'object') {
if (doc[key].$hex != null) {
doc[key] = Buffer.from(doc[key].$hex, 'hex');
} else {
convert$hexToBuffer(doc[key]);
}
}
});
}
function applyArrange(db, command, callback) {
// Don't count on commands being there since we need to test on 2.2 and 2.4
if (command.delete) {
if (command.deletes.length !== 1) {
return callback(new Error('can only arrange with 1 delete'));
}
if (command.deletes[0].limit !== 1) {
return callback(new Error('can only arrange with delete limit 1'));
}
db.collection(command.delete).deleteOne(command.deletes[0].q, callback);
} else if (command.insert) {
db.collection(command.insert).insertMany(command.documents, callback);
} else if (command.update) {
const bulk = [];
for (let i = 0; i < command.updates.length; ++i) {
bulk.push({
updateOne: {
filter: command.updates[i].q,
update: command.updates[i].u
}
});
}
db.collection(command.update).bulkWrite(bulk, callback);
} else {
const msg = 'Command not recognized: ' + require('util').inspect(command);
callback(new Error(msg));
}
}
/**
* NODE-822 GridFSBucketWriteStream end method does not handle optional parameters
*/
it('should correctly handle calling end function with only a callback', {
metadata: { requires: { topology: ['single'], node: '>4.0.0' } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsabort', chunkSizeBytes: 1 });
const CHUNKS_COLL = 'gridfsabort.chunks';
const uploadStream = bucket.openUploadStream('test.dat');
const id = uploadStream.id;
const query = { files_id: id };
uploadStream.write('a', 'utf8', function (error) {
expect(error).to.not.exist;
db.collection(CHUNKS_COLL).count(query, function (error, c) {
expect(error).to.not.exist;
expect(c).to.equal(1);
uploadStream.abort(function (error) {
expect(error).to.not.exist;
db.collection(CHUNKS_COLL).count(query, function (error, c) {
expect(error).to.not.exist;
expect(c).to.equal(0);
uploadStream.write('b', 'utf8', function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: this stream has been aborted'
);
uploadStream.end(function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: this stream has been aborted'
);
// Fail if user tries to abort an aborted stream
uploadStream.abort().then(null, function (error) {
expect(error.toString()).to.equal(
'MongoDriverError: Cannot call abort() on a stream twice'
);
client.close(done);
});
});
});
});
});
});
});
});
}
});
/**
* Provide start and end parameters for file download to skip ahead x bytes and limit the total amount of bytes read to n
*
* @example-class GridFSBucket
* @example-method openDownloadStream
*/
it('NODE-829 start/end options for openDownloadStream where start-end is < size of chunk', {
metadata: { requires: { topology: ['single'] } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), { maxPoolSize: 1 });
client.connect(function (err, client) {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, {
bucketName: 'gridfsdownload',
chunkSizeBytes: 20
});
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('teststart.dat');
uploadStream.once('finish', function () {
const downloadStream = bucket
.openDownloadStreamByName('teststart.dat', { start: 1 })
.end(6);
downloadStream.on('error', function (error) {
expect(error).to.not.exist;
});
let gotData = 0;
let str = '';
downloadStream.on('data', function (data) {
++gotData;
str += data.toString('utf8');
});
downloadStream.on('end', function () {
// Depending on different versions of node, we may get
// different amounts of 'data' events. node 0.10 gives 2,
// node >= 0.12 gives 3. Either is correct, but we just
// care that we got between 1 and 3, and got the right result
expect(gotData >= 1 && gotData <= 3).to.equal(true);
expect(str).to.equal('pache');
client.close(done);
});
});
readStream.pipe(uploadStream);
});
}
});
it('should correctly handle indexes create with BSON.Double', function (done) {
const configuration = this.configuration;
const client = configuration.newClient();
client.connect((err, client) => {
expect(err).to.not.exist;
const db = client.db(configuration.db);
const col = db.collection('fs.files');
col.createIndex({ filename: new Double(1.0), uploadDate: new Double(1.0) }, err => {
expect(err).to.not.exist;
col.listIndexes().toArray((err, indexes) => {
expect(err).to.not.exist;
const names = indexes.map(i => i.name);
expect(names).to.eql(['_id_', 'filename_1_uploadDate_1']);
client.close();
done();
});
});
});
});
it('NODE-2623 downloadStream should emit error on end > size', function () {
const configuration = this.configuration;
return withClient.bind(this)((client, done) => {
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('test.dat');
const actualSize = fs.fstatSync(fs.openSync('./LICENSE.md', 'r')).size;
const wrongExpectedSize = Math.floor(actualSize * 1.1);
const id = uploadStream.id;
uploadStream.once('finish', function () {
const downloadStream = bucket.openDownloadStream(id, { end: wrongExpectedSize });
downloadStream.on('data', function () {});
downloadStream.on('error', function (err) {
expect(err.message).to.equal(
`Stream end (${wrongExpectedSize}) must not be more than the length of the file (${actualSize})`
);
done();
});
});
readStream.pipe(uploadStream);
});
});
});
| 1 | 20,700 | Would it be appropriate for this to be a `MongoStreamClosedError`? | mongodb-node-mongodb-native | js |
@@ -26,11 +26,13 @@ import (
"github.com/golang/glog"
"github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
clientset "github.com/openebs/maya/pkg/client/generated/clientset/internalclientset"
+ snapclient "github.com/openebs/maya/pkg/client/generated/openebs.io/snapshot/v1/clientset/internalclientset"
"k8s.io/api/admission/v1beta1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
+ "k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer" | 1 | /*
Copyright 2019 The OpenEBS Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package webhook
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/golang/glog"
"github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
clientset "github.com/openebs/maya/pkg/client/generated/clientset/internalclientset"
"k8s.io/api/admission/v1beta1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes"
)
var (
runtimeScheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(runtimeScheme)
deserializer = codecs.UniversalDeserializer()
// (https://github.com/kubernetes/kubernetes/issues/57982)
defaulter = runtime.ObjectDefaulter(runtimeScheme)
)
// Skip validation in special namespaces, i.e. in kube-system and kube-public
// namespaces the validation will be skipped
var (
ignoredNamespaces = []string{
metav1.NamespaceSystem,
metav1.NamespacePublic,
}
)
// webhook implements a validating webhook.
type webhook struct {
// Server defines parameters for running an golang HTTP server.
Server *http.Server
// kubeClient is a standard kubernetes clientset
kubeClient kubernetes.Interface
// clientset is a openebs custom resource package generated for custom API group.
clientset clientset.Interface
}
// Parameters are server configures parameters
type Parameters struct {
// Port is webhook server port
Port int
//CertFile is path to the x509 certificate for https
CertFile string
//KeyFile is path to the x509 private key matching `CertFile`
KeyFile string
}
func init() {
_ = corev1.AddToScheme(runtimeScheme)
_ = admissionregistrationv1beta1.AddToScheme(runtimeScheme)
// defaulting with webhooks:
// https://github.com/kubernetes/kubernetes/issues/57982
_ = v1.AddToScheme(runtimeScheme)
}
// New creates a new instance of a webhook.
func New(p Parameters, kubeClient kubernetes.Interface, openebsClient clientset.Interface) (*webhook, error) {
pair, err := tls.LoadX509KeyPair(p.CertFile, p.KeyFile)
if err != nil {
return nil, err
}
wh := &webhook{
Server: &http.Server{
Addr: fmt.Sprintf(":%v", p.Port),
TLSConfig: &tls.Config{Certificates: []tls.Certificate{pair}},
},
kubeClient: kubeClient,
clientset: openebsClient,
}
return wh, nil
}
func admissionRequired(ignoredList []string, metadata *metav1.ObjectMeta) bool {
// skip special kubernetes system namespaces
for _, namespace := range ignoredList {
if metadata.Namespace == namespace {
glog.V(4).Infof("Skip validation for %v for it's in special namespace:%v", metadata.Name, metadata.Namespace)
return false
}
}
return true
}
func validationRequired(ignoredList []string, metadata *metav1.ObjectMeta) bool {
required := admissionRequired(ignoredList, metadata)
glog.V(4).Infof("Validation policy for %v/%v: required:%v", metadata.Namespace, metadata.Name, required)
return required
}
// validate validates the persistentvolumeclaim(PVC) delete request
func (wh *webhook) validate(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
req := ar.Request
response := &v1beta1.AdmissionResponse{}
// validates only if requested operation is DELETE and request kind is PVC
if ar.Request.Operation != v1beta1.Delete || req.Kind.Kind != "PersistentVolumeClaim" {
response.Allowed = true
return response
}
// ignore the Delete request of PVC if resource name is empty which
// can happen as part of cleanup process of namespace
if ar.Request.Name == "" {
response.Allowed = true
return response
}
glog.Infof("AdmissionReview for Kind=%v, Namespace=%v Name=%v UID=%v patchOperation=%v UserInfo=%v",
req.Kind, req.Namespace, req.Name, req.UID, req.Operation, req.UserInfo)
// TODO* use raw object once validation webhooks support DELETE request
// object as non nil value https://github.com/kubernetes/kubernetes/issues/66536
//var pvc corev1.PersistentVolumeClaim
//err := json.Unmarshal(req.Object.Raw, &pvc)
//if err != nil {
// glog.Errorf("Could not unmarshal raw object: %v, %v", err, req.Object.Raw)
// status.Allowed = false
// status.Result = &metav1.Status{
// Status: metav1.StatusFailure, Code: http.StatusBadRequest, Reason: metav1.StatusReasonBadRequest,
// Message: err.Error(),
// }
// return status
//}
// fetch the pvc specifications
pvc, err := wh.kubeClient.CoreV1().PersistentVolumeClaims(req.Namespace).Get(req.Name, metav1.GetOptions{})
if err != nil {
response.Allowed = false
response.Result = &metav1.Status{
Message: fmt.Sprintf("error retrieving PVC: %v", err.Error()),
}
return response
}
if !validationRequired(ignoredNamespaces, &pvc.ObjectMeta) {
glog.V(4).Infof("Skipping validation for %s/%s due to policy check", pvc.Namespace, pvc.Name)
return &v1beta1.AdmissionResponse{
Allowed: true,
}
}
// construct source-volume label to list all the matched cstorVolumes
label := fmt.Sprintf("openebs.io/source-volume=%s", pvc.Spec.VolumeName)
listOptions := metav1.ListOptions{
LabelSelector: label,
}
// get the all CStorVolumes resources in all namespaces based on the
// source-volume label to verify if there is any clone volume exists.
// if source-volume label matches with name of PV, failed the pvc
// deletion operation.
response.Allowed = true
cStorVolumes, err := wh.getCstorVolumes(listOptions)
if err != nil {
response.Allowed = false
response.Result = &metav1.Status{
Message: fmt.Sprintf("error retrieving CstorVolumes: %v", err.Error()),
}
return response
}
if len(cStorVolumes.Items) != 0 {
response.Allowed = false
response.Result = &metav1.Status{
Status: metav1.StatusFailure, Code: http.StatusForbidden, Reason: "PVC with cloned volumes can't be deleted",
Message: fmt.Sprintf("pvc %q has '%v' cloned volume(s)", pvc.Name, len(cStorVolumes.Items)),
}
}
return response
}
// getCstorVolumes gets the list of CstorVolumes based in the source-volume labels
func (wh *webhook) getCstorVolumes(listOptions metav1.ListOptions) (*v1alpha1.CStorVolumeList, error) {
var cStorVolumes *v1alpha1.CStorVolumeList
var err error
cStorVolumes, err = wh.clientset.OpenebsV1alpha1().CStorVolumes("").List(listOptions)
return cStorVolumes, err
}
// Serve method for webhook server, handles http requests for webhooks
func (wh *webhook) Serve(w http.ResponseWriter, r *http.Request) {
var body []byte
if r.Body != nil {
if data, err := ioutil.ReadAll(r.Body); err == nil {
body = data
}
}
if len(body) == 0 {
glog.Error("empty body")
http.Error(w, "empty body", http.StatusBadRequest)
return
}
// verify the content type is accurate
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
glog.Errorf("Content-Type=%s, expect application/json", contentType)
http.Error(w, "invalid Content-Type, expect `application/json`", http.StatusUnsupportedMediaType)
return
}
var admissionResponse *v1beta1.AdmissionResponse
ar := v1beta1.AdmissionReview{}
if _, _, err := deserializer.Decode(body, nil, &ar); err != nil {
glog.Errorf("Can't decode body: %v", err)
admissionResponse = &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
} else {
if r.URL.Path == "/validate" {
admissionResponse = wh.validate(&ar)
}
}
admissionReview := v1beta1.AdmissionReview{}
if admissionResponse != nil {
admissionReview.Response = admissionResponse
if ar.Request != nil {
admissionReview.Response.UID = ar.Request.UID
}
}
resp, err := json.Marshal(admissionReview)
if err != nil {
glog.Errorf("Can't encode response: %v", err)
http.Error(w, fmt.Sprintf("could not encode response: %v", err), http.StatusInternalServerError)
}
glog.V(5).Infof("Ready to write reponse ...")
if _, err := w.Write(resp); err != nil {
glog.Errorf("Can't write response: %v", err)
http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError)
}
}
| 1 | 12,113 | Can you raise new issue that talks about refactoring webhook code. It should follow `idiomatic maya` patterns. | openebs-maya | go |
@@ -0,0 +1,9 @@
+using Datadog.Trace.Interfaces;
+
+namespace Datadog.Trace.ClrProfiler.Interfaces
+{
+ internal interface ISpanDecorator
+ {
+ void Decorate(ISpan span);
+ }
+} | 1 | 1 | 14,665 | (Probably repeating myself) Instead of `Datadog.Trace.Interfaces`, should we move this and several other files into a `Datadog.Trace.Decorators` namespace instead? | DataDog-dd-trace-dotnet | .cs |
|
@@ -1,6 +1,7 @@
# -*- encoding : utf-8 -*-
require 'kaminari'
require 'rsolr'
+require 'deprecation'
module Blacklight
autoload :Configurable, 'blacklight/configurable' | 1 | # -*- encoding : utf-8 -*-
require 'kaminari'
require 'rsolr'
module Blacklight
autoload :Configurable, 'blacklight/configurable'
autoload :Configuration, 'blacklight/configuration'
autoload :SearchFields, 'blacklight/search_fields'
autoload :Solr, 'blacklight/solr'
autoload :SolrHelper, 'blacklight/solr_helper'
autoload :SolrRepository, 'blacklight/solr_repository'
autoload :RequestBuilders, 'blacklight/request_builders'
autoload :Exceptions, 'blacklight/exceptions'
autoload :User, 'blacklight/user'
autoload :Controller, 'blacklight/controller'
autoload :Base, 'blacklight/base'
autoload :Catalog, 'blacklight/catalog'
autoload :TokenBasedUser, 'blacklight/token_based_user'
autoload :Bookmarks, 'blacklight/bookmarks'
autoload :DocumentPresenter, 'blacklight/document_presenter'
autoload :Routes, 'blacklight/routes'
autoload :OpenStructWithHashAccess, 'blacklight/utils'
autoload :SolrResponse, 'blacklight/solr_response'
autoload :Facet, 'blacklight/facet'
extend SearchFields
require 'blacklight/version'
require 'blacklight/engine' if defined?(Rails)
class << self
attr_accessor :solr, :solr_config
end
# Secret key used to share session information with
# other services (e.g. refworks callback urls)
mattr_accessor :secret_key
@@secret_key = nil
def self.solr_file
"#{::Rails.root.to_s}/config/solr.yml"
end
def self.add_routes(router, options = {})
Blacklight::Routes.new(router, options).draw
end
def self.solr
@solr ||= RSolr.connect(Blacklight.solr_config)
end
def self.solr_config
@solr_config ||= begin
raise "The #{::Rails.env} environment settings were not found in the solr.yml config" unless solr_yml[::Rails.env]
solr_yml[::Rails.env].symbolize_keys
end
end
def self.solr_yml
require 'erb'
require 'yaml'
return @solr_yml if @solr_yml
unless File.exists?(solr_file)
raise "You are missing a solr configuration file: #{solr_file}. Have you run \"rails generate blacklight:install\"?"
end
begin
@solr_erb = ERB.new(IO.read(solr_file)).result(binding)
rescue Exception => e
raise("solr.yml was found, but could not be parsed with ERB. \n#{$!.inspect}")
end
begin
@solr_yml = YAML::load(@solr_erb)
rescue StandardError => e
raise("solr.yml was found, but could not be parsed.\n")
end
if @solr_yml.nil? || !@solr_yml.is_a?(Hash)
raise("solr.yml was found, but was blank or malformed.\n")
end
return @solr_yml
end
def self.logger
::Rails.logger
end
#############
# Methods for figuring out path to BL plugin, and then locate various files
# either in the app itself or defaults in the plugin -- whether you are running
# from the plugin itself or from an actual app using te plugin.
# In a seperate module so it can be used by both Blacklight class, and
# by rake tasks without loading the whole Rails environment.
#############
# returns the full path the the blacklight plugin installation
def self.root
@root ||= File.expand_path(File.dirname(File.dirname(__FILE__)))
end
end
| 1 | 5,639 | Should we generate `gem "rsolr"` into the application Gemfile? | projectblacklight-blacklight | rb |
@@ -130,6 +130,8 @@ static struct optparse_option attach_opts[] = {
{ .name = "label-io", .key = 'l', .has_arg = 0,
.usage = "Label output by rank",
},
+ { .name = "verbose", .key = 'v', .has_arg = 0,
+ .usage = "Increase verbosity" },
{ .name = "quiet", .key = 'q', .has_arg = 0,
.usage = "Suppress warnings written to stderr from flux-job",
}, | 1 | /************************************************************\
* Copyright 2018 Lawrence Livermore National Security, LLC
* (c.f. AUTHORS, NOTICE.LLNS, COPYING)
*
* This file is part of the Flux resource manager framework.
* For details, see https://github.com/flux-framework.
*
* SPDX-License-Identifier: LGPL-3.0
\************************************************************/
/* "plumbing" commands (see git(1)) for Flux job management */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <jansson.h>
#include <argz.h>
#include <czmq.h>
#include <flux/core.h>
#include <flux/optparse.h>
#if HAVE_FLUX_SECURITY
#include <flux/security/sign.h>
#endif
#include "src/common/libutil/xzmalloc.h"
#include "src/common/libutil/log.h"
#include "src/common/libutil/fluid.h"
#include "src/common/libjob/job.h"
#include "src/common/libutil/read_all.h"
#include "src/common/libutil/monotime.h"
#include "src/common/libidset/idset.h"
#include "src/common/libeventlog/eventlog.h"
#include "src/common/libioencode/ioencode.h"
int cmd_list (optparse_t *p, int argc, char **argv);
int cmd_submit (optparse_t *p, int argc, char **argv);
int cmd_attach (optparse_t *p, int argc, char **argv);
int cmd_id (optparse_t *p, int argc, char **argv);
int cmd_namespace (optparse_t *p, int argc, char **argv);
int cmd_cancel (optparse_t *p, int argc, char **argv);
int cmd_raise (optparse_t *p, int argc, char **argv);
int cmd_kill (optparse_t *p, int argc, char **argv);
int cmd_priority (optparse_t *p, int argc, char **argv);
int cmd_eventlog (optparse_t *p, int argc, char **argv);
int cmd_wait_event (optparse_t *p, int argc, char **argv);
int cmd_info (optparse_t *p, int argc, char **argv);
int cmd_stats (optparse_t *p, int argc, char **argv);
int cmd_drain (optparse_t *p, int argc, char **argv);
int cmd_wait (optparse_t *p, int argc, char **argv);
int stdin_flags;
static struct optparse_option global_opts[] = {
OPTPARSE_TABLE_END
};
static struct optparse_option list_opts[] = {
{ .name = "count", .key = 'c', .has_arg = 1, .arginfo = "N",
.usage = "Limit output to N jobs",
},
{ .name = "states", .key = 's', .has_arg = 1, .arginfo = "STATES",
.flags = OPTPARSE_OPT_AUTOSPLIT,
.usage = "List jobs in specific states",
},
{ .name = "userid", .key = 'u', .has_arg = 1, .arginfo = "UID",
.usage = "Limit output to specific userid. " \
"Specify \"all\" for all users.",
},
{ .name = "all-user", .key = 'a', .has_arg = 0,
.usage = "List my jobs, regardless of state",
},
{ .name = "all", .key = 'A', .has_arg = 0,
.usage = "List jobs for all users, regardless of state",
},
OPTPARSE_TABLE_END
};
static struct optparse_option raise_opts[] = {
{ .name = "severity", .key = 's', .has_arg = 1, .arginfo = "N",
.usage = "Set exception severity [0-7] (default=0)",
},
{ .name = "type", .key = 't', .has_arg = 1, .arginfo = "TYPE",
.usage = "Set exception type (default=cancel)",
},
OPTPARSE_TABLE_END
};
static struct optparse_option kill_opts[] = {
{ .name = "signal", .key = 's', .has_arg = 1, .arginfo = "SIG",
.usage = "Send signal SIG (default SIGTERM)",
},
OPTPARSE_TABLE_END
};
static struct optparse_option submit_opts[] = {
{ .name = "priority", .key = 'p', .has_arg = 1, .arginfo = "N",
.usage = "Set job priority (0-31, default=16)",
},
{ .name = "flags", .key = 'f', .has_arg = 3,
.flags = OPTPARSE_OPT_AUTOSPLIT,
.usage = "Set submit comma-separated flags (e.g. debug, waitable)",
},
#if HAVE_FLUX_SECURITY
{ .name = "security-config", .key = 'c', .has_arg = 1, .arginfo = "pattern",
.usage = "Use non-default security config glob",
},
{ .name = "sign-type", .key = 's', .has_arg = 1, .arginfo = "TYPE",
.usage = "Use non-default mechanism type to sign J",
},
#endif
OPTPARSE_TABLE_END
};
static struct optparse_option attach_opts[] = {
{ .name = "show-events", .key = 'E', .has_arg = 0,
.usage = "Show job events on stderr",
},
{ .name = "show-exec", .key = 'X', .has_arg = 0,
.usage = "Show exec events on stderr",
},
{ .name = "label-io", .key = 'l', .has_arg = 0,
.usage = "Label output by rank",
},
{ .name = "quiet", .key = 'q', .has_arg = 0,
.usage = "Suppress warnings written to stderr from flux-job",
},
OPTPARSE_TABLE_END
};
static struct optparse_option id_opts[] = {
{ .name = "from", .key = 'f', .has_arg = 1,
.arginfo = "dec|kvs|hex|words",
.usage = "Convert jobid from specified form",
},
{ .name = "to", .key = 't', .has_arg = 1,
.arginfo = "dec|kvs|hex|words",
.usage = "Convert jobid to specified form",
},
OPTPARSE_TABLE_END
};
static struct optparse_option eventlog_opts[] = {
{ .name = "format", .key = 'f', .has_arg = 1, .arginfo = "FORMAT",
.usage = "Specify output format: text, json",
},
{ .name = "time-format", .key = 'T', .has_arg = 1, .arginfo = "FORMAT",
.usage = "Specify time format: raw, iso, offset",
},
{ .name = "path", .key = 'p', .has_arg = 1, .arginfo = "PATH",
.usage = "Specify alternate eventlog path suffix "
"(e.g. \"guest.exec.eventlog\")",
},
OPTPARSE_TABLE_END
};
static struct optparse_option wait_event_opts[] = {
{ .name = "format", .key = 'f', .has_arg = 1, .arginfo = "FORMAT",
.usage = "Specify output format: text, json",
},
{ .name = "time-format", .key = 'T', .has_arg = 1, .arginfo = "FORMAT",
.usage = "Specify time format: raw, iso, offset",
},
{ .name = "timeout", .key = 't', .has_arg = 1, .arginfo = "DURATION",
.usage = "timeout after DURATION",
},
{ .name = "match-context", .key = 'm', .has_arg = 1, .arginfo = "KEY=VAL",
.usage = "match key=val in context",
},
{ .name = "quiet", .key = 'q', .has_arg = 0,
.usage = "Do not output matched event",
},
{ .name = "verbose", .key = 'v', .has_arg = 0,
.usage = "Output all events before matched event",
},
{ .name = "path", .key = 'p', .has_arg = 1, .arginfo = "PATH",
.usage = "Specify alternate eventlog path suffix "
"(e.g. \"guest.exec.eventlog\")",
},
OPTPARSE_TABLE_END
};
static struct optparse_option drain_opts[] = {
{ .name = "timeout", .key = 't', .has_arg = 1, .arginfo = "DURATION",
.usage = "timeout after DURATION",
},
OPTPARSE_TABLE_END
};
static struct optparse_subcommand subcommands[] = {
{ "list",
"[OPTIONS]",
"List jobs",
cmd_list,
0,
list_opts
},
{ "priority",
"[OPTIONS] id priority",
"Set job priority",
cmd_priority,
0,
NULL,
},
{ "cancel",
"[OPTIONS] id [message ...]",
"Cancel a job",
cmd_cancel,
0,
NULL,
},
{ "raise",
"[OPTIONS] id [message ...]",
"Raise exception for job",
cmd_raise,
0,
raise_opts,
},
{ "kill",
"[OPTIONS] id",
"Send signal to running job",
cmd_kill,
0,
kill_opts,
},
{ "attach",
"[OPTIONS] id",
"Interactively attach to job",
cmd_attach,
0,
attach_opts,
},
{ "submit",
"[OPTIONS] [jobspec]",
"Run job",
cmd_submit,
0,
submit_opts
},
{ "id",
"[OPTIONS] [id ...]",
"Convert jobid(s) to another form",
cmd_id,
0,
id_opts
},
{ "eventlog",
"[-f text|json] [-T raw|iso|offset] [-p path] id",
"Display eventlog for a job",
cmd_eventlog,
0,
eventlog_opts
},
{ "wait-event",
"[-f text|json] [-T raw|iso|offset] [-t seconds] [-m key=val] "
"[-p path] id event",
"Wait for an event ",
cmd_wait_event,
0,
wait_event_opts
},
{ "info",
"id key ...",
"Display info for a job",
cmd_info,
0,
NULL
},
{ "stats",
NULL,
"Get current job stats",
cmd_stats,
0,
NULL
},
{ "drain",
"[-t seconds]",
"Wait for queue to become empty.",
cmd_drain,
0,
drain_opts
},
{ "namespace",
"[id ...]",
"Convert job ids to job guest kvs namespace names",
cmd_namespace,
0,
NULL
},
{ "wait",
"[id]",
"Wait for job to complete.",
cmd_wait,
0,
NULL
},
OPTPARSE_SUBCMD_END
};
int usage (optparse_t *p, struct optparse_option *o, const char *optarg)
{
struct optparse_subcommand *s;
optparse_print_usage (p);
fprintf (stderr, "\n");
fprintf (stderr, "Common commands from flux-job:\n");
s = subcommands;
while (s->name) {
fprintf (stderr, " %-15s %s\n", s->name, s->doc);
s++;
}
exit (1);
}
int main (int argc, char *argv[])
{
char *cmdusage = "[OPTIONS] COMMAND ARGS";
optparse_t *p;
int optindex;
int exitval;
log_init ("flux-job");
p = optparse_create ("flux-job");
if (optparse_add_option_table (p, global_opts) != OPTPARSE_SUCCESS)
log_msg_exit ("optparse_add_option_table() failed");
/* Override help option for our own */
if (optparse_set (p, OPTPARSE_USAGE, cmdusage) != OPTPARSE_SUCCESS)
log_msg_exit ("optparse_set (USAGE)");
/* Override --help callback in favor of our own above */
if (optparse_set (p, OPTPARSE_OPTION_CB, "help", usage) != OPTPARSE_SUCCESS)
log_msg_exit ("optparse_set() failed");
/* Don't print internal subcommands, we do it ourselves */
if (optparse_set (p, OPTPARSE_PRINT_SUBCMDS, 0) != OPTPARSE_SUCCESS)
log_msg_exit ("optparse_set (PRINT_SUBCMDS)");
if (optparse_reg_subcommands (p, subcommands) != OPTPARSE_SUCCESS)
log_msg_exit ("optparse_reg_subcommands");
if ((optindex = optparse_parse_args (p, argc, argv)) < 0)
exit (1);
if ((argc - optindex == 0)
|| !optparse_get_subcommand (p, argv[optindex])) {
usage (p, NULL, NULL);
exit (1);
}
if ((exitval = optparse_run_subcommand (p, argc, argv)) < 0)
exit (1);
optparse_destroy (p);
log_fini ();
return (exitval);
}
/* Parse a free argument 's', expected to be a 64-bit unsigned.
* On error, exit complaining about parsing 'name'.
*/
static unsigned long long parse_arg_unsigned (const char *s, const char *name)
{
unsigned long long i;
char *endptr;
errno = 0;
i = strtoull (s, &endptr, 10);
if (errno != 0 || *endptr != '\0')
log_msg_exit ("error parsing %s: \"%s\"", name, s);
return i;
}
/* Parse free arguments into a space-delimited message.
* On error, exit complaning about parsing 'name'.
* Caller must free the resulting string
*/
static char *parse_arg_message (char **argv, const char *name)
{
char *argz = NULL;
size_t argz_len = 0;
error_t e;
if ((e = argz_create (argv, &argz, &argz_len)) != 0)
log_errn_exit (e, "error parsing %s", name);
argz_stringify (argz, argz_len, ' ');
return argz;
}
int cmd_priority (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
flux_t *h;
flux_future_t *f;
int priority;
flux_jobid_t id;
if (optindex != argc - 2) {
optparse_print_usage (p);
exit (1);
}
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
id = parse_arg_unsigned (argv[optindex++], "jobid");
priority = parse_arg_unsigned (argv[optindex++], "priority");
if (!(f = flux_job_set_priority (h, id, priority)))
log_err_exit ("flux_job_set_priority");
if (flux_rpc_get (f, NULL) < 0)
log_msg_exit ("%llu: %s", (unsigned long long)id,
future_strerror (f, errno));
flux_future_destroy (f);
flux_close (h);
return 0;
}
int cmd_raise (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
int severity = optparse_get_int (p, "severity", 0);
const char *type = optparse_get_str (p, "type", "cancel");
flux_t *h;
flux_jobid_t id;
char *note = NULL;
flux_future_t *f;
if (argc - optindex < 1) {
optparse_print_usage (p);
exit (1);
}
id = parse_arg_unsigned (argv[optindex++], "jobid");
if (optindex < argc)
note = parse_arg_message (argv + optindex, "message");
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (!(f = flux_job_raise (h, id, type, severity, note)))
log_err_exit ("flux_job_raise");
if (flux_rpc_get (f, NULL) < 0)
log_msg_exit ("%llu: %s", (unsigned long long)id,
future_strerror (f, errno));
flux_future_destroy (f);
flux_close (h);
free (note);
return 0;
}
/*
* List generated by:
*
* $ kill -l | sed 's/[0-9]*)//g' | xargs -n1 printf ' "%s",\n'
*
* (ignoring SIGRT*)
*/
static const char *sigmap[] = {
NULL, /* 1 origin */
"SIGHUP",
"SIGINT",
"SIGQUIT",
"SIGILL",
"SIGTRAP",
"SIGABRT",
"SIGBUS",
"SIGFPE",
"SIGKILL",
"SIGUSR1",
"SIGSEGV",
"SIGUSR2",
"SIGPIPE",
"SIGALRM",
"SIGTERM",
"SIGSTKFLT",
"SIGCHLD",
"SIGCONT",
"SIGSTOP",
"SIGTSTP",
"SIGTTIN",
"SIGTTOU",
"SIGURG",
"SIGXCPU",
"SIGXFSZ",
"SIGVTALRM",
"SIGPROF",
"SIGWINCH",
"SIGIO",
"SIGPWR",
"SIGSYS",
NULL,
};
static bool isnumber (const char *s, int *result)
{
char *endptr;
long int l;
errno = 0;
l = strtol (s, &endptr, 10);
if (errno
|| *endptr != '\0'
|| l <= 0) {
return false;
}
*result = (int) l;
return true;
}
static int str2signum (const char *sigstr)
{
int i;
if (isnumber (sigstr, &i)) {
if (i <= 0)
return -1;
return i;
}
i = 1;
while (sigmap[i] != NULL) {
if (strcmp (sigstr, sigmap[i]) == 0 ||
strcmp (sigstr, sigmap[i]+3) == 0)
return i;
i++;
}
return -1;
}
int cmd_kill (optparse_t *p, int argc, char **argv)
{
flux_t *h;
flux_future_t *f;
int optindex = optparse_option_index (p);
flux_jobid_t id;
const char *s;
int signum;
if (argc - optindex < 1) {
optparse_print_usage (p);
exit (1);
}
id = parse_arg_unsigned (argv[optindex++], "jobid");
s = optparse_get_str (p, "signal", "SIGTERM");
if ((signum = str2signum (s))< 0)
log_msg_exit ("kill: Invalid signal %s", s);
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (!(f = flux_job_kill (h, id, signum)))
log_err_exit ("flux_job_kill");
if (flux_rpc_get (f, NULL) < 0)
log_msg_exit ("kill %ju: %s",
(uintmax_t) id,
future_strerror (f, errno));
flux_future_destroy (f);
flux_close (h);
return 0;
}
int cmd_cancel (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
flux_t *h;
flux_jobid_t id;
char *note = NULL;
flux_future_t *f;
if (argc - optindex < 1) {
optparse_print_usage (p);
exit (1);
}
id = parse_arg_unsigned (argv[optindex++], "jobid");
if (optindex < argc)
note = parse_arg_message (argv + optindex, "message");
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (!(f = flux_job_cancel (h, id, note)))
log_err_exit ("flux_job_cancel");
if (flux_rpc_get (f, NULL) < 0)
log_msg_exit ("%llu: %s", (unsigned long long)id,
future_strerror (f, errno));
flux_future_destroy (f);
flux_close (h);
free (note);
return 0;
}
int cmd_list (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
int max_entries = optparse_get_int (p, "count", 0);
char *attrs = "[\"userid\",\"priority\",\"t_submit\",\"state\"," \
"\"name\",\"ntasks\",\"nnodes\",\"ranks\",\"t_depend\",\"t_sched\"," \
"\"t_run\",\"t_cleanup\",\"t_inactive\"]";
flux_t *h;
flux_future_t *f;
json_t *jobs;
size_t index;
json_t *value;
uint32_t userid = geteuid ();
const char *arg;
int flags = 0;
int state_mask = 0;
if (optindex != argc) {
optparse_print_usage (p);
exit (1);
}
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
optparse_getopt_iterator_reset (p, "states");
while ((arg = optparse_getopt_next (p, "states"))) {
flux_job_state_t state;
if (flux_job_strtostate (arg, &state) == 0)
state_mask |= state;
else if (!strcasecmp (arg, "pending"))
state_mask |= FLUX_JOB_PENDING;
else if (!strcasecmp (arg, "running"))
state_mask |= FLUX_JOB_RUNNING;
else if (!strcasecmp (arg, "active"))
state_mask |= FLUX_JOB_ACTIVE;
else
log_msg_exit ("error parsing --states: %s is unknown", arg);
}
if (optparse_hasopt (p, "all-user") || optparse_hasopt (p, "all"))
state_mask = FLUX_JOB_ACTIVE | FLUX_JOB_INACTIVE;
if ((state_mask & FLUX_JOB_PENDING) != 0)
flags |= FLUX_JOB_LIST_PENDING;
if ((state_mask & FLUX_JOB_RUNNING) != 0)
flags |= FLUX_JOB_LIST_RUNNING;
if ((state_mask & FLUX_JOB_INACTIVE) != 0)
flags |= FLUX_JOB_LIST_INACTIVE;
/* if no job listing specifics listed, default to listing pending
* & running jobs */
if (!flags) {
flags = FLUX_JOB_LIST_PENDING | FLUX_JOB_LIST_RUNNING;
state_mask = FLUX_JOB_PENDING | FLUX_JOB_RUNNING;
}
if ((arg = optparse_get_str (p, "userid", NULL))) {
if (!strcmp (arg, "all"))
userid = FLUX_USERID_UNKNOWN;
else {
char *endptr;
errno = 0;
userid = strtoul (arg, &endptr, 10);
if (errno != 0 || (*endptr) != '\0')
log_msg_exit ("error parsing userid: \"%s\"", arg);
}
}
if (optparse_hasopt (p, "all"))
userid = FLUX_USERID_UNKNOWN;
if (!(f = flux_job_list (h, max_entries, attrs, userid, flags)))
log_err_exit ("flux_job_list");
if (flux_rpc_get_unpack (f, "{s:o}", "jobs", &jobs) < 0)
log_err_exit ("flux_job_list");
json_array_foreach (jobs, index, value) {
char *str;
int state;
if (json_unpack (value, "{s:i}", "state", &state) < 0)
log_msg_exit ("error parsing list response (state is missing)");
if ((state & state_mask) != 0) {
str = json_dumps (value, 0);
if (!str)
log_msg_exit ("error parsing list response");
printf ("%s\n", str);
free (str);
}
}
flux_future_destroy (f);
flux_close (h);
return (0);
}
/* Read entire file 'name' ("-" for stdin). Exit program on error.
*/
size_t read_jobspec (const char *name, void **bufp)
{
int fd;
ssize_t size;
void *buf;
if (!strcmp (name, "-"))
fd = STDIN_FILENO;
else {
if ((fd = open (name, O_RDONLY)) < 0)
log_err_exit ("%s", name);
}
if ((size = read_all (fd, &buf)) < 0)
log_err_exit ("%s", name);
if (fd != STDIN_FILENO)
(void)close (fd);
*bufp = buf;
return size;
}
int cmd_submit (optparse_t *p, int argc, char **argv)
{
flux_t *h;
#if HAVE_FLUX_SECURITY
flux_security_t *sec = NULL;
const char *sec_config;
const char *sign_type;
#endif
int flags = 0;
void *jobspec;
int jobspecsz;
const char *J = NULL;
int priority;
int optindex = optparse_option_index (p);
flux_future_t *f;
flux_jobid_t id;
const char *input = "-";
if (optindex != argc - 1 && optindex != argc) {
optparse_print_usage (p);
exit (1);
}
if (optindex < argc)
input = argv[optindex++];
if (optparse_hasopt (p, "flags")) {
const char *name;
while ((name = optparse_getopt_next (p, "flags"))) {
if (!strcmp (name, "debug"))
flags |= FLUX_JOB_DEBUG;
else if (!strcmp (name, "waitable"))
flags |= FLUX_JOB_WAITABLE;
else
log_msg_exit ("unknown flag: %s", name);
}
}
#if HAVE_FLUX_SECURITY
/* If any non-default security options are specified, create security
* context so jobspec can be pre-signed before submission.
*/
if (optparse_hasopt (p, "security-config")
|| optparse_hasopt (p, "sign-type")) {
sec_config = optparse_get_str (p, "security-config", NULL);
if (!(sec = flux_security_create (0)))
log_err_exit ("security");
if (flux_security_configure (sec, sec_config) < 0)
log_err_exit ("security config %s", flux_security_last_error (sec));
sign_type = optparse_get_str (p, "sign-type", NULL);
}
#endif
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
jobspecsz = read_jobspec (input, &jobspec);
assert (((char *)jobspec)[jobspecsz] == '\0');
if (jobspecsz == 0)
log_msg_exit ("required jobspec is empty");
priority = optparse_get_int (p, "priority", FLUX_JOB_PRIORITY_DEFAULT);
#if HAVE_FLUX_SECURITY
if (sec) {
if (!(J = flux_sign_wrap (sec, jobspec, jobspecsz, sign_type, 0)))
log_err_exit ("flux_sign_wrap: %s", flux_security_last_error (sec));
flags |= FLUX_JOB_PRE_SIGNED;
}
#endif
if (!(f = flux_job_submit (h, J ? J : jobspec, priority, flags)))
log_err_exit ("flux_job_submit");
if (flux_job_submit_get_id (f, &id) < 0) {
log_msg_exit ("%s", future_strerror (f, errno));
}
printf ("%llu\n", (unsigned long long)id);
flux_future_destroy (f);
#if HAVE_FLUX_SECURITY
flux_security_destroy (sec); // invalidates J
#endif
flux_close (h);
free (jobspec);
return 0;
}
struct attach_ctx {
flux_t *h;
int exit_code;
flux_jobid_t id;
flux_future_t *eventlog_f;
flux_future_t *exec_eventlog_f;
flux_future_t *output_f;
flux_watcher_t *sigint_w;
flux_watcher_t *sigtstp_w;
struct timespec t_sigint;
flux_watcher_t *stdin_w;
zlist_t *stdin_rpcs;
bool stdin_data_sent;
optparse_t *p;
bool output_header_parsed;
int leader_rank;
double timestamp_zero;
int eventlog_watch_count;
};
void attach_completed_check (struct attach_ctx *ctx)
{
/* stop all non-eventlog watchers and destroy all lingering
* futures so we can exit the reactor */
if (!ctx->eventlog_watch_count) {
if (ctx->stdin_rpcs) {
flux_future_t *f = zlist_pop (ctx->stdin_rpcs);
while (f) {
flux_future_destroy (f);
zlist_remove (ctx->stdin_rpcs, f);
f = zlist_pop (ctx->stdin_rpcs);
}
}
flux_watcher_stop (ctx->sigint_w);
flux_watcher_stop (ctx->sigtstp_w);
flux_watcher_stop (ctx->stdin_w);
}
}
/* Print eventlog entry to 'fp'.
* Prefix and context may be NULL.
*/
void print_eventlog_entry (FILE *fp,
const char *prefix,
double timestamp,
const char *name,
json_t *context)
{
char *context_s = NULL;
if (context) {
if (!(context_s = json_dumps (context, JSON_COMPACT)))
log_err_exit ("%s: error re-encoding context", __func__);
}
fprintf (stderr, "%.3fs: %s%s%s%s%s\n",
timestamp,
prefix ? prefix : "",
prefix ? "." : "",
name,
context_s ? " " : "",
context_s ? context_s : "");
free (context_s);
}
static void handle_output_data (struct attach_ctx *ctx, json_t *context)
{
FILE *fp;
const char *stream;
const char *rank;
char *data;
int len;
if (!ctx->output_header_parsed)
log_msg_exit ("stream data read before header");
if (iodecode (context, &stream, &rank, &data, &len, NULL) < 0)
log_msg_exit ("malformed event context");
if (!strcmp (stream, "stdout"))
fp = stdout;
else
fp = stderr;
if (len > 0) {
if (optparse_hasopt (ctx->p, "label-io"))
fprintf (fp, "%s: ", rank);
fwrite (data, len, 1, fp);
}
free (data);
}
static void handle_output_redirect (struct attach_ctx *ctx, json_t *context)
{
const char *stream = NULL;
const char *rank = NULL;
const char *path = NULL;
if (!ctx->output_header_parsed)
log_msg_exit ("stream redirect read before header");
if (json_unpack (context, "{ s:s s:s s?:s }",
"stream", &stream,
"rank", &rank,
"path", &path) < 0)
log_msg_exit ("malformed redirect context");
if (!optparse_hasopt (ctx->p, "quiet"))
fprintf (stderr, "%s: %s redirected%s%s\n",
rank,
stream,
path ? " to " : "",
path ? path : "");
}
/* Level prefix strings. Nominally, output log event 'level' integers
* are Internet RFC 5424 severity levels. In the context of flux-shell,
* the first 3 levels are equivalently "fatal" errors.
*/
static const char *levelstr[] = {
"FATAL", "FATAL", "FATAL", "ERROR", " WARN", NULL, "DEBUG", "TRACE"
};
static void handle_output_log (struct attach_ctx *ctx,
double ts,
json_t *context)
{
const char *msg = NULL;
const char *file = NULL;
const char *component = NULL;
int rank = -1;
int line = -1;
int level = -1;
json_error_t err;
if (json_unpack_ex (context, &err, 0,
"{ s?i s:i s:s s?:s s?:s s?:i }",
"rank", &rank,
"level", &level,
"message", &msg,
"component", &component,
"file", &file,
"line", &line) < 0) {
log_err ("invalid log event in guest.output: %s", err.text);
return;
}
if (!optparse_hasopt (ctx->p, "quiet")) {
const char *label = levelstr [level];
fprintf (stderr, "%.3fs: flux-shell", ts - ctx->timestamp_zero);
if (rank >= 0)
fprintf (stderr, "[%d]", rank);
if (label)
fprintf (stderr, ": %s", label);
if (component)
fprintf (stderr, ": %s", component);
fprintf (stderr, ": %s\n", msg);
}
}
/* Handle an event in the guest.output eventlog.
* This is a stream of responses, one response per event, terminated with
* an ENODATA error response (or another error if something went wrong).
* The first eventlog entry is a header; remaining entries are data,
* redirect, or log messages. Print each data entry to stdout/stderr,
* with task/rank prefix if --label-io was specified. For each redirect entry, print
* information on paths to redirected locations if --quiet is not
* speciifed.
*/
void attach_output_continuation (flux_future_t *f, void *arg)
{
struct attach_ctx *ctx = arg;
const char *entry;
json_t *o;
const char *name;
double ts;
json_t *context;
if (flux_job_event_watch_get (f, &entry) < 0) {
if (errno == ENODATA)
goto done;
log_msg_exit ("flux_job_event_watch_get: %s",
future_strerror (f, errno));
}
if (!(o = eventlog_entry_decode (entry)))
log_err_exit ("eventlog_entry_decode");
if (eventlog_entry_parse (o, &ts, &name, &context) < 0)
log_err_exit ("eventlog_entry_parse");
if (!strcmp (name, "header")) {
/* Future: per-stream encoding */
ctx->output_header_parsed = true;
}
else if (!strcmp (name, "data")) {
handle_output_data (ctx, context);
}
else if (!strcmp (name, "redirect")) {
handle_output_redirect (ctx, context);
}
else if (!strcmp (name, "log")) {
handle_output_log (ctx, ts, context);
}
json_decref (o);
flux_future_reset (f);
return;
done:
flux_future_destroy (f);
ctx->output_f = NULL;
ctx->eventlog_watch_count--;
attach_completed_check (ctx);
}
void attach_cancel_continuation (flux_future_t *f, void *arg)
{
if (flux_future_get (f, NULL) < 0)
log_msg ("cancel: %s", future_strerror (f, errno));
flux_future_destroy (f);
}
/* Handle the user typing ctrl-C (SIGINT) and ctrl-Z (SIGTSTP).
* If the user types ctrl-C twice within 2s, cancel the job.
* If the user types ctrl-C then ctrl-Z within 2s, detach from the job.
*/
void attach_signal_cb (flux_reactor_t *r, flux_watcher_t *w,
int revents, void *arg)
{
struct attach_ctx *ctx = arg;
flux_future_t *f;
int signum = flux_signal_watcher_get_signum (w);
if (signum == SIGINT) {
if (monotime_since (ctx->t_sigint) > 2000) {
monotime (&ctx->t_sigint);
flux_watcher_start (ctx->sigtstp_w);
log_msg ("one more ctrl-C within 2s to cancel or ctrl-Z to detach");
}
else {
if (!(f = flux_job_cancel (ctx->h, ctx->id,
"interrupted by ctrl-C")))
log_err_exit ("flux_job_cancel");
if (flux_future_then (f, -1, attach_cancel_continuation, NULL) < 0)
log_err_exit ("flux_future_then");
}
}
else if (signum == SIGTSTP) {
if (monotime_since (ctx->t_sigint) <= 2000) {
if (ctx->eventlog_f) {
if (flux_job_event_watch_cancel (ctx->eventlog_f) < 0)
log_err_exit ("flux_job_event_watch_cancel");
}
if (ctx->exec_eventlog_f) {
if (flux_job_event_watch_cancel (ctx->exec_eventlog_f) < 0)
log_err_exit ("flux_job_event_watch_cancel");
}
if (ctx->output_f) {
if (flux_job_event_watch_cancel (ctx->output_f) < 0)
log_err_exit ("flux_job_event_watch_cancel");
}
log_msg ("detaching...");
}
else {
flux_watcher_stop (ctx->sigtstp_w);
log_msg ("one more ctrl-Z to suspend");
}
}
}
/* atexit handler
* This is a good faith attempt to restore stdin flags to what they were
* before we set O_NONBLOCK.
*/
void restore_stdin_flags (void)
{
(void)fcntl (STDIN_FILENO, F_SETFL, stdin_flags);
}
static void attach_send_shell_completion (flux_future_t *f, void *arg)
{
struct attach_ctx *ctx = arg;
/* failng to write stdin to service is (generally speaking) a
* fatal error */
if (flux_future_get (f, NULL) < 0) {
/* stdin may not be accepted for multiple reasons
* - job has completed
* - user requested stdin via file
* - stdin stream already closed due to prior pipe in
*/
if (errno == ENOSYS) {
/* Only generate an error if an attempt to send stdin failed.
*/
if (ctx->stdin_data_sent)
log_msg_exit ("stdin not accepted by job");
}
else
log_err_exit ("attach_send_shell");
}
flux_future_destroy (f);
zlist_remove (ctx->stdin_rpcs, f);
}
static int attach_send_shell (struct attach_ctx *ctx,
const void *buf,
int len,
bool eof)
{
json_t *context = NULL;
char topic[1024];
flux_future_t *f = NULL;
int saved_errno;
int rc = -1;
snprintf (topic, sizeof (topic), "shell-%ju.stdin", (uintmax_t)ctx->id);
if (!(context = ioencode ("stdin", "all", buf, len, eof)))
goto error;
if (!(f = flux_rpc_pack (ctx->h, topic, ctx->leader_rank, 0, "O", context)))
goto error;
if (flux_future_then (f, -1, attach_send_shell_completion, ctx) < 0)
goto error;
if (zlist_append (ctx->stdin_rpcs, f) < 0)
goto error;
/* f memory now in hands of attach_send_shell_completion() or ctx->stdin_rpcs */
f = NULL;
rc = 0;
error:
saved_errno = errno;
json_decref (context);
flux_future_destroy (f);
errno = saved_errno;
return rc;
}
/* Handle std input from user */
void attach_stdin_cb (flux_reactor_t *r, flux_watcher_t *w,
int revents, void *arg)
{
struct attach_ctx *ctx = arg;
flux_buffer_t *fb;
const char *ptr;
int len;
fb = flux_buffer_read_watcher_get_buffer (w);
assert (fb);
if (!(ptr = flux_buffer_read_line (fb, &len)))
log_err_exit ("flux_buffer_read_line on stdin");
if (len > 0) {
if (attach_send_shell (ctx, ptr, len, false) < 0)
log_err_exit ("attach_send_shell");
ctx->stdin_data_sent = true;
}
else {
/* possibly left over data before EOF */
if (!(ptr = flux_buffer_read (fb, -1, &len)))
log_err_exit ("flux_buffer_read on stdin");
if (len > 0) {
if (attach_send_shell (ctx, ptr, len, false) < 0)
log_err_exit ("attach_send_shell");
ctx->stdin_data_sent = true;
}
else {
if (attach_send_shell (ctx, NULL, 0, true) < 0)
log_err_exit ("attach_send_shell");
flux_watcher_stop (ctx->stdin_w);
}
}
}
/* Handle an event in the guest.exec eventlog.
* This is a stream of responses, one response per event, terminated with
* an ENODATA error response (or another error if something went wrong).
* On the shell.init event, start watching the guest.output eventlog.
* It is guaranteed to exist when guest.output is emitted.
* If --show-exec was specified, print all events on stderr.
*/
void attach_exec_event_continuation (flux_future_t *f, void *arg)
{
struct attach_ctx *ctx = arg;
const char *entry;
json_t *o;
double timestamp;
const char *name;
json_t *context;
if (flux_job_event_watch_get (f, &entry) < 0) {
if (errno == ENODATA)
goto done;
log_msg_exit ("flux_job_event_watch_get: %s",
future_strerror (f, errno));
}
if (!(o = eventlog_entry_decode (entry)))
log_err_exit ("eventlog_entry_decode");
if (eventlog_entry_parse (o, ×tamp, &name, &context) < 0)
log_err_exit ("eventlog_entry_parse");
if (!strcmp (name, "shell.init")) {
flux_watcher_t *w;
if (json_unpack (context, "{s:i}",
"leader-rank", &ctx->leader_rank) < 0)
log_err_exit ("error decoding shell.init context");
/* flux_buffer_read_watcher_create() requires O_NONBLOCK on
* stdin */
if ((stdin_flags = fcntl (STDIN_FILENO, F_GETFL)) < 0)
log_err_exit ("fcntl F_GETFL stdin");
if (atexit (restore_stdin_flags) != 0)
log_err_exit ("atexit");
if (fcntl (STDIN_FILENO, F_SETFL, stdin_flags | O_NONBLOCK) < 0)
log_err_exit ("fcntl F_SETFL stdin");
w = flux_buffer_read_watcher_create (flux_get_reactor (ctx->h),
STDIN_FILENO,
1 << 20,
attach_stdin_cb,
FLUX_WATCHER_LINE_BUFFER,
ctx);
if (!w)
log_err_exit ("flux_buffer_read_watcher_create");
if (!(ctx->stdin_rpcs = zlist_new ()))
log_err_exit ("zlist_new");
ctx->stdin_w = w;
flux_watcher_start (ctx->stdin_w);
if (!(ctx->output_f = flux_job_event_watch (ctx->h,
ctx->id,
"guest.output",
0)))
log_err_exit ("flux_job_event_watch");
if (flux_future_then (ctx->output_f,
-1.,
attach_output_continuation,
ctx) < 0)
log_err_exit ("flux_future_then");
ctx->eventlog_watch_count++;
}
if (optparse_hasopt (ctx->p, "show-exec")) {
print_eventlog_entry (stderr,
"exec",
timestamp - ctx->timestamp_zero,
name,
context);
}
json_decref (o);
flux_future_reset (f);
return;
done:
flux_future_destroy (f);
ctx->exec_eventlog_f = NULL;
ctx->eventlog_watch_count--;
attach_completed_check (ctx);
}
/* Handle an event in the main job eventlog.
* This is a stream of responses, one response per event, terminated with
* an ENODATA error response (or another error if something went wrong).
* If a fatal exception event occurs, print it on stderr.
* If --show-events was specified, print all events on stderr.
* If submit event occurs, begin watching guest.exec.eventlog.
* If finish event occurs, capture ctx->exit code.
*/
void attach_event_continuation (flux_future_t *f, void *arg)
{
struct attach_ctx *ctx = arg;
const char *entry;
json_t *o;
double timestamp;
const char *name;
json_t *context;
int status;
if (flux_job_event_watch_get (f, &entry) < 0) {
if (errno == ENODATA)
goto done;
if (errno == ENOENT)
log_msg_exit ("Failed to attach to %ju: No such job", ctx->id);
log_msg_exit ("flux_job_event_watch_get: %s",
future_strerror (f, errno));
}
if (!(o = eventlog_entry_decode (entry)))
log_err_exit ("eventlog_entry_decode");
if (eventlog_entry_parse (o, ×tamp, &name, &context) < 0)
log_err_exit ("eventlog_entry_parse");
if (ctx->timestamp_zero == 0.)
ctx->timestamp_zero = timestamp;
if (!strcmp (name, "exception")) {
const char *type;
int severity;
const char *note = NULL;
if (json_unpack (context, "{s:s s:i s?:s}",
"type", &type,
"severity", &severity,
"note", ¬e) < 0)
log_err_exit ("error decoding exception context");
fprintf (stderr, "%.3fs: job.exception type=%s severity=%d %s\n",
timestamp - ctx->timestamp_zero,
type,
severity,
note ? note : "");
}
else if (!strcmp (name, "submit")) {
if (!(ctx->exec_eventlog_f = flux_job_event_watch (ctx->h,
ctx->id,
"guest.exec.eventlog",
0)))
log_err_exit ("flux_job_event_watch");
if (flux_future_then (ctx->exec_eventlog_f,
-1,
attach_exec_event_continuation,
ctx) < 0)
log_err_exit ("flux_future_then");
ctx->eventlog_watch_count++;
}
else {
if (!strcmp (name, "finish")) {
if (json_unpack (context, "{s:i}", "status", &status) < 0)
log_err_exit ("error decoding finish context");
if (WIFSIGNALED (status)) {
ctx->exit_code = WTERMSIG (status) + 128;
log_msg ("task(s) %s", strsignal (WTERMSIG (status)));
}
else if (WIFEXITED (status)) {
ctx->exit_code = WEXITSTATUS (status);
if (ctx->exit_code != 0)
log_msg ("task(s) exited with exit code %d",
ctx->exit_code);
}
}
}
if (optparse_hasopt (ctx->p, "show-events")
&& strcmp (name, "exception") != 0) {
print_eventlog_entry (stderr,
"job",
timestamp - ctx->timestamp_zero,
name,
context);
}
json_decref (o);
flux_future_reset (f);
return;
done:
flux_future_destroy (f);
ctx->eventlog_f = NULL;
ctx->eventlog_watch_count--;
attach_completed_check (ctx);
}
int cmd_attach (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
flux_reactor_t *r;
struct attach_ctx ctx;
memset (&ctx, 0, sizeof (ctx));
ctx.exit_code = 1;
if (argc - optindex != 1) {
optparse_print_usage (p);
exit (1);
}
ctx.id = parse_arg_unsigned (argv[optindex++], "jobid");
ctx.p = p;
if (!(ctx.h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (!(r = flux_get_reactor (ctx.h)))
log_err_exit ("flux_get_reactor");
if (!(ctx.eventlog_f = flux_job_event_watch (ctx.h,
ctx.id,
"eventlog",
0)))
log_err_exit ("flux_job_event_watch");
if (flux_future_then (ctx.eventlog_f,
-1,
attach_event_continuation,
&ctx) < 0)
log_err_exit ("flux_future_then");
ctx.eventlog_watch_count++;
/* Ignore SIGTTIN, SIGTTOU.
*
* SIGTTIN is ignored to avoid flux-job attach being stopped while
* in the background. Normally, background flux-job attach doesn't
* register activity on stdin, so this is not necessary. However,
* in some cases (e.g. docker run -ti), activity on the terminal
* does seem to wakeup epoll on background processes, and ignoring
* SIGTTIN is a workaround in those cases.
* (https://github.com/flux-framework/flux-core/issues/2599)
*
* SIGTTOU is ignored so that flux-job attach can still write to
* stderr/out even when in the background on a terminal with the
* TOSTOP output mode set (also rare, but possible)
*/
signal (SIGTTIN, SIG_IGN);
signal (SIGTTOU, SIG_IGN);
ctx.sigint_w = flux_signal_watcher_create (r,
SIGINT,
attach_signal_cb,
&ctx);
ctx.sigtstp_w = flux_signal_watcher_create (r,
SIGTSTP,
attach_signal_cb,
&ctx);
if (!ctx.sigint_w || !ctx.sigtstp_w)
log_err_exit ("flux_signal_watcher_create");
flux_watcher_start (ctx.sigint_w);
if (flux_reactor_run (r, 0) < 0)
log_err_exit ("flux_reactor_run");
zlist_destroy (&(ctx.stdin_rpcs));
flux_watcher_destroy (ctx.sigint_w);
flux_watcher_destroy (ctx.sigtstp_w);
flux_watcher_destroy (ctx.stdin_w);
flux_close (ctx.h);
return ctx.exit_code;
}
void id_convert (optparse_t *p, const char *src, char *dst, int dstsz)
{
const char *from = optparse_get_str (p, "from", "dec");
const char *to = optparse_get_str (p, "to", "dec");
flux_jobid_t id;
/* src to id
*/
if (!strcmp (from, "dec")) {
id = parse_arg_unsigned (src, "input");
}
else if (!strcmp (from, "hex")) {
if (fluid_decode (src, &id, FLUID_STRING_DOTHEX) < 0)
log_msg_exit ("%s: malformed input", src);
}
else if (!strcmp (from, "kvs")) {
if (strncmp (src, "job.", 4) != 0)
log_msg_exit ("%s: missing 'job.' prefix", src);
if (fluid_decode (src + 4, &id, FLUID_STRING_DOTHEX) < 0)
log_msg_exit ("%s: malformed input", src);
}
else if (!strcmp (from, "words")) {
if (fluid_decode (src, &id, FLUID_STRING_MNEMONIC) < 0)
log_msg_exit ("%s: malformed input", src);
}
else
log_msg_exit ("Unknown from=%s", from);
/* id to dst
*/
if (!strcmp (to, "dec")) {
snprintf (dst, dstsz, "%llu", (unsigned long long)id);
}
else if (!strcmp (to, "kvs")) {
if (flux_job_kvs_key (dst, dstsz, id, NULL) < 0)
log_msg_exit ("error encoding id");
}
else if (!strcmp (to, "hex")) {
if (fluid_encode (dst, dstsz, id, FLUID_STRING_DOTHEX) < 0)
log_msg_exit ("error encoding id");
}
else if (!strcmp (to, "words")) {
if (fluid_encode (dst, dstsz, id, FLUID_STRING_MNEMONIC) < 0)
log_msg_exit ("error encoding id");
}
else
log_msg_exit ("Unknown to=%s", to);
}
char *trim_string (char *s)
{
/* trailing */
int len = strlen (s);
while (len > 1 && isspace (s[len - 1])) {
s[len - 1] = '\0';
len--;
}
/* leading */
char *p = s;
while (*p && isspace (*p))
p++;
return p;
}
int cmd_id (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
char dst[256];
if (optindex == argc) {
char src[256];
while ((fgets (src, sizeof (src), stdin))) {
id_convert (p, trim_string (src), dst, sizeof (dst));
printf ("%s\n", dst);
}
}
else {
while (optindex < argc) {
id_convert (p, argv[optindex++], dst, sizeof (dst));
printf ("%s\n", dst);
}
}
return 0;
}
static void print_job_namespace (const char *src)
{
char ns[64];
flux_jobid_t id = parse_arg_unsigned (src, "jobid");
if (flux_job_kvs_namespace (ns, sizeof (ns), id) < 0)
log_msg_exit ("error getting kvs namespace for %ju", id);
printf ("%s\n", ns);
}
int cmd_namespace (optparse_t *p, int argc, char **argv)
{
int optindex = optparse_option_index (p);
if (optindex == argc) {
char src[256];
while ((fgets (src, sizeof (src), stdin)))
print_job_namespace (trim_string (src));
}
else {
while (optindex < argc)
print_job_namespace (argv[optindex++]);
}
return 0;
}
struct entry_format {
const char *format;
const char *time_format;
double initial;
};
void entry_format_parse_options (optparse_t *p, struct entry_format *e)
{
e->format = optparse_get_str (p, "format", "text");
if (strcasecmp (e->format, "text")
&& strcasecmp (e->format, "json"))
log_msg_exit ("invalid format type");
e->time_format = optparse_get_str (p, "time-format", "raw");
if (strcasecmp (e->time_format, "raw")
&& strcasecmp (e->time_format, "iso")
&& strcasecmp (e->time_format, "offset"))
log_msg_exit ("invalid time-format type");
}
struct eventlog_ctx {
optparse_t *p;
flux_jobid_t id;
const char *path;
struct entry_format e;
};
/* convert floating point timestamp (UNIX epoch, UTC) to ISO 8601 string,
* with microsecond precision
*/
static int event_timestr (struct entry_format *e, double timestamp,
char *buf, size_t size)
{
if (!strcasecmp (e->time_format, "raw")) {
if (snprintf (buf, size, "%lf", timestamp) >= size)
return -1;
}
else if (!strcasecmp (e->time_format, "iso")) {
time_t sec = timestamp;
unsigned long usec = (timestamp - sec)*1E6;
struct tm tm;
if (!gmtime_r (&sec, &tm))
return -1;
if (strftime (buf, size, "%FT%T", &tm) == 0)
return -1;
size -= strlen (buf);
buf += strlen (buf);
if (snprintf (buf, size, ".%.6luZ", usec) >= size)
return -1;
}
else { /* !strcasecmp (e->time_format, "offset") */
if (e->initial == 0.)
e->initial = timestamp;
timestamp -= e->initial;
if (snprintf (buf, size, "%lf", timestamp) >= size)
return -1;
}
return 0;
}
void output_event_text (struct entry_format *e, json_t *event)
{
double timestamp;
const char *name;
json_t *context = NULL;
char buf[128];
if (eventlog_entry_parse (event, ×tamp, &name, &context) < 0)
log_err_exit ("eventlog_entry_parse");
if (event_timestr (e, timestamp, buf, sizeof (buf)) < 0)
log_msg_exit ("error converting timestamp to ISO 8601");
printf ("%s %s", buf, name);
if (context) {
const char *key;
json_t *value;
json_object_foreach (context, key, value) {
char *sval;
sval = json_dumps (value, JSON_ENCODE_ANY|JSON_COMPACT);
printf (" %s=%s", key, sval);
free (sval);
}
}
printf ("\n");
fflush (stdout);
}
void output_event_json (json_t *event)
{
char *e;
if (!(e = json_dumps (event, JSON_COMPACT)))
log_msg_exit ("json_dumps");
printf ("%s\n", e);
free (e);
}
void output_event (struct entry_format *e, json_t *event)
{
if (!strcasecmp (e->format, "text"))
output_event_text (e, event);
else /* !strcasecmp (e->format, "json") */
output_event_json (event);
}
void eventlog_continuation (flux_future_t *f, void *arg)
{
struct eventlog_ctx *ctx = arg;
const char *s;
json_t *a = NULL;
size_t index;
json_t *value;
if (flux_rpc_get_unpack (f, "{s:s}", ctx->path, &s) < 0) {
if (errno == ENOENT) {
flux_future_destroy (f);
if (!strcmp (ctx->path, "eventlog"))
log_msg_exit ("job %lu not found", ctx->id);
else
log_msg_exit ("eventlog path %s not found", ctx->path);
}
else
log_err_exit ("flux_job_eventlog_lookup_get");
}
if (!(a = eventlog_decode (s)))
log_err_exit ("eventlog_decode");
json_array_foreach (a, index, value) {
output_event (&ctx->e, value);
}
fflush (stdout);
json_decref (a);
flux_future_destroy (f);
}
int cmd_eventlog (optparse_t *p, int argc, char **argv)
{
flux_t *h;
int optindex = optparse_option_index (p);
flux_future_t *f;
const char *topic = "job-info.lookup";
struct eventlog_ctx ctx = {0};
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (argc - optindex != 1) {
optparse_print_usage (p);
exit (1);
}
ctx.id = parse_arg_unsigned (argv[optindex++], "jobid");
ctx.path = optparse_get_str (p, "path", "eventlog");
ctx.p = p;
entry_format_parse_options (p, &ctx.e);
if (!(f = flux_rpc_pack (h, topic, FLUX_NODEID_ANY, 0,
"{s:I s:[s] s:i}",
"id", ctx.id,
"keys", ctx.path,
"flags", 0)))
log_err_exit ("flux_rpc_pack");
if (flux_future_then (f, -1., eventlog_continuation, &ctx) < 0)
log_err_exit ("flux_future_then");
if (flux_reactor_run (flux_get_reactor (h), 0) < 0)
log_err_exit ("flux_reactor_run");
flux_close (h);
return (0);
}
struct wait_event_ctx {
optparse_t *p;
const char *wait_event;
double timeout;
flux_jobid_t id;
const char *path;
bool got_event;
struct entry_format e;
char *context_key;
char *context_value;
};
bool wait_event_test_context (struct wait_event_ctx *ctx, json_t *context)
{
void *iter;
bool match = false;
iter = json_object_iter (context);
while (iter && !match) {
const char *key = json_object_iter_key (iter);
json_t *value = json_object_iter_value (iter);
if (!strcmp (key, ctx->context_key)) {
char *str = json_dumps (value, JSON_ENCODE_ANY|JSON_COMPACT);
if (!strcmp (str, ctx->context_value))
match = true;
free (str);
}
/* special case, json_dumps() will put quotes around string
* values. Consider the case when user does not surround
* string value with quotes */
if (!match && json_is_string (value)) {
const char *str = json_string_value (value);
if (!strcmp (str, ctx->context_value))
match = true;
}
iter = json_object_iter_next (context, iter);
}
return match;
}
bool wait_event_test (struct wait_event_ctx *ctx, json_t *event)
{
double timestamp;
const char *name;
json_t *context = NULL;
bool match = false;
if (eventlog_entry_parse (event, ×tamp, &name, &context) < 0)
log_err_exit ("eventlog_entry_parse");
if (ctx->e.initial == 0.)
ctx->e.initial = timestamp;
if (!strcmp (name, ctx->wait_event)) {
if (ctx->context_key) {
if (context)
match = wait_event_test_context (ctx, context);
}
else
match = true;
}
return match;
}
void wait_event_continuation (flux_future_t *f, void *arg)
{
struct wait_event_ctx *ctx = arg;
json_t *o = NULL;
const char *event;
if (flux_rpc_get (f, NULL) < 0) {
if (errno == ENOENT) {
flux_future_destroy (f);
if (!strcmp (ctx->path, "eventlog"))
log_msg_exit ("job %lu not found", ctx->id);
else
log_msg_exit ("eventlog path %s not found", ctx->path);
}
else if (errno == ETIMEDOUT) {
flux_future_destroy (f);
log_msg_exit ("wait-event timeout on event '%s'\n",
ctx->wait_event);
} else if (errno == ENODATA) {
flux_future_destroy (f);
if (!ctx->got_event)
log_msg_exit ("event '%s' never received",
ctx->wait_event);
return;
}
/* else fallthrough and have `flux_job_event_watch_get'
* handle error */
}
if (flux_job_event_watch_get (f, &event) < 0)
log_err_exit ("flux_job_event_watch_get");
if (!(o = eventlog_entry_decode (event)))
log_err_exit ("eventlog_entry_decode");
if (wait_event_test (ctx, o)) {
ctx->got_event = true;
if (!optparse_hasopt (ctx->p, "quiet"))
output_event (&ctx->e, o);
if (flux_job_event_watch_cancel (f) < 0)
log_err_exit ("flux_job_event_watch_cancel");
} else if (optparse_hasopt (ctx->p, "verbose")) {
if (!ctx->got_event)
output_event (&ctx->e, o);
}
json_decref (o);
flux_future_reset (f);
/* re-call to set timeout */
if (flux_future_then (f, ctx->timeout, wait_event_continuation, arg) < 0)
log_err_exit ("flux_future_then");
}
int cmd_wait_event (optparse_t *p, int argc, char **argv)
{
flux_t *h;
int optindex = optparse_option_index (p);
flux_future_t *f;
struct wait_event_ctx ctx = {0};
const char *str;
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if ((argc - optindex) != 2) {
optparse_print_usage (p);
exit (1);
}
ctx.id = parse_arg_unsigned (argv[optindex++], "jobid");
ctx.p = p;
ctx.wait_event = argv[optindex++];
ctx.timeout = optparse_get_duration (p, "timeout", -1.0);
ctx.path = optparse_get_str (p, "path", "eventlog");
entry_format_parse_options (p, &ctx.e);
if ((str = optparse_get_str (p, "match-context", NULL))) {
ctx.context_key = xstrdup (str);
ctx.context_value = strchr (ctx.context_key, '=');
if (!ctx.context_value)
log_msg_exit ("must specify a context test as key=value");
*ctx.context_value++ = '\0';
}
if (!(f = flux_job_event_watch (h, ctx.id, ctx.path, 0)))
log_err_exit ("flux_job_event_watch");
if (flux_future_then (f, ctx.timeout, wait_event_continuation, &ctx) < 0)
log_err_exit ("flux_future_then");
if (flux_reactor_run (flux_get_reactor (h), 0) < 0)
log_err_exit ("flux_reactor_run");
free (ctx.context_key);
flux_close (h);
return (0);
}
struct info_ctx {
flux_jobid_t id;
json_t *keys;
};
void info_output (flux_future_t *f, const char *suffix, flux_jobid_t id)
{
const char *s;
if (flux_rpc_get_unpack (f, "{s:s}", suffix, &s) < 0) {
if (errno == ENOENT) {
flux_future_destroy (f);
log_msg_exit ("job %lu id or key not found", id);
}
else
log_err_exit ("flux_rpc_get_unpack");
}
/* XXX - prettier output later */
printf ("%s\n", s);
}
void info_continuation (flux_future_t *f, void *arg)
{
struct info_ctx *ctx = arg;
size_t index;
json_t *key;
json_array_foreach (ctx->keys, index, key) {
const char *s = json_string_value (key);
info_output (f, s, ctx->id);
}
flux_future_destroy (f);
}
int cmd_info (optparse_t *p, int argc, char **argv)
{
flux_t *h;
int optindex = optparse_option_index (p);
flux_future_t *f;
const char *topic = "job-info.lookup";
struct info_ctx ctx = {0};
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if ((argc - optindex) < 2) {
optparse_print_usage (p);
exit (1);
}
ctx.id = parse_arg_unsigned (argv[optindex++], "jobid");
if (!(ctx.keys = json_array ()))
log_msg_exit ("json_array");
while (optindex < argc) {
json_t *s;
if (!(s = json_string (argv[optindex])))
log_msg_exit ("json_string");
if (json_array_append_new (ctx.keys, s) < 0)
log_msg_exit ("json_array_append");
optindex++;
}
if (!(f = flux_rpc_pack (h, topic, FLUX_NODEID_ANY, 0,
"{s:I s:O s:i}",
"id", ctx.id,
"keys", ctx.keys,
"flags", 0)))
log_err_exit ("flux_rpc_pack");
if (flux_future_then (f, -1., info_continuation, &ctx) < 0)
log_err_exit ("flux_future_then");
if (flux_reactor_run (flux_get_reactor (h), 0) < 0)
log_err_exit ("flux_reactor_run");
json_decref (ctx.keys);
flux_close (h);
return (0);
}
int cmd_stats (optparse_t *p, int argc, char **argv)
{
flux_t *h;
flux_future_t *f;
const char *topic = "job-info.job-stats";
const char *s;
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (!(f = flux_rpc (h, topic, NULL, FLUX_NODEID_ANY, 0)))
log_err_exit ("flux_rpc");
if (flux_rpc_get (f, &s) < 0)
log_msg_exit ("stats: %s", future_strerror (f, errno));
/* for time being, just output json object for result */
printf ("%s\n", s);
flux_close (h);
return (0);
}
int cmd_drain (optparse_t *p, int argc, char **argv)
{
flux_t *h;
int optindex = optparse_option_index (p);
double timeout = optparse_get_duration (p, "timeout", -1.);
flux_future_t *f;
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (argc - optindex != 0) {
optparse_print_usage (p);
exit (1);
}
if (!(f = flux_rpc (h, "job-manager.drain", NULL, FLUX_NODEID_ANY, 0)))
log_err_exit ("flux_rpc");
if (flux_future_wait_for (f, timeout) < 0 || flux_rpc_get (f, NULL) < 0)
log_msg_exit ("drain: %s", errno == ETIMEDOUT
? "timeout" : future_strerror (f, errno));
flux_future_destroy (f);
flux_close (h);
return (0);
}
int cmd_wait (optparse_t *p, int argc, char **argv)
{
flux_t *h;
int optindex = optparse_option_index (p);
flux_future_t *f;
flux_jobid_t id = FLUX_JOBID_ANY;
bool success;
const char *errstr;
if ((argc - optindex) > 1) {
optparse_print_usage (p);
exit (1);
}
if (!(h = flux_open (NULL, 0)))
log_err_exit ("flux_open");
if (optindex < argc)
id = parse_arg_unsigned (argv[optindex++], "jobid");
if (!(f = flux_job_wait (h, id)))
log_err_exit ("flux_job_wait");
if (flux_job_wait_get_status (f, &success, &errstr) < 0)
log_msg_exit ("%s", flux_future_error_string (f));
if (id == FLUX_JOBID_ANY) {
if (flux_job_wait_get_id (f, &id) < 0)
log_err_exit ("flux_job_wait_get_id");
printf ("%ju\n", (uintmax_t)id);
}
if (!success)
log_msg_exit ("%s", errstr);
flux_future_destroy (f);
flux_close (h);
return (0);
}
/*
* vi:tabstop=4 shiftwidth=4 expandtab
*/
| 1 | 25,942 | commit message, "currently ignored"? (-ed) | flux-framework-flux-core | c |
@@ -37,6 +37,12 @@ module Selenium
def bridge_class
Bridge
end
+
+ def print_page(**options)
+ options[:page_ranges] &&= Array(options[:page_ranges])
+
+ bridge.print_page(options)
+ end
end # Driver
end # Firefox
end # WebDriver | 1 | # frozen_string_literal: true
# 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.
module Selenium
module WebDriver
module Firefox
#
# Driver implementation for Firefox using GeckoDriver.
# @api private
#
class Driver < WebDriver::Driver
include DriverExtensions::HasAddons
include DriverExtensions::HasWebStorage
def browser
:firefox
end
def bridge_class
Bridge
end
end # Driver
end # Firefox
end # WebDriver
end # Selenium
| 1 | 18,368 | Same here. and all others. | SeleniumHQ-selenium | py |
@@ -25,14 +25,16 @@ namespace Nethermind.Blockchain
public class OneTimeChainProcessor : IBlockchainProcessor
{
private readonly IBlockchainProcessor _processor;
+ private readonly IBlockchainProcessor _mainChainProcessor;
private readonly IReadOnlyDbProvider _readOnlyDbProvider;
private object _lock = new object();
- public OneTimeChainProcessor(IReadOnlyDbProvider readOnlyDbProvider, IBlockchainProcessor processor)
+ public OneTimeChainProcessor(IReadOnlyDbProvider readOnlyDbProvider, IBlockchainProcessor processor, IBlockchainProcessor mainChainProcessor = null)
{
_readOnlyDbProvider = readOnlyDbProvider ?? throw new ArgumentNullException(nameof(readOnlyDbProvider));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
+ _mainChainProcessor = mainChainProcessor;
}
public void Start() | 1 | // Copyright (c) 2018 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Threading.Tasks;
using Nethermind.Core;
using Nethermind.Evm.Tracing;
using Nethermind.Store;
namespace Nethermind.Blockchain
{
public class OneTimeChainProcessor : IBlockchainProcessor
{
private readonly IBlockchainProcessor _processor;
private readonly IReadOnlyDbProvider _readOnlyDbProvider;
private object _lock = new object();
public OneTimeChainProcessor(IReadOnlyDbProvider readOnlyDbProvider, IBlockchainProcessor processor)
{
_readOnlyDbProvider = readOnlyDbProvider ?? throw new ArgumentNullException(nameof(readOnlyDbProvider));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
}
public void Start()
{
_processor.Start();
}
public Task StopAsync(bool processRemainingBlocks = false)
{
return _processor.StopAsync(processRemainingBlocks);
}
public Block Process(Block block, ProcessingOptions options, IBlockTracer listener)
{
lock (_lock)
{
Block result = _processor.Process(block, options, listener);
_readOnlyDbProvider.ClearTempChanges();
return result;
}
}
public event EventHandler ProcessingQueueEmpty
{
add { }
remove { }
}
}
} | 1 | 23,055 | can we pass some simple interface instead of a full additional processor? (an imterface with these two events only) | NethermindEth-nethermind | .cs |
@@ -107,6 +107,8 @@ insert_exit_stub_other_flags(dcontext_t *dcontext, fragment_t *f,
/* FIXME i#1575: coarse-grain NYI on ARM */
ASSERT_NOT_IMPLEMENTED(!TEST(FRAG_COARSE_GRAIN, f->flags));
if (LINKSTUB_DIRECT(l_flags)) {
+ /* We put a NOP here for future linking. */
+ *pc++ = 0xd503201f;
/* stp x0, x1, [x(stolen), #(offs)] */
*pc++ = (0xa9000000 | 0 | 1 << 10 | (dr_reg_stolen - DR_REG_X0) << 5 |
TLS_REG0_SLOT >> 3 << 15); | 1 | /* **********************************************************
* Copyright (c) 2014-2017 Google, Inc. All rights reserved.
* Copyright (c) 2016 ARM Limited. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of ARM Limited 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 ARM LIMITED OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include "../globals.h"
#include "arch.h"
#include "instr.h"
#include "instr_create.h"
#include "instrlist.h"
#include "instrument.h"
/* shorten code generation lines */
#define APP instrlist_meta_append
#define PRE instrlist_meta_preinsert
#define OPREG opnd_create_reg
/***************************************************************************/
/* EXIT STUB */
/***************************************************************************/
byte *
insert_relative_target(byte *pc, cache_pc target, bool hot_patch)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return NULL;
}
byte *
insert_relative_jump(byte *pc, cache_pc target, bool hot_patch)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return NULL;
}
uint
nop_pad_ilist(dcontext_t *dcontext, fragment_t *f, instrlist_t *ilist, bool emitting)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return 0;
}
size_t
get_fcache_return_tls_offs(dcontext_t *dcontext, uint flags)
{
/* AArch64 always uses shared gencode so we ignore FRAG_DB_SHARED(flags) */
if (TEST(FRAG_COARSE_GRAIN, flags)) {
/* FIXME i#1575: coarse-grain NYI on AArch64 */
ASSERT_NOT_IMPLEMENTED(false);
return 0;
}
return TLS_FCACHE_RETURN_SLOT;
}
/* Generate move (immediate) of a 64-bit value using 4 instructions. */
static uint *
insert_mov_imm(uint *pc, reg_id_t dst, ptr_int_t val)
{
uint rt = dst - DR_REG_X0;
ASSERT(rt < 31);
*pc++ = 0xd2800000 | rt | (val & 0xffff) << 5; /* mov x(rt), #x */
*pc++ = 0xf2a00000 | rt | (val >> 16 & 0xffff) << 5; /* movk x(rt), #x, lsl #16 */
*pc++ = 0xf2c00000 | rt | (val >> 32 & 0xffff) << 5; /* movk x(rt), #x, lsl #32 */
*pc++ = 0xf2e00000 | rt | (val >> 48 & 0xffff) << 5; /* movk x(rt), #x, lsl #48 */
return pc;
}
/* Emit code for the exit stub at stub_pc. Return the size of the
* emitted code in bytes. This routine assumes that the caller will
* take care of any cache synchronization necessary.
* The stub is unlinked initially, except coarse grain indirect exits,
* which are always linked.
*/
int
insert_exit_stub_other_flags(dcontext_t *dcontext, fragment_t *f,
linkstub_t *l, cache_pc stub_pc, ushort l_flags)
{
uint *pc = (uint *)stub_pc;
/* FIXME i#1575: coarse-grain NYI on ARM */
ASSERT_NOT_IMPLEMENTED(!TEST(FRAG_COARSE_GRAIN, f->flags));
if (LINKSTUB_DIRECT(l_flags)) {
/* stp x0, x1, [x(stolen), #(offs)] */
*pc++ = (0xa9000000 | 0 | 1 << 10 | (dr_reg_stolen - DR_REG_X0) << 5 |
TLS_REG0_SLOT >> 3 << 15);
/* mov x0, ... */
pc = insert_mov_imm(pc, DR_REG_X0, (ptr_int_t)l);
/* ldr x1, [x(stolen), #(offs)] */
*pc++ = (0xf9400000 | 1 | (dr_reg_stolen - DR_REG_X0) << 5 |
get_fcache_return_tls_offs(dcontext, f->flags) >>
3 << 10);
/* br x1 */
*pc++ = 0xd61f0000 | 1 << 5;
} else {
/* Stub starts out unlinked. */
cache_pc exit_target = get_unlinked_entry(dcontext,
EXIT_TARGET_TAG(dcontext, f, l));
/* stp x0, x1, [x(stolen), #(offs)] */
*pc++ = (0xa9000000 | 0 | 1 << 10 | (dr_reg_stolen - DR_REG_X0) << 5 |
TLS_REG0_SLOT >> 3 << 15);
/* mov x0, ... */
pc = insert_mov_imm(pc, DR_REG_X0, (ptr_int_t)l);
/* ldr x1, [x(stolen), #(offs)] */
*pc++ = (0xf9400000 | 1 | (dr_reg_stolen - DR_REG_X0) << 5 |
get_ibl_entry_tls_offs(dcontext, exit_target) >> 3 << 10);
/* br x1 */
*pc++ = 0xd61f0000 | 1 << 5;
}
ASSERT((ptr_int_t)((byte *)pc - (byte *)stub_pc) ==
DIRECT_EXIT_STUB_SIZE(l_flags));
return (int)((byte *)pc - (byte *)stub_pc);
}
bool
exit_cti_reaches_target(dcontext_t *dcontext, fragment_t *f,
linkstub_t *l, cache_pc target_pc)
{
cache_pc branch_pc = EXIT_CTI_PC(f, l);
/* Compute offset as unsigned, modulo arithmetic. */
ptr_uint_t off = (ptr_uint_t)target_pc - (ptr_uint_t)branch_pc;
uint enc = *(uint *)branch_pc;
ASSERT(ALIGNED(branch_pc, 4) && ALIGNED(target_pc, 4));
if ((enc & 0xfc000000) == 0x14000000) /* B (OP_b)*/
return (off + 0x8000000 < 0x10000000);
else if ((enc & 0xff000010) == 0x54000000 ||
(enc & 0x7e000000) == 0x34000000) /* B.cond, CBNZ, CBZ */
return (off + 0x40000 < 0x80000);
else if ((enc & 0x7e000000) == 0x36000000) /* TBNZ, TBZ */
return (off + 0x2000 < 0x4000);
ASSERT(false);
return false;
}
void
patch_stub(fragment_t *f, cache_pc stub_pc, cache_pc target_pc, bool hot_patch)
{
/* Compute offset as unsigned, modulo arithmetic. */
ptr_uint_t off = (ptr_uint_t)target_pc - (ptr_uint_t)stub_pc;
if (off + 0x8000000 < 0x10000000) {
/* We can get there with a B (OP_b, 26-bit signed immediate offset). */
*(uint *)stub_pc = (0x14000000 | (0x03ffffff & off >> 2));
if (hot_patch)
machine_cache_sync(stub_pc, stub_pc + 4, true);
return;
}
/* We must use an indirect branch. */
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
}
bool
stub_is_patched(fragment_t *f, cache_pc stub_pc)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return false;
}
void
unpatch_stub(fragment_t *f, cache_pc stub_pc, bool hot_patch)
{
/* Restore the stp x0, x1, [x28] instruction. */
*(uint *)stub_pc = (0xa9000000 | 0 | 1 << 10 | (dr_reg_stolen - DR_REG_X0) << 5 |
TLS_REG0_SLOT >> 3 << 15);
if (hot_patch)
machine_cache_sync(stub_pc, stub_pc + AARCH64_INSTR_SIZE, true);
}
void
patch_branch(dr_isa_mode_t isa_mode, cache_pc branch_pc, cache_pc target_pc,
bool hot_patch)
{
/* Compute offset as unsigned, modulo arithmetic. */
ptr_uint_t off = (ptr_uint_t)target_pc - (ptr_uint_t)branch_pc;
uint *p = (uint *)branch_pc;
uint enc = *p;
ASSERT(ALIGNED(branch_pc, 4) && ALIGNED(target_pc, 4));
if ((enc & 0xfc000000) == 0x14000000) { /* B */
ASSERT(off + 0x8000000 < 0x10000000);
*p = (0x14000000 | (0x03ffffff & off >> 2));
}
else if ((enc & 0xff000010) == 0x54000000 ||
(enc & 0x7e000000) == 0x34000000) { /* B.cond, CBNZ, CBZ */
ASSERT(off + 0x40000 < 0x80000);
*p = (enc & 0xff00001f) | (0x00ffffe0 & off >> 2 << 5);
}
else if ((enc & 0x7e000000) == 0x36000000) { /* TBNZ, TBZ */
ASSERT(off + 0x2000 < 0x4000);
*p = (enc & 0xfff8001f) | (0x0007ffe0 & off >> 2 << 5);
}
else
ASSERT(false);
if (hot_patch)
machine_cache_sync(branch_pc, branch_pc + 4, true);
return;
}
uint
patchable_exit_cti_align_offs(dcontext_t *dcontext, instr_t *inst, cache_pc pc)
{
return 0; /* always aligned */
}
cache_pc
exit_cti_disp_pc(cache_pc branch_pc)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return NULL;
}
void
link_indirect_exit_arch(dcontext_t *dcontext, fragment_t *f,
linkstub_t *l, bool hot_patch,
app_pc target_tag)
{
byte *stub_pc = (byte *)EXIT_STUB_PC(dcontext, f, l);
uint *pc;
cache_pc exit_target;
ibl_type_t ibl_type = {0};
DEBUG_DECLARE(bool is_ibl = )
get_ibl_routine_type_ex(dcontext, target_tag, &ibl_type);
ASSERT(is_ibl);
if (IS_IBL_LINKED(ibl_type.link_state))
exit_target = target_tag;
else
exit_target = get_linked_entry(dcontext, target_tag);
pc = (uint *)(stub_pc + exit_stub_size(dcontext, target_tag, f->flags) -
(2 * AARCH64_INSTR_SIZE));
/* ldr x1, [x(stolen), #(offs)] */
pc[0] = (0xf9400000 | 1 | (dr_reg_stolen - DR_REG_X0) << 5 |
get_ibl_entry_tls_offs(dcontext, exit_target) >> 3 << 10);
/* br x1 */
pc[1] = 0xd61f0000 | 1 << 5;
if (hot_patch)
machine_cache_sync(pc, pc + 2, true);
}
cache_pc
indirect_linkstub_stub_pc(dcontext_t *dcontext, fragment_t *f, linkstub_t *l)
{
cache_pc cti = EXIT_CTI_PC(f, l);
if (!EXIT_HAS_STUB(l->flags, f->flags))
return NULL;
ASSERT(decode_raw_is_jmp(dcontext, cti));
return decode_raw_jmp_target(dcontext, cti);
}
cache_pc
cbr_fallthrough_exit_cti(cache_pc prev_cti_pc)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return NULL;
}
void
unlink_indirect_exit(dcontext_t *dcontext, fragment_t *f, linkstub_t *l)
{
byte *stub_pc = (byte *)EXIT_STUB_PC(dcontext, f, l);
uint *pc;
cache_pc exit_target;
ibl_code_t *ibl_code = NULL;
ASSERT(linkstub_owned_by_fragment(dcontext, f, l));
ASSERT(LINKSTUB_INDIRECT(l->flags));
/* Target is always the same, so if it's already unlinked, this is a nop. */
if (!TEST(LINK_LINKED, l->flags))
return;
ibl_code = get_ibl_routine_code(dcontext,
extract_branchtype(l->flags), f->flags);
exit_target = ibl_code->unlinked_ibl_entry;
pc = (uint *)(stub_pc +
exit_stub_size(dcontext, ibl_code->indirect_branch_lookup_routine,
f->flags) - (2 * AARCH64_INSTR_SIZE));
/* ldr x1, [x(stolen), #(offs)] */
*pc = (0xf9400000 | 1 | (dr_reg_stolen - DR_REG_X0) << 5 |
get_ibl_entry_tls_offs(dcontext, exit_target) >> 3 << 10);
machine_cache_sync(pc, pc + 1, true);
}
/*******************************************************************************
* COARSE-GRAIN FRAGMENT SUPPORT
*/
cache_pc
entrance_stub_jmp(cache_pc stub)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return NULL;
}
bool
coarse_is_entrance_stub(cache_pc stub)
{
/* FIXME i#1575: coarse-grain NYI on AArch64 */
return false;
}
/*###########################################################################
*
* fragment_t Prefixes
*/
int
fragment_ibt_prefix_size(uint flags)
{
/* Nothing extra for ibt as we don't have flags to restore */
return FRAGMENT_BASE_PREFIX_SIZE(flags);
}
void
insert_fragment_prefix(dcontext_t *dcontext, fragment_t *f)
{
/* Always use prefix on AArch64 as there is no load to PC. */
byte *pc = (byte *)f->start_pc;
ASSERT(f->prefix_size == 0);
/* ldr x0, [x(stolen), #(off)] */
*(uint *)pc = (0xf9400000 | (ENTRY_PC_REG - DR_REG_X0) |
(dr_reg_stolen - DR_REG_X0) << 5 |
ENTRY_PC_SPILL_SLOT >> 3 << 10);
pc += 4;
f->prefix_size = (byte)(((cache_pc)pc) - f->start_pc);
ASSERT(f->prefix_size == fragment_prefix_size(f->flags));
}
/***************************************************************************/
/* THREAD-PRIVATE/SHARED ROUTINE GENERATION */
/***************************************************************************/
/* Load DR's TLS base to dr_reg_stolen via reg_base. */
static void
insert_load_dr_tls_base(dcontext_t *dcontext, instrlist_t *ilist, instr_t *where,
reg_id_t reg_base)
{
/* Load TLS base from user-mode thread pointer/ID register:
* mrs reg_base, tpidr_el0
*/
PRE(ilist, where, INSTR_CREATE_mrs(dcontext, opnd_create_reg(reg_base),
opnd_create_reg(DR_REG_TPIDR_EL0)));
/* ldr dr_reg_stolen, [reg_base, DR_TLS_BASE_OFFSET] */
PRE(ilist, where,
XINST_CREATE_load(dcontext, opnd_create_reg(dr_reg_stolen),
OPND_CREATE_MEMPTR(reg_base, DR_TLS_BASE_OFFSET)));
}
/* Having only one thread register (TPIDR_EL0) shared between app and DR,
* we steal a register for DR's TLS base in the code cache, and store
* DR's TLS base into an private lib's TLS slot for accessing in C code.
* On entering the code cache (fcache_enter):
* - grab gen routine's parameter dcontext and put it into REG_DCXT
* - load DR's TLS base into dr_reg_stolen from privlib's TLS
*/
void
append_fcache_enter_prologue(dcontext_t *dcontext, instrlist_t *ilist, bool absolute)
{
ASSERT_NOT_IMPLEMENTED(!absolute &&
!TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask));
/* Grab gen routine's parameter dcontext and put it into REG_DCXT:
* mov x(dxct), x0
*/
APP(ilist, XINST_CREATE_move(dcontext, opnd_create_reg(REG_DCXT),
opnd_create_reg(DR_REG_X0)));
/* FIXME i#2019: check dcontext->signals_pending. First we need a way to
* create a conditional branch b.le.
*/
/* set up stolen reg */
insert_load_dr_tls_base(dcontext, ilist, NULL/*append*/, SCRATCH_REG0);
}
void
append_call_exit_dr_hook(dcontext_t *dcontext, instrlist_t *ilist,
bool absolute, bool shared)
{
/* i#1569: DR_HOOK is not supported on AArch64 */
ASSERT_NOT_IMPLEMENTED(EXIT_DR_HOOK == NULL);
}
void
append_restore_xflags(dcontext_t *dcontext, instrlist_t *ilist, bool absolute)
{
APP(ilist, RESTORE_FROM_DC(dcontext, DR_REG_W0, XFLAGS_OFFSET));
APP(ilist, RESTORE_FROM_DC(dcontext, DR_REG_W1, XFLAGS_OFFSET + 4));
APP(ilist, RESTORE_FROM_DC(dcontext, DR_REG_W2, XFLAGS_OFFSET + 8));
APP(ilist, INSTR_CREATE_msr(dcontext, opnd_create_reg(DR_REG_NZCV),
opnd_create_reg(DR_REG_X0)));
APP(ilist, INSTR_CREATE_msr(dcontext, opnd_create_reg(DR_REG_FPCR),
opnd_create_reg(DR_REG_X1)));
APP(ilist, INSTR_CREATE_msr(dcontext, opnd_create_reg(DR_REG_FPSR),
opnd_create_reg(DR_REG_X2)));
}
/* dcontext is in REG_DCXT; other registers can be used as scratch.
*/
void
append_restore_simd_reg(dcontext_t *dcontext, instrlist_t *ilist, bool absolute)
{
int i;
/* add x1, x(dcxt), #(off) */
APP(ilist,
XINST_CREATE_add_2src(dcontext, opnd_create_reg(DR_REG_X1),
opnd_create_reg(REG_DCXT),
OPND_CREATE_INTPTR(offsetof(priv_mcontext_t, simd))));
for (i = 0; i < 32; i += 2) {
/* ldp q(i), q(i + 1), [x1, #(i * 16)] */
APP(ilist, INSTR_CREATE_ldp(dcontext,
opnd_create_reg(DR_REG_Q0 + i),
opnd_create_reg(DR_REG_Q0 + i + 1),
opnd_create_base_disp(DR_REG_X1, DR_REG_NULL, 0,
i * 16, OPSZ_32)));
}
}
/* Append instructions to restore gpr on fcache enter, to be executed
* right before jump to fcache target.
* - dcontext is in REG_DCXT
* - DR's tls base is in dr_reg_stolen
* - all other registers can be used as scratch, and we are using X0.
*/
void
append_restore_gpr(dcontext_t *dcontext, instrlist_t *ilist, bool absolute)
{
int i;
/* FIXME i#1573: NYI on ARM with SELFPROT_DCONTEXT */
ASSERT_NOT_IMPLEMENTED(!TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask));
ASSERT(dr_reg_stolen != SCRATCH_REG0);
/* Store stolen reg value into TLS slot. */
APP(ilist, RESTORE_FROM_DC(dcontext, SCRATCH_REG0, REG_OFFSET(dr_reg_stolen)));
APP(ilist, SAVE_TO_TLS(dcontext, SCRATCH_REG0, TLS_REG_STOLEN_SLOT));
/* Save DR's tls base into mcontext. */
APP(ilist, SAVE_TO_DC(dcontext, dr_reg_stolen, REG_OFFSET(dr_reg_stolen)));
i = (REG_DCXT == DR_REG_X0);
/* ldp x30, x(i), [x(dcxt), #x30_offset] */
APP(ilist, INSTR_CREATE_ldp(dcontext,
opnd_create_reg(DR_REG_X30),
opnd_create_reg(DR_REG_X0 + i),
opnd_create_base_disp(REG_DCXT, DR_REG_NULL, 0,
REG_OFFSET(DR_REG_X30), OPSZ_16)));
/* mov sp, x(i) */
APP(ilist, XINST_CREATE_move(dcontext, opnd_create_reg(DR_REG_SP),
opnd_create_reg(DR_REG_X0 + i)));
for (i = 0; i < 30; i += 2) {
if ((REG_DCXT - DR_REG_X0) >> 1 != i >> 1) {
/* ldp x(i), x(i+1), [x(dcxt), #xi_offset] */
APP(ilist, INSTR_CREATE_ldp(dcontext,
opnd_create_reg(DR_REG_X0 + i),
opnd_create_reg(DR_REG_X0 + i + 1),
opnd_create_base_disp(REG_DCXT, DR_REG_NULL, 0,
REG_OFFSET(DR_REG_X0 + i),
OPSZ_16)));
}
}
i = (REG_DCXT - DR_REG_X0) & ~1;
/* ldp x(i), x(i+1), [x(dcxt), #xi_offset] */
APP(ilist, INSTR_CREATE_ldp(dcontext,
opnd_create_reg(DR_REG_X0 + i),
opnd_create_reg(DR_REG_X0 + i + 1),
opnd_create_base_disp(REG_DCXT, DR_REG_NULL, 0,
REG_OFFSET(DR_REG_X0 + i),
OPSZ_16)));
}
/* Append instructions to save gpr on fcache return, called after
* append_fcache_return_prologue.
* Assuming the execution comes from an exit stub via br DR_REG_X1,
* dcontext base is held in REG_DCXT, and exit stub in X0.
* App's x0 and x1 is stored in TLS_REG0_SLOT and TLS_REG1_SLOT
* - store all registers into dcontext's mcontext
* - restore REG_DCXT app value from TLS slot to mcontext
* - restore dr_reg_stolen app value from TLS slot to mcontext
*/
void
append_save_gpr(dcontext_t *dcontext, instrlist_t *ilist, bool ibl_end, bool absolute,
generated_code_t *code, linkstub_t *linkstub, bool coarse_info)
{
int i;
/* X0 and X1 will always have been saved in TLS slots before executing
* the code generated here. See, for example:
* emit_do_syscall_common, emit_indirect_branch_lookup, handle_sigreturn,
* insert_exit_stub_other_flags, execute_handler_from_{cache,dispatch},
* transfer_from_sig_handler_to_fcache_return
*/
for (i = 2; i < 30; i += 2) {
/* stp x(i), x(i+1), [x(dcxt), #xi_offset] */
APP(ilist, INSTR_CREATE_stp(dcontext,
opnd_create_base_disp(REG_DCXT, DR_REG_NULL, 0,
REG_OFFSET(DR_REG_X0 + i),
OPSZ_16),
opnd_create_reg(DR_REG_X0 + i),
opnd_create_reg(DR_REG_X0 + i + 1)));
}
/* mov x1, sp */
APP(ilist, XINST_CREATE_move(dcontext, opnd_create_reg(DR_REG_X1),
opnd_create_reg(DR_REG_SP)));
/* stp x30, x1, [x(dcxt), #x30_offset] */
APP(ilist, INSTR_CREATE_stp(dcontext,
opnd_create_base_disp(REG_DCXT, DR_REG_NULL, 0,
REG_OFFSET(DR_REG_X30), OPSZ_16),
opnd_create_reg(DR_REG_X30),
opnd_create_reg(DR_REG_X1)));
/* ldp x1, x2, [x(stolen)]
* stp x1, x2, [x(dcxt)]
*/
APP(ilist, INSTR_CREATE_ldp(dcontext,
opnd_create_reg(DR_REG_X1), opnd_create_reg(DR_REG_X2),
opnd_create_base_disp(dr_reg_stolen, DR_REG_NULL, 0,
0, OPSZ_16)));
APP(ilist, INSTR_CREATE_stp(dcontext,
opnd_create_base_disp(REG_DCXT, DR_REG_NULL, 0,
0, OPSZ_16),
opnd_create_reg(DR_REG_X1), opnd_create_reg(DR_REG_X2)));
if (linkstub != NULL) {
/* FIXME i#1575: NYI for coarse-grain stub */
ASSERT_NOT_IMPLEMENTED(false);
}
/* REG_DCXT's app value is stored in DCONTEXT_BASE_SPILL_SLOT by
* append_prepare_fcache_return, so copy it to mcontext.
*/
APP(ilist, RESTORE_FROM_TLS(dcontext, SCRATCH_REG1, DCONTEXT_BASE_SPILL_SLOT));
APP(ilist, SAVE_TO_DC(dcontext, SCRATCH_REG1, REG_DCXT_OFFS));
/* dr_reg_stolen's app value is always stored in the TLS spill slot,
* and we restore its value back to mcontext on fcache return.
*/
APP(ilist, RESTORE_FROM_TLS(dcontext, SCRATCH_REG1, TLS_REG_STOLEN_SLOT));
APP(ilist, SAVE_TO_DC(dcontext, SCRATCH_REG1, REG_OFFSET(dr_reg_stolen)));
}
/* dcontext base is held in REG_DCXT, and exit stub in X0.
* GPR's are already saved.
*/
void
append_save_simd_reg(dcontext_t *dcontext, instrlist_t *ilist, bool absolute)
{
int i;
/* add x1, x(DCXT), #(off) */
APP(ilist,
XINST_CREATE_add_2src(dcontext, opnd_create_reg(DR_REG_X1),
opnd_create_reg(REG_DCXT),
OPND_CREATE_INTPTR(offsetof(priv_mcontext_t, simd))));
for (i = 0; i < 32; i += 2) {
/* stp q(i), q(i + 1), [x1, #(i * 16)] */
APP(ilist, INSTR_CREATE_stp(dcontext,
opnd_create_base_disp(DR_REG_X1, DR_REG_NULL, 0,
i * 16, OPSZ_32),
opnd_create_reg(DR_REG_Q0 + i),
opnd_create_reg(DR_REG_Q0 + i + 1)));
}
}
/* Scratch reg0 is holding exit stub. */
void
append_save_clear_xflags(dcontext_t *dcontext, instrlist_t *ilist, bool absolute)
{
APP(ilist, INSTR_CREATE_mrs(dcontext, opnd_create_reg(DR_REG_X1),
opnd_create_reg(DR_REG_NZCV)));
APP(ilist, INSTR_CREATE_mrs(dcontext, opnd_create_reg(DR_REG_X2),
opnd_create_reg(DR_REG_FPCR)));
APP(ilist, INSTR_CREATE_mrs(dcontext, opnd_create_reg(DR_REG_X3),
opnd_create_reg(DR_REG_FPSR)));
APP(ilist, SAVE_TO_DC(dcontext, DR_REG_W1, XFLAGS_OFFSET));
APP(ilist, SAVE_TO_DC(dcontext, DR_REG_W2, XFLAGS_OFFSET + 4));
APP(ilist, SAVE_TO_DC(dcontext, DR_REG_W3, XFLAGS_OFFSET + 8));
}
bool
append_call_enter_dr_hook(dcontext_t *dcontext, instrlist_t *ilist,
bool ibl_end, bool absolute)
{
/* i#1569: DR_HOOK is not supported on AArch64 */
ASSERT_NOT_IMPLEMENTED(EXIT_DR_HOOK == NULL);
return false;
}
void
insert_save_eflags(dcontext_t *dcontext, instrlist_t *ilist, instr_t *where,
uint flags, bool tls, bool absolute
_IF_X86_64(bool x86_to_x64_ibl_opt))
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
}
void
insert_restore_eflags(dcontext_t *dcontext, instrlist_t *ilist, instr_t *where,
uint flags, bool tls, bool absolute
_IF_X86_64(bool x86_to_x64_ibl_opt))
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
}
byte *
emit_inline_ibl_stub(dcontext_t *dcontext, byte *pc,
ibl_code_t *ibl_code, bool target_trace_table)
{
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return pc;
}
byte *
emit_indirect_branch_lookup(dcontext_t *dc, generated_code_t *code, byte *pc,
byte *fcache_return_pc,
bool target_trace_table,
bool inline_ibl_head,
ibl_code_t *ibl_code /* IN/OUT */)
{
bool absolute = false;
instrlist_t ilist;
instrlist_init(&ilist);
patch_list_t *patch = &ibl_code->ibl_patch;
init_patch_list(patch, PATCH_TYPE_INDIRECT_TLS);
instr_t *load_tag = INSTR_CREATE_label(dc);
instr_t *compare_tag = INSTR_CREATE_label(dc);
instr_t *try_next = INSTR_CREATE_label(dc);
instr_t *miss = INSTR_CREATE_label(dc);
instr_t *not_hit = INSTR_CREATE_label(dc);
instr_t *target_delete_entry = INSTR_CREATE_label(dc);
instr_t *unlinked = INSTR_CREATE_label(dc);
/* FIXME i#1569: Use INSTR_CREATE macros when encoder is implemented. */
/* On entry we expect:
* x0: link_stub entry
* x1: scratch reg, arrived from br x1
* x2: indirect branch target
* TLS_REG0_SLOT: app's x0
* TLS_REG1_SLOT: app's x1
* TLS_REG2_SLOT: app's x2
* TLS_REG3_SLOT: scratch space
* There are three entries with the same context:
* indirect_branch_lookup
* target_delete_entry
* unlink_stub_entry
* On miss exit we output:
* x0: the dcontext->last_exit
* x1: br x1
* x2: app's x2
* TLS_REG0_SLOT: app's x0 (recovered by fcache_return)
* TLS_REG1_SLOT: app's x1 (recovered by fcache_return)
* On hit exit we output:
* x0: fragment_start_pc (points to the fragment prefix)
* x1: app's x1
* x2: app's x2
* TLS_REG1_SLOT: app's x0 (recovered by fragment_prefix)
*/
/* Spill x0. */
APP(&ilist, instr_create_save_to_tls(dc, DR_REG_R0, TLS_REG3_SLOT));
/* Load hash mask and base. */
/* ldp x1, x0, [x28, hash_mask] */
APP(&ilist,
INSTR_CREATE_ldp(dc, opnd_create_reg(DR_REG_X1), opnd_create_reg(DR_REG_X0),
opnd_create_base_disp(dr_reg_stolen, DR_REG_NULL, 0,
TLS_MASK_SLOT(ibl_code->branch_type),
OPSZ_16)));
/* and x1, x1, x2 */
APP(&ilist, XINST_CREATE_and(dc, opnd_create_reg(DR_REG_X1),
opnd_create_reg(DR_REG_X2)));
/* Get table entry. */
/* add x1, x0, x1, LSL #4 */
APP(&ilist, INSTR_CREATE_add_shift
(dc, opnd_create_reg(DR_REG_X1),
opnd_create_reg(DR_REG_X0),
opnd_create_reg(DR_REG_X1),
OPND_CREATE_INT8(DR_SHIFT_LSL),
OPND_CREATE_INT8(4 - HASHTABLE_IBL_OFFSET(ibl_code->branch_type))));
/* x1 now holds the fragment_entry_t* in the hashtable. */
APP(&ilist, load_tag);
/* Load tag from fragment_entry_t* in the hashtable to x0. */
/* ldr x0, [x1, #tag_fragment_offset] */
APP(&ilist,
INSTR_CREATE_ldr(dc, opnd_create_reg(DR_REG_X0),
OPND_CREATE_MEMPTR(DR_REG_X1,
offsetof(fragment_entry_t, tag_fragment))));
/* Did we hit? */
APP(&ilist, compare_tag);
/* cbz x0, not_hit */
APP(&ilist, INSTR_CREATE_cbz(dc, opnd_create_instr(not_hit),
opnd_create_reg(DR_REG_X0)));
/* sub x0, x0, x2 */
APP(&ilist, XINST_CREATE_sub(dc, opnd_create_reg(DR_REG_X0),
opnd_create_reg(DR_REG_X2)));
/* cbnz x0, try_next */
APP(&ilist, INSTR_CREATE_cbnz(dc, opnd_create_instr(try_next),
opnd_create_reg(DR_REG_X0)));
/* Hit path: load the app's original value of x0 and x1. */
/* ldp x0, x2, [x28] */
APP(&ilist, INSTR_CREATE_ldp(dc,
opnd_create_reg(DR_REG_X0), opnd_create_reg(DR_REG_X2),
opnd_create_base_disp(dr_reg_stolen, DR_REG_NULL, 0,
TLS_REG0_SLOT, OPSZ_16)));
/* Store x0 in TLS_REG1_SLOT as requied in the fragment prefix. */
APP(&ilist, instr_create_save_to_tls(dc, DR_REG_R0, TLS_REG1_SLOT));
/* ldr x0, [x1, #start_pc_fragment_offset] */
APP(&ilist, INSTR_CREATE_ldr
(dc, opnd_create_reg(DR_REG_X0),
OPND_CREATE_MEMPTR(DR_REG_X1,
offsetof(fragment_entry_t, start_pc_fragment))));
/* mov x1, x2 */
APP(&ilist, XINST_CREATE_move(dc, opnd_create_reg(DR_REG_X1),
opnd_create_reg(DR_REG_X2)));
/* Recover app's original x2. */
APP(&ilist, instr_create_restore_from_tls(dc, DR_REG_R2, TLS_REG2_SLOT));
/* br x0 */
APP(&ilist, INSTR_CREATE_br(dc, opnd_create_reg(DR_REG_X0)));
APP(&ilist, try_next);
/* Try next entry, in case of collision. No wraparound check is needed
* because of the sentinel at the end.
* ldr x0, [x1, #tag_fragment_offset]! */
APP(&ilist,
instr_create_2dst_3src(dc, OP_ldr, opnd_create_reg(DR_REG_X0),
opnd_create_reg(DR_REG_X1),
OPND_CREATE_MEMPTR(DR_REG_X1, sizeof(fragment_entry_t)),
opnd_create_reg(DR_REG_X1),
OPND_CREATE_INTPTR(sizeof(fragment_entry_t))));
/* b compare_tag */
APP(&ilist, INSTR_CREATE_b(dc, opnd_create_instr(compare_tag)));
APP(&ilist, not_hit);
if (INTERNAL_OPTION(ibl_sentinel_check)) {
/* Load start_pc from fragment_entry_t* in the hashtable to x0. */
/* ldr x0, [x1, #start_pc_fragment] */
APP(&ilist, XINST_CREATE_load(dc, opnd_create_reg(DR_REG_X0),
OPND_CREATE_MEMPTR(DR_REG_X1,
offsetof(fragment_entry_t,
start_pc_fragment))));
/* To compare with an arbitrary constant we'd need a 4th scratch reg.
* Instead we rely on the sentinel start PC being 1.
*/
ASSERT(HASHLOOKUP_SENTINEL_START_PC == (cache_pc)PTR_UINT_1);
/* sub x0, x0, #1 */
APP(&ilist, XINST_CREATE_sub(dc, opnd_create_reg(DR_REG_X0),
OPND_CREATE_INT8(1)));
/* cbnz x0, miss */
APP(&ilist, INSTR_CREATE_cbnz(dc, opnd_create_instr(miss),
opnd_create_reg(DR_REG_R0)));
/* Point at the first table slot and then go load and compare its tag */
/* ldr x1, [x28, #table_base] */
APP(&ilist,
XINST_CREATE_load(dc, opnd_create_reg(DR_REG_X1),
OPND_CREATE_MEMPTR(dr_reg_stolen,
TLS_TABLE_SLOT(ibl_code->branch_type))));
/* branch to load_tag */
APP(&ilist, INSTR_CREATE_b(dc, opnd_create_instr(load_tag)));
}
APP(&ilist, miss);
/* Recover the dcontext->last_exit to x0 */
APP(&ilist, instr_create_restore_from_tls(dc, DR_REG_R0, TLS_REG3_SLOT));
/* Target delete entry */
APP(&ilist, target_delete_entry);
add_patch_marker(patch, target_delete_entry, PATCH_ASSEMBLE_ABSOLUTE,
0 /* beginning of instruction */,
(ptr_uint_t*)&ibl_code->target_delete_entry);
/* Unlink path: entry from stub */
APP(&ilist, unlinked);
add_patch_marker(patch, unlinked, PATCH_ASSEMBLE_ABSOLUTE,
0 /* beginning of instruction */,
(ptr_uint_t*)&ibl_code->unlinked_ibl_entry);
/* Put ib tgt into dcontext->next_tag */
insert_shared_get_dcontext(dc, &ilist, NULL, true);
APP(&ilist, SAVE_TO_DC(dc, DR_REG_R2, NEXT_TAG_OFFSET));
APP(&ilist, instr_create_restore_from_tls(dc, DR_REG_R5, DCONTEXT_BASE_SPILL_SLOT));
APP(&ilist, instr_create_restore_from_tls(dc, DR_REG_R2, TLS_REG2_SLOT));
/* ldr x1, [x(stolen), #(offs)] */
APP(&ilist, INSTR_CREATE_ldr(dc, opnd_create_reg(DR_REG_X1),
OPND_TLS_FIELD(TLS_FCACHE_RETURN_SLOT)));
/* br x1 */
APP(&ilist, INSTR_CREATE_br(dc, opnd_create_reg(DR_REG_X1)));
ibl_code->ibl_routine_length = encode_with_patch_list(dc, patch, &ilist, pc);
instrlist_clear(dc, &ilist);
return pc + ibl_code->ibl_routine_length;
}
void
relink_special_ibl_xfer(dcontext_t *dcontext, int index,
ibl_entry_point_type_t entry_type,
ibl_branch_type_t ibl_type)
{
generated_code_t *code;
byte *ibl_tgt;
uint *pc;
if (dcontext == GLOBAL_DCONTEXT) {
ASSERT(!special_ibl_xfer_is_thread_private()); /* else shouldn't be called */
code = SHARED_GENCODE_MATCH_THREAD(get_thread_private_dcontext());
} else {
ASSERT(special_ibl_xfer_is_thread_private()); /* else shouldn't be called */
code = THREAD_GENCODE(dcontext);
}
if (code == NULL) /* thread private that we don't need */
return;
ibl_tgt = special_ibl_xfer_tgt(dcontext, code, entry_type, ibl_type);
ASSERT(code->special_ibl_xfer[index] != NULL);
pc = (uint *)(code->special_ibl_xfer[index] + code->special_ibl_unlink_offs[index]);
protect_generated_code(code, WRITABLE);
/* ldr x1, [x(stolen), #(offs)] */
pc[0] = (0xf9400000 | 1 | (dr_reg_stolen - DR_REG_X0) << 5 |
get_ibl_entry_tls_offs(dcontext, ibl_tgt) >> 3 << 10);
/* br x1 */
pc[1] = 0xd61f0000 | 1 << 5;
machine_cache_sync(pc, pc + 2, true);
protect_generated_code(code, READONLY);
}
bool
fill_with_nops(dr_isa_mode_t isa_mode, byte *addr, size_t size)
{
byte *pc;
if (!ALIGNED(addr, 4) || !ALIGNED(addr + size, 4)) {
ASSERT_NOT_REACHED();
return false;
}
for (pc = addr; pc < addr + size; pc += 4)
*(uint *)pc = 0xd503201f; /* nop */
return true;
}
| 1 | 11,680 | Use a named constant | DynamoRIO-dynamorio | c |
@@ -56,7 +56,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var stop = Assert.Single(events, e => e.EventName == "ConnectionStop");
Assert.All(new[] { "connectionId" }, p => Assert.Contains(p, stop.PayloadNames));
- Assert.Same(KestrelEventSource.Log, stop.EventSource);
+ Assert.Same(KestrelEventSource.Log, stop?.EventSource);
}
private string GetProperty(EventWrittenEventArgs data, string propName) | 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.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Infrastructure;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{
public class EventSourceTests : IDisposable
{
private readonly TestEventListener _listener = new TestEventListener();
public EventSourceTests()
{
_listener.EnableEvents(KestrelEventSource.Log, EventLevel.Verbose);
}
[Fact]
public async Task EmitsConnectionStartAndStop()
{
string connectionId = null;
int port;
using (var server = new TestServer(context =>
{
connectionId = context.Features.Get<IHttpConnectionFeature>().ConnectionId;
return Task.CompletedTask;
}))
{
port = server.Port;
using (var connection = server.CreateConnection())
{
await connection.SendAll("GET / HTTP/1.1",
"",
"")
.TimeoutAfter(TimeSpan.FromSeconds(10));
await connection.Receive("HTTP/1.1 200");
}
}
// capture list here as other tests executing in parallel may log events
Assert.NotNull(connectionId);
var events = _listener.EventData.Where(e => e != null && GetProperty(e, "connectionId") == connectionId).ToList();
var start = Assert.Single(events, e => e.EventName == "ConnectionStart");
Assert.All(new[] { "connectionId", "scheme", "remoteEndPoint", "localEndPoint" }, p => Assert.Contains(p, start.PayloadNames));
Assert.Equal("http", GetProperty(start, "scheme"));
Assert.Equal($"127.0.0.1:{port}", GetProperty(start, "localEndPoint"));
var stop = Assert.Single(events, e => e.EventName == "ConnectionStop");
Assert.All(new[] { "connectionId" }, p => Assert.Contains(p, stop.PayloadNames));
Assert.Same(KestrelEventSource.Log, stop.EventSource);
}
private string GetProperty(EventWrittenEventArgs data, string propName)
=> data.Payload[data.PayloadNames.IndexOf(propName)] as string;
private class TestEventListener : EventListener
{
private volatile bool _disposed;
private ConcurrentBag<EventWrittenEventArgs> _events = new ConcurrentBag<EventWrittenEventArgs>();
public IEnumerable<EventWrittenEventArgs> EventData => _events;
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
if (!_disposed)
{
_events.Add(eventData);
}
}
public override void Dispose()
{
_disposed = true;
base.Dispose();
}
}
public void Dispose()
{
_listener.Dispose();
}
}
}
| 1 | 12,412 | The `?` is unnecessary since `Assert.Single` will fail if it can't find the stop event. | aspnet-KestrelHttpServer | .cs |
@@ -29,6 +29,12 @@ import org.apache.iceberg.StructLike;
* Implementations must be {@link Serializable} because instances will be serialized to tasks.
*/
public interface LocationProvider extends Serializable {
+
+ /**
+ * Return a fully-qualified data location.
+ */
+ String dataLocation();
+
/**
* Return a fully-qualified data file location for the given filename.
* | 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.io;
import java.io.Serializable;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.StructLike;
/**
* Interface for providing data file locations to write tasks.
* <p>
* Implementations must be {@link Serializable} because instances will be serialized to tasks.
*/
public interface LocationProvider extends Serializable {
/**
* Return a fully-qualified data file location for the given filename.
*
* @param filename a file name
* @return a fully-qualified location URI for a data file
*/
String newDataLocation(String filename);
/**
* Return a fully-qualified data file location for the given partition and filename.
*
* @param spec a partition spec
* @param partitionData a tuple of partition data for data in the file, matching the given spec
* @param filename a file name
* @return a fully-qualified location URI for a data file
*/
String newDataLocation(PartitionSpec spec, StructLike partitionData, String filename);
}
| 1 | 18,984 | What about providers that don't have a reliable location? Do they return null? | apache-iceberg | java |
@@ -14,9 +14,14 @@
// limitations under the License.
// </copyright>
+using System;
+
namespace OpenTelemetry.Metrics
{
public abstract class MetricProcessor : BaseProcessor<MetricItem>
{
+ // GetMetric or GetMemoryState or GetAggregatedMetrics..
+ // ...or some other names
+ public abstract void SetGetMetricFunction(Func<MetricItem> getMetrics);
}
} | 1 | // <copyright file="MetricProcessor.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>
namespace OpenTelemetry.Metrics
{
public abstract class MetricProcessor : BaseProcessor<MetricItem>
{
}
}
| 1 | 20,580 | I might not be thinking about things right, but would it make sense for a MetricProcessor to have a handle on the ParentProvider kinda like how we do for traces? That way instead of calling `SetGetMetricFunction(this.Collect)` in the MeterProviderSdk you'd have a handle on the provider to call `Collect` directly. | open-telemetry-opentelemetry-dotnet | .cs |
@@ -30,7 +30,8 @@ def check_dynamodb(expect_shutdown=False, print_error=False):
# wait for backend port to be opened
wait_for_port_open(PORT_DYNAMODB_BACKEND, http_path="/", expect_success=False, sleep_time=1)
# check DynamoDB
- out = aws_stack.connect_to_service("dynamodb").list_tables()
+ endpoint_url = f"http://127.0.0.1:{PORT_DYNAMODB_BACKEND}"
+ out = aws_stack.connect_to_service("dynamodb", endpoint_url=endpoint_url).list_tables()
except Exception as e:
if print_error:
LOGGER.error("DynamoDB health check failed: %s %s" % (e, traceback.format_exc())) | 1 | import logging
import os
import traceback
from localstack import config
from localstack.constants import MODULE_MAIN_PATH
from localstack.services import install
from localstack.services.dynamodb import dynamodb_listener
from localstack.services.infra import do_run, log_startup_message, start_proxy_for_service
from localstack.utils.aws import aws_stack
from localstack.utils.common import (
get_free_tcp_port,
mkdir,
wait_for_port_closed,
wait_for_port_open,
)
LOGGER = logging.getLogger(__name__)
# backend service port (updated on startup)
PORT_DYNAMODB_BACKEND = None
# todo: will be replaced with plugin mechanism
PROCESS_THREAD = None
def check_dynamodb(expect_shutdown=False, print_error=False):
out = None
try:
# wait for backend port to be opened
wait_for_port_open(PORT_DYNAMODB_BACKEND, http_path="/", expect_success=False, sleep_time=1)
# check DynamoDB
out = aws_stack.connect_to_service("dynamodb").list_tables()
except Exception as e:
if print_error:
LOGGER.error("DynamoDB health check failed: %s %s" % (e, traceback.format_exc()))
if expect_shutdown:
assert out is None
else:
assert isinstance(out["TableNames"], list)
def start_dynamodb(port=None, asynchronous=False, update_listener=None):
global PROCESS_THREAD, PORT_DYNAMODB_BACKEND
PORT_DYNAMODB_BACKEND = get_free_tcp_port()
port = port or config.PORT_DYNAMODB
install.install_dynamodb_local()
ddb_data_dir_param = "-inMemory"
if config.DATA_DIR:
ddb_data_dir = "%s/dynamodb" % config.DATA_DIR
mkdir(ddb_data_dir)
# as the service command cds into a different directory, the absolute
# path of the DATA_DIR is needed as the -dbPath
absolute_path = os.path.abspath(ddb_data_dir)
ddb_data_dir_param = "-dbPath %s" % absolute_path
cmd = (
"cd %s/infra/dynamodb/; java -Djava.library.path=./DynamoDBLocal_lib "
+ "-Xmx%s -jar DynamoDBLocal.jar -port %s %s"
) % (
MODULE_MAIN_PATH,
config.DYNAMODB_HEAP_SIZE,
PORT_DYNAMODB_BACKEND,
ddb_data_dir_param,
)
log_startup_message("DynamoDB")
start_proxy_for_service(
"dynamodb",
port,
backend_port=PORT_DYNAMODB_BACKEND,
update_listener=update_listener,
)
# todo: extract reference from do_run (should return pid)
PROCESS_THREAD = do_run(cmd, asynchronous, auto_restart=True)
return PROCESS_THREAD
def restart_dynamodb():
LOGGER.debug("Restarting DynamoDB process ...")
PROCESS_THREAD.stop()
wait_for_port_closed(PORT_DYNAMODB_BACKEND)
start_dynamodb(asynchronous=True, update_listener=dynamodb_listener.UPDATE_DYNAMODB)
| 1 | 13,243 | nit: If we want to squeeze out a few more milliseconds from the startup, we may actually be able to remove this line (`wait_for_port_open(PORT_DYNAMODB_BACKEND, http_path="/", ...` should already be sufficient to ensure that the service is up and responding to HTTP requests). Thoughts? | localstack-localstack | py |
@@ -4880,7 +4880,7 @@ os_normalized_sysnum(int num_raw, instr_t *gateway, dcontext_t *dcontext)
}
}
# ifdef X64
- if (num_raw >> 24 == 0x2)
+ if (num_raw & SYSCALL_NUM_MARKER_BSD)
return (int)(num_raw & 0xffffff); /* Drop BSD bit */
else
num = (int)num_raw; /* Keep Mach and Machdep bits */ | 1 | /* *******************************************************************************
* Copyright (c) 2010-2021 Google, Inc. All rights reserved.
* Copyright (c) 2011 Massachusetts Institute of Technology 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 */
/*
* os.c - Linux specific routines
*/
/* Easiest to match kernel stat struct by using 64-bit.
* This limits us to 2.4+ kernel but that's ok.
* I don't really want to get into requiring kernel headers to build
* general release packages, though that would be fine for targeted builds.
* There are 3 different stat syscalls (SYS_oldstat, SYS_stat, and SYS_stat64)
* and using _LARGEFILE64_SOURCE with SYS_stat64 is the best match.
*/
#define _LARGEFILE64_SOURCE
/* for mmap-related #defines */
#include <sys/types.h>
#include <sys/mman.h>
/* in case MAP_32BIT is missing */
#ifndef MAP_32BIT
# define MAP_32BIT 0x40
#endif
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON /* MAP_ANON on Mac */
#endif
/* for open */
#include <sys/stat.h>
#include <fcntl.h>
#include "../globals.h"
#include "../hashtable.h"
#include "../native_exec.h"
#include <unistd.h> /* for write and usleep and _exit */
#include <limits.h>
#ifdef MACOS
# include <sys/sysctl.h> /* for sysctl */
# ifndef SYS___sysctl
/* The name was changed on Yosemite */
# define SYS___sysctl SYS_sysctl
# endif
# include <mach/mach_traps.h> /* for swtch_pri */
# include "include/syscall_mach.h"
#endif
#ifdef LINUX
# include <sys/vfs.h> /* for statfs */
#elif defined(MACOS)
# include <sys/mount.h> /* for statfs */
# include <mach/mach.h>
# include <mach/task.h>
# include <mach/semaphore.h>
# include <mach/sync_policy.h>
#endif
#include <dirent.h>
/* for getrlimit */
#include <sys/time.h>
#include <sys/resource.h>
#ifndef X64
struct compat_rlimit {
uint rlim_cur;
uint rlim_max;
};
#endif
#ifdef MACOS
typedef struct rlimit rlimit64_t;
#else
typedef struct rlimit64 rlimit64_t;
#endif
#ifdef LINUX
/* For clone and its flags, the manpage says to include sched.h with _GNU_SOURCE
* defined. _GNU_SOURCE brings in unwanted extensions and causes name
* conflicts. Instead, we include unix/sched.h which comes from the Linux
* kernel headers.
*/
# include <linux/sched.h>
#endif
#include "module.h" /* elf */
#include "tls.h"
#if defined(X86) && defined(DEBUG)
# include "os_asm_defines.asm" /* for TLS_SELF_OFFSET_ASM */
#endif
#ifndef F_DUPFD_CLOEXEC /* in linux 2.6.24+ */
# define F_DUPFD_CLOEXEC 1030
#endif
/* This is not always sufficient to identify a syscall return value.
* For example, MacOS has some 32-bit syscalls that return 64-bit
* values in xdx:xax.
*/
#define MCXT_SYSCALL_RES(mc) ((mc)->IF_X86_ELSE(xax, r0))
#if defined(DR_HOST_AARCH64)
# define READ_TP_TO_R3_DISP_IN_R2 \
"mrs " ASM_R3 ", tpidr_el0\n\t" \
"ldr " ASM_R3 ", [" ASM_R3 ", " ASM_R2 "] \n\t"
#elif defined(DR_HOST_ARM)
# define READ_TP_TO_R3_DISP_IN_R2 \
"mrc p15, 0, " ASM_R3 \
", c13, c0, " STRINGIFY(USR_TLS_REG_OPCODE) " \n\t" \
"ldr " ASM_R3 ", [" ASM_R3 \
", " ASM_R2 "] \n\t"
#endif /* ARM */
/* Prototype for all functions in .init_array. */
typedef int (*init_fn_t)(int argc, char **argv, char **envp);
/* For STATIC_LIBRARY we do not cache environ so the app can change it. */
#ifndef STATIC_LIBRARY
/* i#46: Private __environ pointer. Points at the environment variable array
* on the stack, which is different from what libc __environ may point at. We
* use the environment for following children and setting options, so its OK
* that we don't see what libc says.
*/
char **our_environ;
#endif
#include <errno.h>
/* avoid problems with use of errno as var name in rest of file */
#if !defined(STANDALONE_UNIT_TEST) && !defined(MACOS)
# undef errno
#endif
/* we define __set_errno below */
/* must be prior to <link.h> => <elf.h> => INT*_{MIN,MAX} */
#include "instr.h" /* for get_app_segment_base() */
#include "decode_fast.h" /* decode_cti: maybe os_handle_mov_seg should be ifdef X86? */
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <syslog.h> /* vsyslog */
#include "../vmareas.h"
#ifdef RCT_IND_BRANCH
# include "../rct.h"
#endif
#ifdef LINUX
# include "include/syscall.h" /* our own local copy */
# include "include/clone3.h"
# include "include/close_range.h"
#else
# include <sys/syscall.h>
#endif
#include "../module_shared.h"
#include "os_private.h"
#include "../synch.h"
#include "memquery.h"
#include "ksynch.h"
#include "dr_tools.h" /* dr_syscall_result_info_t */
#ifndef HAVE_MEMINFO_QUERY
# include "memcache.h"
#endif
#include "instrument.h"
#ifdef LINUX
# include "rseq_linux.h"
#endif
#ifdef MACOS
# define SYSNUM_EXIT_PROCESS SYS_exit
# define SYSNUM_EXIT_THREAD SYS_bsdthread_terminate
#else
# define SYSNUM_EXIT_PROCESS SYS_exit_group
# define SYSNUM_EXIT_THREAD SYS_exit
#endif
#ifdef ANDROID
/* Custom prctl flags specific to Android (xref i#1861) */
# define PR_SET_VMA 0x53564d41
# define PR_SET_VMA_ANON_NAME 0
#endif
/* Guards data written by os_set_app_thread_area(). */
DECLARE_CXTSWPROT_VAR(static mutex_t set_thread_area_lock,
INIT_LOCK_FREE(set_thread_area_lock));
static bool first_thread_tls_initialized;
static bool last_thread_tls_exited;
tls_type_t tls_global_type;
#ifndef HAVE_TLS
/* We use a table lookup to find a thread's dcontext */
/* Our only current no-TLS target, VMKernel (VMX86_SERVER), doesn't have apps with
* tons of threads anyway
*/
# define MAX_THREADS 512
typedef struct _tls_slot_t {
thread_id_t tid;
dcontext_t *dcontext;
} tls_slot_t;
/* Stored in heap for self-prot */
static tls_slot_t *tls_table;
/* not static so deadlock_avoidance_unlock() can look for it */
DECLARE_CXTSWPROT_VAR(mutex_t tls_lock, INIT_LOCK_FREE(tls_lock));
#endif
/* Should we place this in a client header? Currently mentioned in
* dr_raw_tls_calloc() docs.
*/
static bool client_tls_allocated[MAX_NUM_CLIENT_TLS];
DECLARE_CXTSWPROT_VAR(static mutex_t client_tls_lock, INIT_LOCK_FREE(client_tls_lock));
#include <stddef.h> /* for offsetof */
#include <sys/utsname.h> /* for struct utsname */
/* forward decl */
static void
handle_execve_post(dcontext_t *dcontext);
static bool
os_switch_lib_tls(dcontext_t *dcontext, bool to_app);
static bool
os_switch_seg_to_context(dcontext_t *dcontext, reg_id_t seg, bool to_app);
#ifdef X86
static bool
os_set_dr_tls_base(dcontext_t *dcontext, os_local_state_t *tls, byte *base);
#endif
#ifdef LINUX
static bool
handle_app_mremap(dcontext_t *dcontext, byte *base, size_t size, byte *old_base,
size_t old_size, uint old_prot, uint old_type);
static void
handle_app_brk(dcontext_t *dcontext, byte *lowest_brk /*if known*/, byte *old_brk,
byte *new_brk);
#endif
/* full path to our own library, used for execve */
static char dynamorio_library_path[MAXIMUM_PATH]; /* just dir */
static char dynamorio_library_filepath[MAXIMUM_PATH];
/* Issue 20: path to other architecture */
static char dynamorio_alt_arch_path[MAXIMUM_PATH];
static char dynamorio_alt_arch_filepath[MAXIMUM_PATH]; /* just dir */
/* Makefile passes us LIBDIR_X{86,64} defines */
#define DR_LIBDIR_X86 STRINGIFY(LIBDIR_X86)
#define DR_LIBDIR_X64 STRINGIFY(LIBDIR_X64)
/* pc values delimiting dynamo dll image */
static app_pc dynamo_dll_start = NULL;
static app_pc dynamo_dll_end = NULL; /* open-ended */
/* pc values delimiting the app, equal to the "dll" bounds for static DR */
static app_pc executable_start = NULL;
static app_pc executable_end = NULL;
/* Used by get_application_name(). */
static char executable_path[MAXIMUM_PATH];
static char *executable_basename;
/* Pointers to arguments. Refers to the main stack set up by the kernel.
* These are only written once during process init and we can live with
* the non-guaranteed-delay until they are visible to other cores.
*/
static int *app_argc = NULL;
static char **app_argv = NULL;
/* does the kernel provide tids that must be used to distinguish threads in a group? */
static bool kernel_thread_groups;
static bool kernel_64bit;
pid_t pid_cached;
static bool fault_handling_initialized;
#ifdef PROFILE_RDTSC
uint kilo_hertz; /* cpu clock speed */
#endif
/* Xref PR 258731, dup of STDOUT/STDERR in case app wants to close them. */
DR_API file_t our_stdout = STDOUT_FILENO;
DR_API file_t our_stderr = STDERR_FILENO;
DR_API file_t our_stdin = STDIN_FILENO;
/* we steal fds from the app */
static rlimit64_t app_rlimit_nofile; /* cur rlimit set by app */
static int min_dr_fd;
/* we store all DR files so we can prevent the app from changing them,
* and so we can close them in a child of fork.
* the table key is the fd and the payload is the set of DR_FILE_* flags.
*/
static generic_table_t *fd_table;
#define INIT_HTABLE_SIZE_FD 6 /* should remain small */
#ifdef DEBUG
static int num_fd_add_pre_heap;
#endif
#ifdef LINUX
/* i#1004: brk emulation */
static byte *app_brk_map;
static byte *app_brk_cur;
static byte *app_brk_end;
#endif
#ifdef MACOS
static int macos_version;
#endif
static bool
is_readable_without_exception_internal(const byte *pc, size_t size, bool query_os);
static bool
mmap_check_for_module_overlap(app_pc base, size_t size, bool readable, uint64 inode,
bool at_map);
#ifdef LINUX
static char *
read_proc_self_exe(bool ignore_cache);
#endif
/* Libc independent directory iterator, similar to readdir. If we ever need
* this on Windows we should generalize it and export it to clients.
*/
typedef struct _dir_iterator_t {
file_t fd;
int off;
int end;
const char *name; /* Name of the current entry. */
char buf[4 * MAXIMUM_PATH]; /* Expect stack alloc, so not too big. */
} dir_iterator_t;
static void
os_dir_iterator_start(dir_iterator_t *iter, file_t fd);
static bool
os_dir_iterator_next(dir_iterator_t *iter);
/* XXX: If we generalize to Windows, will we need os_dir_iterator_stop()? */
/* vsyscall page. hardcoded at 0xffffe000 in earlier kernels, but
* randomly placed since fedora2.
* marked rx then: FIXME: should disallow this guy when that's the case!
* random vsyscall page is identified in maps files as "[vdso]"
* (kernel-provided fake shared library or Virt Dyn Shared Object).
*/
/* i#1583: vdso is now 2 pages, yet we assume vsyscall is on 1st page. */
/* i#2945: vdso is now 3 pages and vsyscall is not on the 1st page. */
app_pc vsyscall_page_start = NULL;
/* pc of the end of the syscall instr itself */
app_pc vsyscall_syscall_end_pc = NULL;
/* pc where kernel returns control after sysenter vsyscall */
app_pc vsyscall_sysenter_return_pc = NULL;
/* pc where our hook-displaced code was copied */
app_pc vsyscall_sysenter_displaced_pc = NULL;
#define VSYSCALL_PAGE_START_HARDCODED ((app_pc)(ptr_uint_t)0xffffe000)
#ifdef X64
/* i#430, in Red Hat Enterprise Server 5.6, vsyscall region is marked
* not executable
* ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vsyscall]
*/
# define VSYSCALL_REGION_MAPS_NAME "[vsyscall]"
#endif
/* i#1908: vdso and vsyscall are now split */
app_pc vdso_page_start = NULL;
size_t vdso_size = 0;
#if !defined(STANDALONE_UNIT_TEST) && !defined(STATIC_LIBRARY)
/* The pthreads library keeps errno in its pthread_descr data structure,
* which it looks up by dispatching on the stack pointer. This doesn't work
* when within dynamo. Thus, we define our own __errno_location() for use both
* by us and the app, to prevent pthreads looking at the stack pointer when
* out of the code cache.
*/
/* FIXME: maybe we should create 1st dcontext earlier so we don't need init_errno?
* any problems with init_errno being set and then dcontext->errno being read?
* FIXME: if a thread issues a dr_app_stop, then we don't want to use
* this errno slot? But it may later do a start...probably ok to keep using
* the slot. But, when threads die, they'll all use the same init_errno!
*/
static int init_errno; /* errno until 1st dcontext created */
int *
__errno_location(void)
{
/* Each dynamo thread should have a separate errno */
dcontext_t *dcontext = get_thread_private_dcontext();
if (dcontext == NULL)
return &init_errno;
else {
/* WARNING: init_errno is in data segment so can be RO! */
return &(dcontext->upcontext_ptr->dr_errno);
}
}
#endif /* !STANDALONE_UNIT_TEST && !STATIC_LIBRARY */
#ifdef HAVE_TLS
/* i#598
* (gdb) x/20i (*(errno_loc_t)0xf721e413)
* 0xf721e413 <__errno_location>: push %ebp
* 0xf721e414 <__errno_location+1>: mov %esp,%ebp
* 0xf721e416 <__errno_location+3>: call <__x86.get_pc_thunk.cx>
* 0xf721e41b <__errno_location+8>: add $0x166bd9,%ecx
* 0xf721e421 <__errno_location+14>: mov -0x1c(%ecx),%eax
* 0xf721e427 <__errno_location+20>: add %gs:0x0,%eax
* 0xf721e42e <__errno_location+27>: pop %ebp
* 0xf721e42f <__errno_location+28>: ret
*
* __errno_location calcuates the errno location by adding
* TLS's base with errno's offset in TLS.
* However, because the TLS has been switched in os_tls_init,
* the calculated address is wrong.
* We first get the errno offset in TLS at init time and
* calculate correct address by adding the app's tls base.
*/
/* __errno_location on ARM:
* 0xb6f0b290 <__errno_location>: ldr r3, [pc, #12]
* 0xb6f0b292 <__errno_location+2>: mrc 15, 0, r0, cr13, cr0, {3}
* 0xb6f0b296 <__errno_location+6>: add r3, pc
* 0xb6f0b298 <__errno_location+8>: ldr r3, [r3, #0]
* 0xb6f0b29a <__errno_location+10>: adds r0, r0, r3
* 0xb6f0b29c <__errno_location+12>: bx lr
* It uses the predefined offset to get errno location in TLS,
* and we should be able to reuse the code here.
*/
static int libc_errno_tls_offs;
static int *
our_libc_errno_loc(void)
{
void *app_tls = os_get_app_tls_base(NULL, TLS_REG_LIB);
if (app_tls == NULL)
return NULL;
return (int *)(app_tls + libc_errno_tls_offs);
}
#endif
/* i#238/PR 499179: libc errno preservation
*
* Errno location is per-thread so we store the
* function globally and call it each time. Note that pthreads seems
* to be the one who provides per-thread errno: using raw syscalls to
* create threads, we end up with a global errno:
*
* > for i in linux.thread.*0/log.*; do grep 'libc errno' $i | head -1; done
* libc errno loc: 0x00007f153de26698
* libc errno loc: 0x00007f153de26698
* > for i in pthreads.pthreads.*0/log.*; do grep 'libc errno' $i | head -1; done
* libc errno loc: 0x00007fc24d1ce698
* libc errno loc: 0x00007fc24d1cd8b8
* libc errno loc: 0x00007fc24c7cc8b8
*/
typedef int *(*errno_loc_t)(void);
#ifdef LINUX
/* Stores whether clone3 is unsupported on the system we're running on. */
static bool is_clone3_enosys = false;
#endif
static errno_loc_t
get_libc_errno_location(bool do_init)
{
static errno_loc_t libc_errno_loc;
if (do_init) {
module_iterator_t *mi = module_iterator_start();
while (module_iterator_hasnext(mi)) {
module_area_t *area = module_iterator_next(mi);
const char *modname = GET_MODULE_NAME(&area->names);
/* We ensure matches start to avoid matching "libgolibc.so".
* GET_MODULE_NAME never includes the path: i#138 will add path.
*/
if (modname != NULL && strstr(modname, "libc.so") == modname) {
bool found = true;
/* called during init when .data is writable */
libc_errno_loc =
(errno_loc_t)d_r_get_proc_address(area->start, "__errno_location");
ASSERT(libc_errno_loc != NULL);
LOG(GLOBAL, LOG_THREADS, 2, "libc errno loc func: " PFX "\n",
libc_errno_loc);
/* Currently, the DR is loaded by system loader and hooked up
* to app's libc. So right now, we still need this routine.
* we can remove this after libc independency and/or
* early injection
*/
if (INTERNAL_OPTION(private_loader)) {
acquire_recursive_lock(&privload_lock);
if (privload_lookup_by_base(area->start) != NULL)
found = false;
release_recursive_lock(&privload_lock);
}
if (found)
break;
}
}
module_iterator_stop(mi);
#ifdef HAVE_TLS
/* i#598: init the libc errno's offset. If we didn't find libc above,
* then we don't need to do this.
*/
if (INTERNAL_OPTION(private_loader) && libc_errno_loc != NULL) {
void *priv_lib_tls_base = os_get_priv_tls_base(NULL, TLS_REG_LIB);
ASSERT(priv_lib_tls_base != NULL);
libc_errno_tls_offs = (void *)libc_errno_loc() - priv_lib_tls_base;
libc_errno_loc = &our_libc_errno_loc;
}
#endif
}
return libc_errno_loc;
}
/* i#238/PR 499179: our __errno_location isn't affecting libc so until
* we have libc independence or our own private isolated libc we need
* to preserve the app's libc's errno
*/
int
get_libc_errno(void)
{
#if defined(STANDALONE_UNIT_TEST) && (defined(MACOS) || defined(ANDROID))
return errno;
#else
# ifdef STANDALONE_UNIT_TEST
errno_loc_t func = __errno_location;
# else
errno_loc_t func = get_libc_errno_location(false);
# endif
if (func == NULL) {
/* libc hasn't been loaded yet or we're doing early injection. */
return 0;
} else {
int *loc = (*func)();
ASSERT(loc != NULL);
LOG(THREAD_GET, LOG_THREADS, 5, "libc errno loc: " PFX "\n", loc);
if (loc != NULL)
return *loc;
}
return 0;
#endif
}
/* N.B.: pthreads has two other locations it keeps on a per-thread basis:
* h_errno and res_state. See glibc-2.2.4/linuxthreads/errno.c.
* If dynamo ever modifies those we'll need to do to them what we now do to
* errno.
*/
/* The environment vars exhibit totally messed up behavior when someone
* does an execve of /bin/sh -- not sure what's going on, but using our
* own implementation of unsetenv fixes all our problems. If we use
* libc's, unsetenv either does nothing or ends up having getenv return
* NULL for other vars that are obviously set (by iterating through environ).
* FIXME: find out the real story here.
*/
int
our_unsetenv(const char *name)
{
/* FIXME: really we should have some kind of synchronization */
size_t name_len;
char **env = our_environ;
if (name == NULL || *name == '\0' || strchr(name, '=') != NULL) {
return -1;
}
ASSERT(our_environ != NULL);
if (our_environ == NULL)
return -1;
name_len = strlen(name);
while (*env != NULL) {
if (strncmp(*env, name, name_len) == 0 && (*env)[name_len] == '=') {
/* We have a match. Shift the subsequent entries. Keep going to
* handle later matches.
*/
char **e;
for (e = env; *e != NULL; e++)
*e = *(e + 1);
} else {
env++;
}
}
return 0;
}
/* Clobbers the name rather than shifting, to preserve auxv (xref i#909). */
bool
disable_env(const char *name)
{
size_t name_len;
char **env = our_environ;
if (name == NULL || *name == '\0' || strchr(name, '=') != NULL) {
return false;
}
ASSERT(our_environ != NULL);
if (our_environ == NULL)
return false;
name_len = strlen(name);
while (*env != NULL) {
if (strncmp(*env, name, name_len) == 0 && (*env)[name_len] == '=') {
/* We have a match. If we shift subsequent entries we'll mess
* up access to auxv, which is after the env block, so we instead
* disable the env var by changing its name.
* We keep going to handle later matches.
*/
snprintf(*env, name_len, "__disabled__");
}
env++;
}
return true;
}
/* i#46: Private getenv.
*/
char *
our_getenv(const char *name)
{
char **env = our_environ;
size_t i;
size_t name_len;
if (name == NULL || name[0] == '\0' || strchr(name, '=') != NULL) {
return NULL;
}
ASSERT_MESSAGE(CHKLVL_ASSERTS,
"our_environ is missing. _init() or "
"dynamorio_set_envp() were not called",
our_environ != NULL);
if (our_environ == NULL)
return NULL;
name_len = strlen(name);
for (i = 0; env[i] != NULL; i++) {
if (strncmp(env[i], name, name_len) == 0 && env[i][name_len] == '=') {
return env[i] + name_len + 1;
}
}
return NULL;
}
bool
is_our_environ_followed_by_auxv(void)
{
#ifdef STATIC_LIBRARY
/* Since we initialize late, our_environ is likely no longer pointed at
* the stack (i#2122).
*/
return false;
#else
return true;
#endif
}
/* Work around drpreload's _init going first. We can get envp in our own _init
* routine down below, but drpreload.so comes first and calls
* dynamorio_app_init before our own _init routine gets called. Apps using the
* app API are unaffected because our _init routine will have run by then. For
* STATIC_LIBRARY, we used to set our_environ in our_init(), but to support
* the app setting DYNAMORIO_OPTIONS after our_init() runs, we now just use environ.
*/
DYNAMORIO_EXPORT
void
dynamorio_set_envp(char **envp)
{
our_environ = envp;
}
/* shared library init */
static int
our_init(int argc, char **argv, char **envp)
{
/* If we do not want to use drpreload.so, we can take over here: but when using
* drpreload, this is called *after* we have already taken over.
*/
extern void dynamorio_app_take_over(void);
bool takeover = false;
#ifdef INIT_TAKE_OVER
takeover = true;
#endif
#ifdef VMX86_SERVER
/* PR 391765: take over here instead of using preload */
takeover = os_in_vmkernel_classic();
#endif
#ifndef STATIC_LIBRARY
if (our_environ != NULL) {
/* Set by dynamorio_set_envp above. These should agree. */
ASSERT(our_environ == envp);
} else {
our_environ = envp;
}
#endif
/* if using preload, no -early_inject */
#ifdef STATIC_LIBRARY
if (!takeover) {
const char *takeover_env = getenv("DYNAMORIO_TAKEOVER_IN_INIT");
if (takeover_env != NULL && strcmp(takeover_env, "1") == 0) {
takeover = true;
}
}
#endif
if (takeover) {
if (dynamorio_app_init() == 0 /* success */) {
dynamorio_app_take_over();
}
}
return 0;
}
#if defined(STATIC_LIBRARY) || defined(STANDALONE_UNIT_TEST)
/* If we're getting linked into a binary that already has an _init definition
* like the app's exe or unit_tests, we add a pointer to our_init() to the
* .init_array section. We can't use the constructor attribute because not all
* toolchains pass the args and environment to the constructor.
*/
static init_fn_t
# ifdef MACOS
__attribute__((section("__DATA,__mod_init_func"), aligned(sizeof(void *)), used))
# else
__attribute__((section(".init_array"), aligned(sizeof(void *)), used))
# endif
init_array[] = { our_init };
#else
/* If we're a normal shared object, then we override _init.
*/
int
_init(int argc, char **argv, char **envp)
{
# ifdef ANDROID
/* i#1862: the Android loader passes *nothing* to lib init routines. We
* rely on DR being listed before libc so we can read the TLS slot the
* kernel set up.
*/
if (!get_kernel_args(&argc, &argv, &envp)) {
/* XXX: scan the stack and look for known auxv patterns or sthg. */
argc = 0;
argv = NULL;
envp = NULL;
}
ASSERT_MESSAGE(CHKLVL_ASSERTS, "failed to find envp", envp != NULL);
# endif
return our_init(argc, argv, envp);
}
#endif
bool
kernel_is_64bit(void)
{
return kernel_64bit;
}
#ifdef MACOS
/* XXX: if we get enough of these, move to os_macos.c or sthg */
static bool
sysctl_query(int level0, int level1, void *buf, size_t bufsz)
{
int res;
int name[2];
size_t len = bufsz;
name[0] = level0;
name[1] = level1;
res = dynamorio_syscall(SYS___sysctl, 6, &name, 2, buf, &len, NULL, 0);
return (res >= 0);
}
int
os_get_version(void)
{
return macos_version;
}
#endif
static void
get_uname(void)
{
/* assumption: only called at init, so we don't need any synch
* or .data unprot
*/
static struct utsname uinfo; /* can be large, avoid stack overflow */
#ifdef MACOS
if (!sysctl_query(CTL_KERN, KERN_OSTYPE, &uinfo.sysname, sizeof(uinfo.sysname)) ||
!sysctl_query(CTL_KERN, KERN_HOSTNAME, &uinfo.nodename, sizeof(uinfo.nodename)) ||
!sysctl_query(CTL_KERN, KERN_OSRELEASE, &uinfo.release, sizeof(uinfo.release)) ||
!sysctl_query(CTL_KERN, KERN_VERSION, &uinfo.version, sizeof(uinfo.version)) ||
!sysctl_query(CTL_HW, HW_MACHINE, &uinfo.machine, sizeof(uinfo.machine))) {
ASSERT(false && "sysctl queries failed");
return;
}
#else
DEBUG_DECLARE(int res =)
dynamorio_syscall(SYS_uname, 1, (ptr_uint_t)&uinfo);
ASSERT(res >= 0);
#endif
LOG(GLOBAL, LOG_TOP, 1, "uname:\n\tsysname: %s\n", uinfo.sysname);
LOG(GLOBAL, LOG_TOP, 1, "\tnodename: %s\n", uinfo.nodename);
LOG(GLOBAL, LOG_TOP, 1, "\trelease: %s\n", uinfo.release);
LOG(GLOBAL, LOG_TOP, 1, "\tversion: %s\n", uinfo.version);
LOG(GLOBAL, LOG_TOP, 1, "\tmachine: %s\n", uinfo.machine);
if (strncmp(uinfo.machine, "x86_64", sizeof("x86_64")) == 0)
kernel_64bit = true;
#ifdef MACOS
/* XXX: I would skip these checks for standalone so we don't have to set env
* vars for frontends to see the options but I'm still afraid of some syscall
* crash with no output: I'd rather have two messages than silent crashing.
*/
if (DYNAMO_OPTION(max_supported_os_version) != 0) { /* 0 disables */
/* We only support OSX 10.7.5+. That means kernels 11.x+. */
# define MIN_DARWIN_VERSION_SUPPORTED 11
int kernel_major;
if (sscanf(uinfo.release, "%d", &kernel_major) != 1 ||
kernel_major > DYNAMO_OPTION(max_supported_os_version) ||
kernel_major < MIN_DARWIN_VERSION_SUPPORTED) {
/* We make this non-fatal as it's likely DR will work */
SYSLOG(SYSLOG_WARNING, UNSUPPORTED_OS_VERSION, 3, get_application_name(),
get_application_pid(), uinfo.release);
}
macos_version = kernel_major;
}
#endif
}
#if defined(LINUX)
/* For some syscalls, detects whether they are unsupported by the system
* we're running on. Particularly, we are interested in detecting missing
* support early-on for syscalls that require complex pre-syscall handling
* by DR. We use this information to fail early for those syscalls.
*
* XXX: Move other logic for detecting unsupported syscalls from their
* respective locations to here at init time, like that for
* SYS_memfd_create in os_create_memory_file.
*
*/
static void
detect_unsupported_syscalls()
{
/* We know that when clone3 is available, it fails with EINVAL with
* these args.
*/
int clone3_errno =
dynamorio_syscall(SYS_clone3, 2, NULL /*clone_args*/, 0 /*clone_args_size*/);
ASSERT(clone3_errno == -ENOSYS || clone3_errno == -EINVAL);
is_clone3_enosys = clone3_errno == -ENOSYS;
}
#endif
/* os-specific initializations */
void
d_r_os_init(void)
{
ksynch_init();
get_uname();
/* Populate global data caches. */
get_application_name();
get_application_base();
/* determine whether gettid is provided and needed for threads,
* or whether getpid suffices. even 2.4 kernels have gettid
* (maps to getpid), don't have an old enough target to test this.
*/
#ifdef MACOS
kernel_thread_groups = (dynamorio_syscall(SYS_thread_selfid, 0) >= 0);
#else
kernel_thread_groups = (dynamorio_syscall(SYS_gettid, 0) >= 0);
#endif
LOG(GLOBAL, LOG_TOP | LOG_STATS, 1, "thread id is from %s\n",
kernel_thread_groups ? "gettid" : "getpid");
#ifdef MACOS
/* SYS_thread_selfid was added in 10.6. We have no simple way to get the
* thread id on 10.5, so we don't support it.
*/
if (!kernel_thread_groups) {
SYSLOG(SYSLOG_WARNING, UNSUPPORTED_OS_VERSION, 3, get_application_name(),
get_application_pid(), "Mac OSX 10.5 or earlier");
}
#else
ASSERT_CURIOSITY(kernel_thread_groups);
#endif
pid_cached = get_process_id();
#ifdef VMX86_SERVER
vmk_init();
#endif
d_r_signal_init();
/* We now set up an early fault handler for d_r_safe_read() (i#350) */
fault_handling_initialized = true;
memquery_init();
#ifdef PROFILE_RDTSC
if (dynamo_options.profile_times) {
ASSERT_NOT_TESTED();
kilo_hertz = get_timer_frequency();
LOG(GLOBAL, LOG_TOP | LOG_STATS, 1, "CPU MHz is %d\n", kilo_hertz / 1000);
}
#endif /* PROFILE_RDTSC */
/* Needs to be after heap_init */
IF_NO_MEMQUERY(memcache_init());
/* we didn't have heap in os_file_init() so create and add global logfile now */
fd_table = generic_hash_create(
GLOBAL_DCONTEXT, INIT_HTABLE_SIZE_FD, 80 /* load factor: not perf-critical */,
HASHTABLE_SHARED | HASHTABLE_PERSISTENT, NULL _IF_DEBUG("fd table"));
#ifdef DEBUG
if (GLOBAL != INVALID_FILE)
fd_table_add(GLOBAL, OS_OPEN_CLOSE_ON_FORK);
#endif
/* Ensure initialization */
get_dynamorio_dll_start();
#ifdef LINUX
if (DYNAMO_OPTION(emulate_brk))
init_emulated_brk(NULL);
#endif
#ifdef ANDROID
/* This must be set up earlier than privload_tls_init, and must be set up
* for non-client-interface as well, as this initializes DR_TLS_BASE_OFFSET
* (i#1931).
*/
init_android_version();
#endif
#ifdef LINUX
if (!standalone_library)
d_r_rseq_init();
#endif
#ifdef MACOS64
tls_process_init();
#endif
#if defined(LINUX)
detect_unsupported_syscalls();
#endif
}
/* called before any logfiles are opened */
void
os_file_init(void)
{
/* We steal fds from the app for better transparency. We lower the max file
* descriptor limit as viewed by the app, and block SYS_dup{2,3} and
* SYS_fcntl(F_DUPFD*) from creating a file explicitly in our space. We do
* not try to stop incremental file opening from extending into our space:
* if the app really is running out of fds, we'll give it some of ours:
* after all we probably don't need all -steal_fds, and if we really need fds
* we typically open them at startup. We also don't bother watching all
* syscalls that take in fds from affecting our fds.
*/
if (DYNAMO_OPTION(steal_fds) > 0) {
struct rlimit rlimit_nofile;
/* SYS_getrlimit uses an old 32-bit-field struct so we want SYS_ugetrlimit */
if (dynamorio_syscall(
IF_MACOS_ELSE(SYS_getrlimit, IF_X64_ELSE(SYS_getrlimit, SYS_ugetrlimit)),
2, RLIMIT_NOFILE, &rlimit_nofile) != 0) {
/* linux default is 1024 */
SYSLOG_INTERNAL_WARNING("getrlimit RLIMIT_NOFILE failed"); /* can't LOG yet */
rlimit_nofile.rlim_cur = 1024;
rlimit_nofile.rlim_max = 1024;
}
/* pretend the limit is lower and reserve the top spots for us.
* for simplicity and to give as much room as possible to app,
* raise soft limit to equal hard limit.
* if an app really depends on a low soft limit, they can run
* with -steal_fds 0.
*/
if (rlimit_nofile.rlim_max > DYNAMO_OPTION(steal_fds)) {
int res;
min_dr_fd = rlimit_nofile.rlim_max - DYNAMO_OPTION(steal_fds);
app_rlimit_nofile.rlim_max = min_dr_fd;
app_rlimit_nofile.rlim_cur = app_rlimit_nofile.rlim_max;
rlimit_nofile.rlim_cur = rlimit_nofile.rlim_max;
res = dynamorio_syscall(SYS_setrlimit, 2, RLIMIT_NOFILE, &rlimit_nofile);
if (res != 0) {
SYSLOG_INTERNAL_WARNING("unable to raise RLIMIT_NOFILE soft limit: %d",
res);
}
} else /* not fatal: we'll just end up using fds in app space */
SYSLOG_INTERNAL_WARNING("unable to reserve fds");
}
/* we don't have heap set up yet so we init fd_table in os_init */
}
/* we need to re-cache after a fork */
static char *
get_application_pid_helper(bool ignore_cache)
{
static char pidstr[16];
if (!pidstr[0] || ignore_cache) {
int pid = get_process_id();
snprintf(pidstr, sizeof(pidstr) - 1, "%d", pid);
}
return pidstr;
}
/* get application pid, (cached), used for event logging */
char *
get_application_pid()
{
return get_application_pid_helper(false);
}
/* The OSX kernel used to place the bare executable path above envp.
* On recent XNU versions, the kernel now prefixes the executable path
* with the string executable_path= so it can be parsed getenv style.
*/
#ifdef MACOS
# define EXECUTABLE_KEY "executable_path="
#endif
/* i#189: we need to re-cache after a fork */
static char *
get_application_name_helper(bool ignore_cache, bool full_path)
{
if (!executable_path[0] || ignore_cache) {
#ifdef VMX86_SERVER
if (os_in_vmkernel_userworld()) {
vmk_getnamefrompid(pid, executable_path, sizeof(executable_path));
} else
#endif
if (DYNAMO_OPTION(early_inject)) {
ASSERT(executable_path[0] != '\0' &&
"i#907: Can't read /proc/self/exe for early injection");
} else {
#ifdef LINUX
/* Populate cache from /proc/self/exe link. */
strncpy(executable_path, read_proc_self_exe(ignore_cache),
BUFFER_SIZE_ELEMENTS(executable_path));
#else
/* OSX kernel puts full app exec path above envp */
char *c, **env = our_environ;
do {
env++;
} while (*env != NULL);
env++; /* Skip the NULL separating the envp array from exec_path */
c = *env;
if (strncmp(EXECUTABLE_KEY, c, strlen(EXECUTABLE_KEY)) == 0) {
c += strlen(EXECUTABLE_KEY);
}
/* If our frontends always absolute-ize paths prior to exec,
* this should usually be absolute -- but we go ahead and
* handle relative just in case (and to handle child processes).
* We add the cur dir, but note that the resulting path can
* still contain . or .. so it's not normalized (but it is a
* correct absolute path). Xref i#1402, i#1406, i#1407.
*/
if (*c != '/') {
int len;
if (!os_get_current_dir(executable_path,
BUFFER_SIZE_ELEMENTS(executable_path)))
len = 0;
else
len = strlen(executable_path);
snprintf(executable_path + len,
BUFFER_SIZE_ELEMENTS(executable_path) - len, "%s%s",
len > 0 ? "/" : "", c);
} else
strncpy(executable_path, c, BUFFER_SIZE_ELEMENTS(executable_path));
#endif
NULL_TERMINATE_BUFFER(executable_path);
/* FIXME: Fall back on /proc/self/cmdline and maybe argv[0] from
* _init().
*/
ASSERT(strlen(executable_path) > 0 && "readlink /proc/self/exe failed");
}
}
/* Get basename. */
if (executable_basename == NULL || ignore_cache) {
executable_basename = strrchr(executable_path, '/');
executable_basename =
(executable_basename == NULL ? executable_path : executable_basename + 1);
}
return (full_path ? executable_path : executable_basename);
}
/* get application name, (cached), used for event logging */
char *
get_application_name(void)
{
return get_application_name_helper(false, true /* full path */);
}
/* i#907: Called during early injection before data section protection to avoid
* issues with /proc/self/exe.
*/
void
set_executable_path(const char *exe_path)
{
strncpy(executable_path, exe_path, BUFFER_SIZE_ELEMENTS(executable_path));
NULL_TERMINATE_BUFFER(executable_path);
/* Re-compute the basename in case the full path changed. */
get_application_name_helper(true /* re-compute */, false /* basename */);
}
/* Note: this is exported so that libdrpreload.so (preload.c) can use it to
* get process names to do selective process following (PR 212034). The
* alternative is to duplicate or compile in this code into libdrpreload.so,
* which is messy. Besides, libdynamorio.so is already loaded into the process
* and avaiable, so cleaner to just use functions from it.
*/
DYNAMORIO_EXPORT const char *
get_application_short_name(void)
{
return get_application_name_helper(false, false /* short name */);
}
/* Sets pointers to the application's command-line arguments. These pointers are then used
* by get_app_args().
*/
void
set_app_args(IN int *app_argc_in, IN char **app_argv_in)
{
app_argc = app_argc_in;
app_argv = app_argv_in;
}
/* Returns the number of application's command-line arguments. */
int
num_app_args()
{
if (!DYNAMO_OPTION(early_inject)) {
set_client_error_code(NULL, DR_ERROR_NOT_IMPLEMENTED);
return -1;
}
return *app_argc;
}
/* Returns the application's command-line arguments. */
int
get_app_args(OUT dr_app_arg_t *args_array, int args_count)
{
if (args_array == NULL || args_count < 0) {
set_client_error_code(NULL, DR_ERROR_INVALID_PARAMETER);
return -1;
}
if (!DYNAMO_OPTION(early_inject)) {
set_client_error_code(NULL, DR_ERROR_NOT_IMPLEMENTED);
return -1;
}
int num_args = num_app_args();
int min = (args_count < num_args) ? args_count : num_args;
for (int i = 0; i < min; i++) {
args_array[i].start = (void *)app_argv[i];
args_array[i].size = strlen(app_argv[i]) + 1 /* consider NULL byte */;
args_array[i].encoding = DR_APP_ARG_CSTR_COMPAT;
}
return min;
}
/* Processor information provided by kernel */
#define PROC_CPUINFO "/proc/cpuinfo"
#define CPUMHZ_LINE_LENGTH 64
#define CPUMHZ_LINE_FORMAT "cpu MHz\t\t: %lu.%03lu\n"
/* printed in /usr/src/linux-2.4/arch/i386/kernel/setup.c calibrated in time.c */
/* seq_printf(m, "cpu MHz\t\t: %lu.%03lu\n", cpu_khz / 1000, (cpu_khz % 1000)) */
/* e.g. cpu MHz : 1594.851 */
static timestamp_t
get_timer_frequency_cpuinfo(void)
{
file_t cpuinfo;
ssize_t nread;
char *buf;
char *mhz_line;
ulong cpu_mhz = 1000;
ulong cpu_khz = 0;
cpuinfo = os_open(PROC_CPUINFO, OS_OPEN_READ);
/* This can happen in a chroot or if /proc is disabled. */
if (cpuinfo == INVALID_FILE)
return 1000 * 1000; /* 1 GHz */
/* cpu MHz is typically in the first 4096 bytes. If not, or we get a short
* or interrupted read, our timer frequency estimate will be off, but it's
* not the end of the world.
* FIXME: Factor a buffered file reader out of our maps iterator if we want
* to do this the right way.
*/
buf = global_heap_alloc(PAGE_SIZE HEAPACCT(ACCT_OTHER));
nread = os_read(cpuinfo, buf, PAGE_SIZE - 1);
if (nread > 0) {
buf[nread] = '\0';
mhz_line = strstr(buf, "cpu MHz\t\t:");
if (mhz_line != NULL &&
sscanf(mhz_line, CPUMHZ_LINE_FORMAT, &cpu_mhz, &cpu_khz) == 2) {
LOG(GLOBAL, LOG_ALL, 2, "Processor speed exactly %lu.%03luMHz\n", cpu_mhz,
cpu_khz);
}
}
global_heap_free(buf, PAGE_SIZE HEAPACCT(ACCT_OTHER));
os_close(cpuinfo);
return cpu_mhz * 1000 + cpu_khz;
}
timestamp_t
get_timer_frequency()
{
#ifdef VMX86_SERVER
if (os_in_vmkernel_userworld()) {
return vmk_get_timer_frequency();
}
#endif
return get_timer_frequency_cpuinfo();
}
/* DR has standardized on UTC time which counts from since Jan 1, 1601.
* That's the Windows standard. But Linux uses the Epoch of Jan 1, 1970.
*/
#define UTC_TO_EPOCH_SECONDS 11644473600
/* seconds since 1601 */
uint
query_time_seconds(void)
{
struct timeval current_time;
uint64 val = dynamorio_syscall(SYS_gettimeofday, 2, ¤t_time, NULL);
#ifdef MACOS
/* MacOS before Sierra returns usecs:secs and does not set the timeval struct. */
if (macos_version < MACOS_VERSION_SIERRA) {
if ((int)val < 0)
return 0;
return (uint)val + UTC_TO_EPOCH_SECONDS;
}
#endif
if ((int)val >= 0) {
return current_time.tv_sec + UTC_TO_EPOCH_SECONDS;
} else {
ASSERT_NOT_REACHED();
return 0;
}
}
/* milliseconds since 1601 */
uint64
query_time_millis()
{
struct timeval current_time;
uint64 val = dynamorio_syscall(SYS_gettimeofday, 2, ¤t_time, NULL);
#ifdef MACOS
/* MacOS before Sierra returns usecs:secs and does not set the timeval struct. */
if (macos_version < MACOS_VERSION_SIERRA) {
if ((int)val > 0) {
current_time.tv_sec = (uint)val;
current_time.tv_usec = (uint)(val >> 32);
}
}
#endif
if ((int)val >= 0) {
uint64 res =
(((uint64)current_time.tv_sec) * 1000) + (current_time.tv_usec / 1000);
res += UTC_TO_EPOCH_SECONDS * 1000;
return res;
} else {
ASSERT_NOT_REACHED();
return 0;
}
}
/* microseconds since 1601 */
uint64
query_time_micros()
{
struct timeval current_time;
uint64 val = dynamorio_syscall(SYS_gettimeofday, 2, ¤t_time, NULL);
#ifdef MACOS
/* MacOS before Sierra returns usecs:secs and does not set the timeval struct. */
if (macos_version < MACOS_VERSION_SIERRA) {
if ((int)val > 0) {
current_time.tv_sec = (uint)val;
current_time.tv_usec = (uint)(val >> 32);
}
}
#endif
if ((int)val >= 0) {
uint64 res = (((uint64)current_time.tv_sec) * 1000000) + current_time.tv_usec;
res += UTC_TO_EPOCH_SECONDS * 1000000;
return res;
} else {
ASSERT_NOT_REACHED();
return 0;
}
}
#ifdef RETURN_AFTER_CALL
/* Finds the bottom of the call stack, presumably at program startup. */
/* This routine is a copycat of internal_dump_callstack and makes
assumptions about program state, i.e. that frame pointers are valid
and should be used only in well known points for release build.
*/
static app_pc
find_stack_bottom()
{
app_pc retaddr = 0;
int depth = 0;
reg_t *fp;
/* from dump_dr_callstack() */
asm("mov %%" ASM_XBP ", %0" : "=m"(fp));
LOG(THREAD_GET, LOG_ALL, 3, "Find stack bottom:\n");
while (fp != NULL && is_readable_without_exception((byte *)fp, sizeof(reg_t) * 2)) {
retaddr = (app_pc) * (fp + 1); /* presumably also readable */
LOG(THREAD_GET, LOG_ALL, 3,
"\tframe ptr " PFX " => parent " PFX ", ret = " PFX "\n", fp, *fp, retaddr);
depth++;
/* yes I've seen weird recursive cases before */
if (fp == (reg_t *)*fp || depth > 100)
break;
fp = (reg_t *)*fp;
}
return retaddr;
}
#endif /* RETURN_AFTER_CALL */
/* os-specific atexit cleanup */
void
os_slow_exit(void)
{
#ifdef MACOS64
tls_process_exit();
#endif
#ifdef LINUX
if (!standalone_library)
d_r_rseq_exit();
#endif
d_r_signal_exit();
memquery_exit();
ksynch_exit();
generic_hash_destroy(GLOBAL_DCONTEXT, fd_table);
fd_table = NULL;
if (doing_detach) {
vsyscall_page_start = NULL;
IF_DEBUG(num_fd_add_pre_heap = 0;)
}
DELETE_LOCK(set_thread_area_lock);
DELETE_LOCK(client_tls_lock);
IF_NO_MEMQUERY(memcache_exit());
}
/* Helper function that calls cleanup_and_terminate after blocking most signals
*(i#2921).
*/
void
block_cleanup_and_terminate(dcontext_t *dcontext, int sysnum, ptr_uint_t sys_arg1,
ptr_uint_t sys_arg2, bool exitproc,
/* these 2 args are only used for Mac thread exit */
ptr_uint_t sys_arg3, ptr_uint_t sys_arg4)
{
/* This thread is on its way to exit. We are blocking all signals since any
* signal that reaches us now can be delayed until after the exit is complete.
* We may still receive a suspend signal for synchronization that we may need
* to reply to (i#2921).
*/
if (sysnum == SYS_kill)
block_all_noncrash_signals_except(NULL, 2, dcontext->sys_param0, SUSPEND_SIGNAL);
else
block_all_noncrash_signals_except(NULL, 1, SUSPEND_SIGNAL);
cleanup_and_terminate(dcontext, sysnum, sys_arg1, sys_arg2, exitproc, sys_arg3,
sys_arg4);
}
/* os-specific atexit cleanup */
void
os_fast_exit(void)
{
/* nothing */
}
void
os_terminate_with_code(dcontext_t *dcontext, terminate_flags_t flags, int exit_code)
{
/* i#1319: we support a signal via 2nd byte */
bool use_signal = exit_code > 0x00ff;
/* XXX: TERMINATE_THREAD not supported */
ASSERT_NOT_IMPLEMENTED(TEST(TERMINATE_PROCESS, flags));
if (use_signal) {
int sig = (exit_code & 0xff00) >> 8;
os_terminate_via_signal(dcontext, flags, sig);
ASSERT_NOT_REACHED();
}
if (TEST(TERMINATE_CLEANUP, flags)) {
/* we enter from several different places, so rewind until top-level kstat */
KSTOP_REWIND_UNTIL(thread_measured);
block_cleanup_and_terminate(dcontext, SYSNUM_EXIT_PROCESS, exit_code, 0,
true /*whole process*/, 0, 0);
} else {
/* clean up may be impossible - just terminate */
d_r_config_exit(); /* delete .1config file */
exit_process_syscall(exit_code);
}
}
void
os_terminate(dcontext_t *dcontext, terminate_flags_t flags)
{
os_terminate_with_code(dcontext, flags, -1);
}
int
os_timeout(int time_in_milliseconds)
{
ASSERT_NOT_IMPLEMENTED(false);
return 0;
}
/************************************************************************
* SEGMENT STEALING
*
* Not easy to make truly transparent -- but the alternative of dispatch
* by thread id on global memory has performance implications.
* Pull the non-STEAL_SEGMENT code out of the cvs attic for a base if
* transparency becomes more of a problem.
*/
#define TLS_LOCAL_STATE_OFFSET (offsetof(os_local_state_t, state))
/* offset from top of page */
#define TLS_OS_LOCAL_STATE 0x00
#define TLS_SELF_OFFSET (TLS_OS_LOCAL_STATE + offsetof(os_local_state_t, self))
#define TLS_THREAD_ID_OFFSET (TLS_OS_LOCAL_STATE + offsetof(os_local_state_t, tid))
#define TLS_DCONTEXT_OFFSET (TLS_OS_LOCAL_STATE + TLS_DCONTEXT_SLOT)
#ifdef X86
# define TLS_MAGIC_OFFSET (TLS_OS_LOCAL_STATE + offsetof(os_local_state_t, magic))
#endif
/* they should be used with os_tls_offset, so do not need add TLS_OS_LOCAL_STATE here
*/
#define TLS_APP_LIB_TLS_BASE_OFFSET (offsetof(os_local_state_t, app_lib_tls_base))
#define TLS_APP_ALT_TLS_BASE_OFFSET (offsetof(os_local_state_t, app_alt_tls_base))
#define TLS_APP_LIB_TLS_REG_OFFSET (offsetof(os_local_state_t, app_lib_tls_reg))
#define TLS_APP_ALT_TLS_REG_OFFSET (offsetof(os_local_state_t, app_alt_tls_reg))
/* N.B.: imm and offs are ushorts!
* We use %c[0-9] to get gcc to emit an integer constant without a leading $ for
* the segment offset. See the documentation here:
* http://gcc.gnu.org/onlinedocs/gccint/Output-Template.html#Output-Template
* Also, var needs to match the pointer size, or else we'll get stack corruption.
* XXX: This is marked volatile prevent gcc from speculating this code before
* checks for is_thread_tls_initialized(), but if we could find a more
* precise constraint, then the compiler would be able to optimize better. See
* glibc comments on THREAD_SELF.
*/
#ifdef DR_HOST_NOT_TARGET
# define WRITE_TLS_SLOT_IMM(imm, var) var = 0, ASSERT_NOT_REACHED()
# define READ_TLS_SLOT_IMM(imm, var) var = 0, ASSERT_NOT_REACHED()
# define WRITE_TLS_INT_SLOT_IMM(imm, var) var = 0, ASSERT_NOT_REACHED()
# define READ_TLS_INT_SLOT_IMM(imm, var) var = 0, ASSERT_NOT_REACHED()
# define WRITE_TLS_SLOT(offs, var) offs = var ? 0 : 1, ASSERT_NOT_REACHED()
# define READ_TLS_SLOT(offs, var) var = (void *)(ptr_uint_t)offs, ASSERT_NOT_REACHED()
#elif defined(MACOS64)
/* For now we have both a directly-addressable os_local_state_t and a pointer to
* it in slot 6. If we settle on always doing the full os_local_state_t in slots,
* we would probably get rid of the indirection here and directly access slot fields.
*/
# define WRITE_TLS_SLOT_IMM(imm, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(void *)); \
__asm__ __volatile__( \
"mov %%gs:%1, %%" ASM_XAX " \n\t" \
"movq %0, %c2(%%" ASM_XAX ") \n\t" \
: \
: "r"(var), "m"(*(void **)(DR_TLS_BASE_SLOT * sizeof(void *))), "i"(imm) \
: "memory", ASM_XAX);
# define READ_TLS_SLOT_IMM(imm, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(void *)); \
__asm__ __volatile__("mov %%gs:%1, %%" ASM_XAX " \n\t" \
"movq %c2(%%" ASM_XAX "), %0 \n\t" \
: "=r"(var) \
: "m"(*(void **)(DR_TLS_BASE_SLOT * sizeof(void *))), \
"i"(imm) \
: ASM_XAX);
# define WRITE_TLS_SLOT(offs, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
__asm__ __volatile__("mov %%gs:%0, %%" ASM_XAX " \n\t" \
"movzwq %1, %%" ASM_XDX " \n\t" \
"movq %2, (%%" ASM_XAX ", %%" ASM_XDX ") \n\t" \
: \
: "m"(*(void **)(DR_TLS_BASE_SLOT * sizeof(void *))), \
"m"(offs), "r"(var) \
: "memory", ASM_XAX, ASM_XDX);
# define READ_TLS_SLOT(offs, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(void *)); \
__asm__ __volatile__("mov %%gs:%1, %%" ASM_XAX " \n\t" \
"movzwq %2, %%" ASM_XDX " \n\t" \
"movq (%%" ASM_XAX ", %%" ASM_XDX "), %0 \n\t" \
: "=r"(var) \
: "m"(*(void **)(DR_TLS_BASE_SLOT * sizeof(void *))), \
"m"(offs) \
: "memory", ASM_XAX, ASM_XDX);
#elif defined(X86)
# define WRITE_TLS_SLOT_IMM(imm, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(void *)); \
asm volatile("mov %0, %" ASM_SEG ":%c1" : : "r"(var), "i"(imm));
# define READ_TLS_SLOT_IMM(imm, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(void *)); \
asm volatile("mov %" ASM_SEG ":%c1, %0" : "=r"(var) : "i"(imm));
# define WRITE_TLS_INT_SLOT_IMM(imm, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(int)); \
asm volatile("movl %0, %" ASM_SEG ":%c1" : : "r"(var), "i"(imm));
# define READ_TLS_INT_SLOT_IMM(imm, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(int)); \
asm volatile("movl %" ASM_SEG ":%c1, %0" : "=r"(var) : "i"(imm));
/* FIXME: need dedicated-storage var for _TLS_SLOT macros, can't use expr */
# define WRITE_TLS_SLOT(offs, var) \
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED()); \
ASSERT(sizeof(var) == sizeof(void *)); \
ASSERT(sizeof(offs) == 2); \
asm("mov %0, %%" ASM_XAX : : "m"((var)) : ASM_XAX); \
asm("movzw" IF_X64_ELSE("q", "l") " %0, %%" ASM_XDX : : "m"((offs)) : ASM_XDX); \
asm("mov %%" ASM_XAX ", %" ASM_SEG ":(%%" ASM_XDX ")" : : : ASM_XAX, ASM_XDX);
# define READ_TLS_SLOT(offs, var) \
ASSERT(sizeof(var) == sizeof(void *)); \
ASSERT(sizeof(offs) == 2); \
asm("movzw" IF_X64_ELSE("q", "l") " %0, %%" ASM_XAX : : "m"((offs)) : ASM_XAX); \
asm("mov %" ASM_SEG ":(%%" ASM_XAX "), %%" ASM_XAX : : : ASM_XAX); \
asm("mov %%" ASM_XAX ", %0" : "=m"((var)) : : ASM_XAX);
#elif defined(AARCHXX)
/* Android needs indirection through a global. The Android toolchain has
* trouble with relocations if we use a global directly in asm, so we convert to
* a local variable in these macros. We pay the cost of the extra instructions
* for Linux ARM to share the code.
*/
# define WRITE_TLS_SLOT_IMM(imm, var) \
do { \
uint _base_offs = DR_TLS_BASE_OFFSET; \
__asm__ __volatile__("mov " ASM_R2 ", %0 \n\t" READ_TP_TO_R3_DISP_IN_R2 \
"str %1, [" ASM_R3 ", %2] \n\t" \
: \
: "r"(_base_offs), "r"(var), "i"(imm) \
: "memory", ASM_R2, ASM_R3); \
} while (0)
# define READ_TLS_SLOT_IMM(imm, var) \
do { \
uint _base_offs = DR_TLS_BASE_OFFSET; \
__asm__ __volatile__("mov " ASM_R2 ", %1 \n\t" READ_TP_TO_R3_DISP_IN_R2 \
"ldr %0, [" ASM_R3 ", %2] \n\t" \
: "=r"(var) \
: "r"(_base_offs), "i"(imm) \
: ASM_R2, ASM_R3); \
} while (0)
# define WRITE_TLS_INT_SLOT_IMM WRITE_TLS_SLOT_IMM /* b/c 32-bit */
# define READ_TLS_INT_SLOT_IMM READ_TLS_SLOT_IMM /* b/c 32-bit */
# define WRITE_TLS_SLOT(offs, var) \
do { \
uint _base_offs = DR_TLS_BASE_OFFSET; \
__asm__ __volatile__("mov " ASM_R2 ", %0 \n\t" READ_TP_TO_R3_DISP_IN_R2 \
"add " ASM_R3 ", " ASM_R3 ", %2 \n\t" \
"str %1, [" ASM_R3 "] \n\t" \
: \
: "r"(_base_offs), "r"(var), "r"(offs) \
: "memory", ASM_R2, ASM_R3); \
} while (0)
# define READ_TLS_SLOT(offs, var) \
do { \
uint _base_offs = DR_TLS_BASE_OFFSET; \
__asm__ __volatile__("mov " ASM_R2 ", %1 \n\t" READ_TP_TO_R3_DISP_IN_R2 \
"add " ASM_R3 ", " ASM_R3 ", %2 \n\t" \
"ldr %0, [" ASM_R3 "] \n\t" \
: "=r"(var) \
: "r"(_base_offs), "r"(offs) \
: ASM_R2, ASM_R3); \
} while (0)
#endif /* X86/ARM */
#ifdef X86
/* We use this at thread init and exit to make it easy to identify
* whether TLS is initialized (i#2089).
* We assume alignment does not matter.
*/
static os_local_state_t uninit_tls; /* has .magic == 0 */
#endif
static bool
is_thread_tls_initialized(void)
{
#ifdef MACOS64
/* For now we have both a directly-addressable os_local_state_t and a pointer to
* it in slot 6. If we settle on always doing the full os_local_state_t in slots,
* we would probably get rid of the indirection here and directly read the magic
* field from its slot.
*/
byte **tls_swap_slot;
tls_swap_slot = (byte **)get_app_tls_swap_slot_addr();
if (tls_swap_slot == NULL || *tls_swap_slot == NULL ||
*tls_swap_slot == TLS_SLOT_VAL_EXITED)
return false;
return true;
#elif defined(X86)
if (INTERNAL_OPTION(safe_read_tls_init)) {
/* Avoid faults during early init or during exit when we have no handler.
* It's not worth extending the handler as the faults are a perf hit anyway.
* For standalone_library, first_thread_tls_initialized will always be false,
* so we'll return false here and use our check in get_thread_private_dcontext().
*/
if (!first_thread_tls_initialized || last_thread_tls_exited)
return false;
/* i#3535: Avoid races between removing DR's SIGSEGV signal handler and
* detached threads being passed native signals. The detaching thread is
* the one doing all the real cleanup, so we simply avoid any safe reads
* or TLS for detaching threads. This var is not cleared until re-init,
* so we have no race with the end of detach.
*/
if (detacher_tid != INVALID_THREAD_ID && detacher_tid != get_sys_thread_id())
return false;
/* To handle WSL (i#1986) where fs and gs start out equal to ss (0x2b),
* and when the MSR is used having a zero selector, and other complexities,
* we just do a blind safe read as the simplest solution once we're past
* initial init and have a fault handler.
*
* i#2089: to avoid the perf cost of syscalls to verify the tid, and to
* distinguish a fork child from a separate-group thread, we no longer read
* the tid field and check that the TLS belongs to this particular thread:
* instead we rely on clearing the .magic field for child threads and at
* thread exit (to avoid a fault) and we simply check the field here.
* A native app thread is very unlikely to match this.
*/
return safe_read_tls_magic() == TLS_MAGIC_VALID;
} else {
/* XXX i#2089: we're keeping this legacy code around until
* we're confident that the safe read code above is safer, more
* performant, and more robust.
*/
os_local_state_t *os_tls = NULL;
ptr_uint_t cur_seg = read_thread_register(SEG_TLS);
/* Handle WSL (i#1986) where fs and gs start out equal to ss (0x2b) */
if (cur_seg != 0 && cur_seg != read_thread_register(SEG_SS)) {
/* XXX: make this a safe read: but w/o dcontext we need special asm support */
READ_TLS_SLOT_IMM(TLS_SELF_OFFSET, os_tls);
}
# ifdef X64
if (os_tls == NULL && tls_dr_using_msr()) {
/* When the MSR is used, the selector in the register remains 0.
* We can't clear the MSR early in a new thread and then look for
* a zero base here b/c if kernel decides to use GDT that zeroing
* will set the selector, unless we want to assume we know when
* the kernel uses the GDT.
* Instead we make a syscall to get the tid. This should be ok
* perf-wise b/c the common case is the non-zero above.
*/
byte *base = tls_get_fs_gs_segment_base(SEG_TLS);
ASSERT(tls_global_type == TLS_TYPE_ARCH_PRCTL);
if (base != (byte *)POINTER_MAX && base != NULL) {
os_tls = (os_local_state_t *)base;
}
}
# endif
if (os_tls != NULL) {
return (os_tls->tid == get_sys_thread_id() ||
/* The child of a fork will initially come here */
os_tls->state.spill_space.dcontext->owning_process ==
get_parent_id());
} else
return false;
}
#elif defined(AARCHXX)
byte **dr_tls_base_addr;
if (tls_global_type == TLS_TYPE_NONE)
return false;
dr_tls_base_addr = (byte **)get_dr_tls_base_addr();
if (dr_tls_base_addr == NULL || *dr_tls_base_addr == NULL ||
/* We use the TLS slot's value to identify a now-exited thread (i#1578) */
*dr_tls_base_addr == TLS_SLOT_VAL_EXITED)
return false;
/* We would like to ASSERT is_dynamo_address(*tls_swap_slot) but that leads
* to infinite recursion for an address not in the vm_reserve area, as
* dynamo_vm_areas_start_reading() ending up calling
* deadlock_avoidance_unlock() which calls get_thread_private_dcontext()
* which comes here.
*/
return true;
#endif
}
bool
is_DR_segment_reader_entry(app_pc pc)
{
/* This routine is used to avoid problems with dr_prepopulate_cache() building
* bbs for DR code that reads DR segments when DR is a static library.
* It's a little ugly but it's not clear there's a better solution.
* See the discussion in i#2463 c#2.
*/
#ifdef X86
if (INTERNAL_OPTION(safe_read_tls_init)) {
return pc == (app_pc)safe_read_tls_magic || pc == (app_pc)safe_read_tls_self;
}
#endif
/* XXX i#2463: for ARM and for -no_safe_read_tls_init it may be
* more complicated as the PC may not be a function entry but the
* start of a bb after a branch in our C code that uses inline asm
* to read the TLS.
*/
return false;
}
#if defined(X86) || defined(DEBUG)
static bool
is_thread_tls_allocated(void)
{
# if defined(X86) && !defined(MACOS64)
if (INTERNAL_OPTION(safe_read_tls_init)) {
/* We use this routine to allow currently-native threads, for which
* is_thread_tls_initialized() (and thus is_thread_initialized()) will
* return false.
* Caution: this will also return true on a fresh clone child.
*/
uint magic;
if (!first_thread_tls_initialized || last_thread_tls_exited)
return false;
magic = safe_read_tls_magic();
return magic == TLS_MAGIC_VALID || magic == TLS_MAGIC_INVALID;
}
# endif
return is_thread_tls_initialized();
}
#endif
/* converts a local_state_t offset to a segment offset */
ushort
os_tls_offset(ushort tls_offs)
{
/* no ushort truncation issues b/c TLS_LOCAL_STATE_OFFSET is 0 */
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(TLS_LOCAL_STATE_OFFSET == 0);
return (TLS_LOCAL_STATE_OFFSET + tls_offs IF_MACOS64(+tls_get_dr_offs()));
}
/* converts a segment offset to a local_state_t offset */
ushort
os_local_state_offset(ushort seg_offs)
{
/* no ushort truncation issues b/c TLS_LOCAL_STATE_OFFSET is 0 */
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(TLS_LOCAL_STATE_OFFSET == 0);
return (seg_offs - TLS_LOCAL_STATE_OFFSET IF_MACOS64(-tls_get_dr_offs()));
}
/* XXX: Will return NULL if called before os_thread_init(), which sets
* ostd->dr_fs/gs_base.
*/
void *
os_get_priv_tls_base(dcontext_t *dcontext, reg_id_t reg)
{
os_thread_data_t *ostd;
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(reg == TLS_REG_ALT || reg == TLS_REG_LIB);
if (dcontext == NULL)
dcontext = get_thread_private_dcontext();
if (dcontext == NULL)
return NULL;
ostd = (os_thread_data_t *)dcontext->os_field;
if (reg == TLS_REG_LIB)
return ostd->priv_lib_tls_base;
else if (reg == TLS_REG_ALT)
return ostd->priv_alt_tls_base;
ASSERT_NOT_REACHED();
return NULL;
}
os_local_state_t *
get_os_tls(void)
{
os_local_state_t *os_tls;
ASSERT(is_thread_tls_initialized());
READ_TLS_SLOT_IMM(TLS_SELF_OFFSET, os_tls);
return os_tls;
}
/* Obtain TLS from dcontext directly, which succeeds in pre-thread-init
* situations where get_os_tls() fails.
*/
static os_local_state_t *
get_os_tls_from_dc(dcontext_t *dcontext)
{
byte *local_state;
ASSERT(dcontext != NULL);
local_state = (byte *)dcontext->local_state;
if (local_state == NULL)
return NULL;
return (os_local_state_t *)(local_state - offsetof(os_local_state_t, state));
}
#ifdef AARCHXX
bool
os_set_app_tls_base(dcontext_t *dcontext, reg_id_t reg, void *base)
{
os_local_state_t *os_tls;
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(reg == TLS_REG_LIB || reg == TLS_REG_ALT);
if (dcontext == NULL)
dcontext = get_thread_private_dcontext();
/* we will be called only if TLS is initialized */
ASSERT(dcontext != NULL);
os_tls = get_os_tls_from_dc(dcontext);
if (reg == TLS_REG_LIB) {
os_tls->app_lib_tls_base = base;
LOG(THREAD, LOG_THREADS, 1, "TLS app lib base =" PFX "\n", base);
return true;
} else if (reg == TLS_REG_ALT) {
os_tls->app_alt_tls_base = base;
LOG(THREAD, LOG_THREADS, 1, "TLS app alt base =" PFX "\n", base);
return true;
}
ASSERT_NOT_REACHED();
return false;
}
#endif
void *
os_get_app_tls_base(dcontext_t *dcontext, reg_id_t reg)
{
os_local_state_t *os_tls;
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(reg == TLS_REG_LIB || reg == TLS_REG_ALT);
if (dcontext == NULL)
dcontext = get_thread_private_dcontext();
if (dcontext == NULL) {
/* No dcontext means we haven't initialized TLS, so we haven't replaced
* the app's segments. get_segment_base is expensive, but this should
* be rare. Re-examine if it pops up in a profile.
*/
return get_segment_base(reg);
}
os_tls = get_os_tls_from_dc(dcontext);
if (reg == TLS_REG_LIB)
return os_tls->app_lib_tls_base;
else if (reg == TLS_REG_ALT)
return os_tls->app_alt_tls_base;
ASSERT_NOT_REACHED();
return NULL;
}
ushort
os_get_app_tls_base_offset(reg_id_t reg)
{
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(TLS_LOCAL_STATE_OFFSET == 0);
if (reg == TLS_REG_LIB)
return TLS_APP_LIB_TLS_BASE_OFFSET;
else if (reg == TLS_REG_ALT)
return TLS_APP_ALT_TLS_BASE_OFFSET;
ASSERT_NOT_REACHED();
return 0;
}
#ifdef X86
ushort
os_get_app_tls_reg_offset(reg_id_t reg)
{
IF_NOT_HAVE_TLS(ASSERT_NOT_REACHED());
ASSERT(TLS_LOCAL_STATE_OFFSET == 0);
if (reg == TLS_REG_LIB)
return TLS_APP_LIB_TLS_REG_OFFSET;
else if (reg == TLS_REG_ALT)
return TLS_APP_ALT_TLS_REG_OFFSET;
ASSERT_NOT_REACHED();
return 0;
}
#endif
void *
d_r_get_tls(ushort tls_offs)
{
void *val;
READ_TLS_SLOT(tls_offs, val);
return val;
}
void
d_r_set_tls(ushort tls_offs, void *value)
{
WRITE_TLS_SLOT(tls_offs, value);
}
/* Returns POINTER_MAX on failure.
* Assumes that cs, ss, ds, and es are flat.
* Should we export this to clients? For now they can get
* this information via opnd_compute_address().
*/
byte *
get_segment_base(uint seg)
{
#ifdef MACOS64
ptr_uint_t *pthread_self = (ptr_uint_t *)read_thread_register(seg);
return (byte *)&pthread_self[SEG_TLS_BASE_OFFSET];
#elif defined(X86)
if (seg == SEG_CS || seg == SEG_SS || seg == SEG_DS || seg == SEG_ES)
return NULL;
# ifdef HAVE_TLS
return tls_get_fs_gs_segment_base(seg);
# else
return (byte *)POINTER_MAX;
# endif /* HAVE_TLS */
#elif defined(AARCHXX)
/* XXX i#1551: should we rename/refactor to avoid "segment"? */
return (byte *)read_thread_register(seg);
#endif
}
/* i#572: handle opnd_compute_address to return the application
* segment base value.
*/
byte *
get_app_segment_base(uint seg)
{
#ifdef X86
if (seg == SEG_CS || seg == SEG_SS || seg == SEG_DS || seg == SEG_ES)
return NULL;
#endif /* X86 */
if (INTERNAL_OPTION(private_loader) && first_thread_tls_initialized &&
!last_thread_tls_exited) {
return d_r_get_tls(os_get_app_tls_base_offset(seg));
}
return get_segment_base(seg);
}
local_state_extended_t *
get_local_state_extended()
{
os_local_state_t *os_tls;
ASSERT(is_thread_tls_initialized());
READ_TLS_SLOT_IMM(TLS_SELF_OFFSET, os_tls);
return &(os_tls->state);
}
local_state_t *
get_local_state()
{
#ifdef HAVE_TLS
return (local_state_t *)get_local_state_extended();
#else
return NULL;
#endif
}
#ifdef DEBUG
void
os_enter_dynamorio(void)
{
# ifdef ARM
/* i#1578: check that app's tls value doesn't match our sentinel */
ASSERT(*(byte **)get_dr_tls_base_addr() != TLS_SLOT_VAL_EXITED);
# endif
}
#endif
/* i#107: handle segment register usage conflicts between app and dr:
* os_handle_mov_seg updates the app's tls selector maintained by DR.
* It is called before entering code cache in dispatch_enter_fcache.
*/
void
os_handle_mov_seg(dcontext_t *dcontext, byte *pc)
{
#ifdef X86
instr_t instr;
opnd_t opnd;
reg_id_t seg;
ushort sel = 0;
our_modify_ldt_t *desc;
int desc_idx;
os_local_state_t *os_tls;
os_thread_data_t *ostd;
instr_init(dcontext, &instr);
decode_cti(dcontext, pc, &instr);
/* the first instr must be mov seg */
ASSERT(instr_get_opcode(&instr) == OP_mov_seg);
opnd = instr_get_dst(&instr, 0);
ASSERT(opnd_is_reg(opnd));
seg = opnd_get_reg(opnd);
ASSERT(reg_is_segment(seg));
ostd = (os_thread_data_t *)dcontext->os_field;
desc = (our_modify_ldt_t *)ostd->app_thread_areas;
os_tls = get_os_tls();
/* get the selector value */
opnd = instr_get_src(&instr, 0);
if (opnd_is_reg(opnd)) {
sel = (ushort)reg_get_value_priv(opnd_get_reg(opnd), get_mcontext(dcontext));
} else {
void *ptr;
ptr = (ushort *)opnd_compute_address_priv(opnd, get_mcontext(dcontext));
ASSERT(ptr != NULL);
if (!d_r_safe_read(ptr, sizeof(sel), &sel)) {
/* FIXME: if invalid address, should deliver a signal to user. */
ASSERT_NOT_IMPLEMENTED(false);
}
}
/* calculate the entry_number */
desc_idx = SELECTOR_INDEX(sel) - tls_min_index();
if (seg == TLS_REG_LIB) {
os_tls->app_lib_tls_reg = sel;
os_tls->app_lib_tls_base = (void *)(ptr_uint_t)desc[desc_idx].base_addr;
} else {
os_tls->app_alt_tls_reg = sel;
os_tls->app_alt_tls_base = (void *)(ptr_uint_t)desc[desc_idx].base_addr;
}
instr_free(dcontext, &instr);
LOG(THREAD_GET, LOG_THREADS, 2,
"thread " TIDFMT " segment change %s to selector 0x%x => "
"app lib tls base: " PFX ", alt tls base: " PFX "\n",
d_r_get_thread_id(), reg_names[seg], sel, os_tls->app_lib_tls_base,
os_tls->app_alt_tls_base);
#elif defined(ARM)
/* FIXME i#1551: NYI on ARM */
ASSERT_NOT_REACHED();
#endif /* X86/ARM */
}
/* Initialization for TLS mangling (-mangle_app_seg on x86).
* Must be called before DR setup its own segment.
*/
static void
os_tls_app_seg_init(os_local_state_t *os_tls, void *segment)
{
app_pc app_lib_tls_base, app_alt_tls_base;
#if defined(X86) && !defined(MACOS64)
int i, index;
our_modify_ldt_t *desc;
os_tls->app_lib_tls_reg = read_thread_register(TLS_REG_LIB);
os_tls->app_alt_tls_reg = read_thread_register(TLS_REG_ALT);
#endif
app_lib_tls_base = get_segment_base(TLS_REG_LIB);
app_alt_tls_base = get_segment_base(TLS_REG_ALT);
/* If we're a non-initial thread, tls will be set to the parent's value,
* or to &uninit_tls (i#2089), both of which will be is_dynamo_address().
*/
os_tls->app_lib_tls_base =
is_dynamo_address(app_lib_tls_base) ? NULL : app_lib_tls_base;
os_tls->app_alt_tls_base =
is_dynamo_address(app_alt_tls_base) ? NULL : app_alt_tls_base;
#if defined(X86) && !defined(MACOS64)
/* get all TLS thread area value */
/* XXX: is get_thread_area supported in 64-bit kernel?
* It has syscall number 211.
* It works for a 32-bit application running in a 64-bit kernel.
* It returns error value -38 for a 64-bit app in a 64-bit kernel.
*/
desc = &os_tls->os_seg_info.app_thread_areas[0];
tls_initialize_indices(os_tls);
index = tls_min_index();
for (i = 0; i < GDT_NUM_TLS_SLOTS; i++) {
tls_get_descriptor(i + index, &desc[i]);
}
#endif /* X86 */
os_tls->os_seg_info.dr_tls_base = segment;
os_tls->os_seg_info.priv_alt_tls_base = IF_X86_ELSE(segment, NULL);
/* now allocate the tls segment for client libraries */
if (INTERNAL_OPTION(private_loader)) {
os_tls->os_seg_info.priv_lib_tls_base = IF_UNIT_TEST_ELSE(
os_tls->app_lib_tls_base, privload_tls_init(os_tls->app_lib_tls_base));
}
#if defined(X86) && !defined(MACOSX64)
LOG(THREAD_GET, LOG_THREADS, 1,
"thread " TIDFMT " app lib tls reg: 0x%x, alt tls reg: 0x%x\n",
d_r_get_thread_id(), os_tls->app_lib_tls_reg, os_tls->app_alt_tls_reg);
#endif
LOG(THREAD_GET, LOG_THREADS, 1,
"thread " TIDFMT " app lib tls base: " PFX ", alt tls base: " PFX "\n",
d_r_get_thread_id(), os_tls->app_lib_tls_base, os_tls->app_alt_tls_base);
LOG(THREAD_GET, LOG_THREADS, 1,
"thread " TIDFMT " priv lib tls base: " PFX ", alt tls base: " PFX ", "
"DR's tls base: " PFX "\n",
d_r_get_thread_id(), os_tls->os_seg_info.priv_lib_tls_base,
os_tls->os_seg_info.priv_alt_tls_base, os_tls->os_seg_info.dr_tls_base);
}
void
os_tls_init(void)
{
#ifdef X86
ASSERT(TLS_MAGIC_OFFSET_ASM == TLS_MAGIC_OFFSET);
ASSERT(TLS_SELF_OFFSET_ASM == TLS_SELF_OFFSET);
#endif
#ifdef HAVE_TLS
/* We create a 1-page segment with an LDT entry for each thread and load its
* selector into fs/gs.
* FIXME PR 205276: this whole scheme currently does not check if app is using
* segments need to watch modify_ldt syscall
*/
# ifdef MACOS64
/* Today we're allocating enough contiguous TLS slots to hold os_local_state_t.
* We also store a pointer to it in TLS slot 6.
*/
byte *segment = tls_get_dr_addr();
# else
byte *segment = heap_mmap(PAGE_SIZE, MEMPROT_READ | MEMPROT_WRITE,
VMM_SPECIAL_MMAP | VMM_PER_THREAD);
# endif
os_local_state_t *os_tls = (os_local_state_t *)segment;
LOG(GLOBAL, LOG_THREADS, 1, "os_tls_init for thread " TIDFMT "\n",
d_r_get_thread_id());
ASSERT(!is_thread_tls_initialized());
/* MUST zero out dcontext slot so uninit access gets NULL */
memset(segment, 0, PAGE_SIZE);
/* store key data in the tls itself */
os_tls->self = os_tls;
os_tls->tid = get_sys_thread_id();
os_tls->tls_type = TLS_TYPE_NONE;
# ifdef X86
os_tls->magic = TLS_MAGIC_VALID;
# endif
/* We save DR's TLS segment base here so that os_get_dr_tls_base() will work
* even when -no_mangle_app_seg is set. If -mangle_app_seg is set, this
* will be overwritten in os_tls_app_seg_init().
*/
os_tls->os_seg_info.dr_tls_base = segment;
ASSERT(proc_is_cache_aligned(os_tls->self + TLS_LOCAL_STATE_OFFSET));
/* Verify that local_state_extended_t should indeed be used. */
ASSERT(DYNAMO_OPTION(ibl_table_in_tls));
/* initialize DR TLS seg base before replacing app's TLS in tls_thread_init */
if (MACHINE_TLS_IS_DR_TLS)
os_tls_app_seg_init(os_tls, segment);
tls_thread_init(os_tls, segment);
ASSERT(os_tls->tls_type != TLS_TYPE_NONE);
/* store type in global var for convenience: should be same for all threads */
tls_global_type = os_tls->tls_type;
/* FIXME: this should be a SYSLOG fatal error? Should fall back on !HAVE_TLS?
* Should have create_ldt_entry() return failure instead of asserting, then.
*/
#else
tls_table = (tls_slot_t *)global_heap_alloc(MAX_THREADS *
sizeof(tls_slot_t) HEAPACCT(ACCT_OTHER));
memset(tls_table, 0, MAX_THREADS * sizeof(tls_slot_t));
#endif
if (!first_thread_tls_initialized) {
first_thread_tls_initialized = true;
if (last_thread_tls_exited) /* re-attach */
last_thread_tls_exited = false;
}
ASSERT(is_thread_tls_initialized());
}
static bool
should_zero_tls_at_thread_exit()
{
#ifdef X86
/* i#2089: For a thread w/o CLONE_SIGHAND we cannot handle a fault, so we want to
* leave &uninit_tls (which was put in place in os_thread_exit()) as long as
* possible. For non-detach, that means until the exit.
*/
return !INTERNAL_OPTION(safe_read_tls_init) || doing_detach;
#else
return true;
#endif
}
/* TLS exit for the current thread who must own local_state. */
void
os_tls_thread_exit(local_state_t *local_state)
{
#ifdef HAVE_TLS
/* We assume (assert below) that local_state_t's start == local_state_extended_t */
os_local_state_t *os_tls =
(os_local_state_t *)(((byte *)local_state) - offsetof(os_local_state_t, state));
tls_type_t tls_type = os_tls->tls_type;
int index = os_tls->ldt_index;
ASSERT(offsetof(local_state_t, spill_space) ==
offsetof(local_state_extended_t, spill_space));
if (should_zero_tls_at_thread_exit()) {
tls_thread_free(tls_type, index);
# if defined(X86) && defined(X64) && !defined(MACOS)
if (tls_type == TLS_TYPE_ARCH_PRCTL) {
/* syscall re-sets gs register so re-clear it */
if (read_thread_register(SEG_TLS) != 0) {
static const ptr_uint_t zero = 0;
WRITE_DR_SEG(zero); /* macro needs lvalue! */
}
}
# endif
}
/* We already set TLS to &uninit_tls in os_thread_exit() */
/* Do not set last_thread_tls_exited if a client_thread is exiting.
* If set, get_thread_private_dcontext() returns NULL, which may cause
* other thread fault on using dcontext.
*/
if (dynamo_exited_all_other_threads && !last_thread_tls_exited) {
last_thread_tls_exited = true;
first_thread_tls_initialized = false; /* for possible re-attach */
}
#endif
}
/* Frees local_state. If the calling thread is exiting (i.e.,
* !other_thread) then also frees kernel resources for the calling
* thread; if other_thread then that may not be possible.
*/
void
os_tls_exit(local_state_t *local_state, bool other_thread)
{
#ifdef HAVE_TLS
# if defined(X86) && !defined(MACOS64)
static const ptr_uint_t zero = 0;
# endif /* X86 */
/* We can't read from fs: as we can be called from other threads */
# if defined(X86) && !defined(MACOS64)
/* If the MSR is in use, writing to the reg faults. We rely on it being 0
* to indicate that.
*/
if (!other_thread && read_thread_register(SEG_TLS) != 0 &&
should_zero_tls_at_thread_exit()) {
WRITE_DR_SEG(zero); /* macro needs lvalue! */
}
# endif /* X86 */
/* For another thread we can't really make these syscalls so we have to
* leave it un-cleaned-up. That's fine if the other thread is exiting:
* but for detach (i#95) we get the other thread to run this code.
*/
if (!other_thread)
os_tls_thread_exit(local_state);
# ifndef MACOS64
/* We can't free prior to tls_thread_free() in case that routine refs os_tls */
/* ASSUMPTION: local_state_t is laid out at same start as local_state_extended_t */
os_local_state_t *os_tls =
(os_local_state_t *)(((byte *)local_state) - offsetof(os_local_state_t, state));
heap_munmap(os_tls->self, PAGE_SIZE, VMM_SPECIAL_MMAP | VMM_PER_THREAD);
# endif
#else
global_heap_free(tls_table, MAX_THREADS * sizeof(tls_slot_t) HEAPACCT(ACCT_OTHER));
DELETE_LOCK(tls_lock);
#endif
}
static int
os_tls_get_gdt_index(dcontext_t *dcontext)
{
os_local_state_t *os_tls = (os_local_state_t *)(((byte *)dcontext->local_state) -
offsetof(os_local_state_t, state));
if (os_tls->tls_type == TLS_TYPE_GDT)
return os_tls->ldt_index;
else
return -1;
}
void
os_tls_pre_init(int gdt_index)
{
#if defined(X86) && !defined(MACOS64)
/* Only set to above 0 for tls_type == TLS_TYPE_GDT */
if (gdt_index > 0) {
/* PR 458917: clear gdt slot to avoid leak across exec */
DEBUG_DECLARE(bool ok;)
static const ptr_uint_t zero = 0;
/* Be sure to clear the selector before anything that might
* call get_thread_private_dcontext()
*/
WRITE_DR_SEG(zero); /* macro needs lvalue! */
DEBUG_DECLARE(ok =)
tls_clear_descriptor(gdt_index);
ASSERT(ok);
}
#elif defined(ARM)
/* FIXME i#1551: NYI on ARM */
ASSERT_NOT_IMPLEMENTED(false);
#endif /* X86/ARM */
}
/* Allocates num_slots tls slots aligned with alignment align */
bool
os_tls_calloc(OUT uint *offset, uint num_slots, uint alignment)
{
bool res = false;
uint i, count = 0;
int start = -1;
uint offs = offsetof(os_local_state_t, client_tls);
if (num_slots == 0 || num_slots > MAX_NUM_CLIENT_TLS)
return false;
d_r_mutex_lock(&client_tls_lock);
for (i = 0; i < MAX_NUM_CLIENT_TLS; i++) {
if (!client_tls_allocated[i] &&
/* ALIGNED doesn't work for 0 */
(alignment == 0 || ALIGNED(offs + i * sizeof(void *), alignment))) {
if (start == -1)
start = i;
count++;
if (count >= num_slots)
break;
} else {
start = -1;
count = 0;
}
}
if (count >= num_slots) {
for (i = 0; i < num_slots; i++)
client_tls_allocated[i + start] = true;
*offset = offs + start * sizeof(void *);
res = true;
}
d_r_mutex_unlock(&client_tls_lock);
return res;
}
bool
os_tls_cfree(uint offset, uint num_slots)
{
uint i;
uint offs = (offset - offsetof(os_local_state_t, client_tls)) / sizeof(void *);
bool ok = true;
d_r_mutex_lock(&client_tls_lock);
for (i = 0; i < num_slots; i++) {
if (!client_tls_allocated[i + offs])
ok = false;
client_tls_allocated[i + offs] = false;
}
d_r_mutex_unlock(&client_tls_lock);
return ok;
}
/* os_data is a clone_record_t for signal_thread_inherit */
void
os_thread_init(dcontext_t *dcontext, void *os_data)
{
os_local_state_t *os_tls = get_os_tls();
os_thread_data_t *ostd = (os_thread_data_t *)heap_alloc(
dcontext, sizeof(os_thread_data_t) HEAPACCT(ACCT_OTHER));
dcontext->os_field = (void *)ostd;
/* make sure stack fields, etc. are 0 now so they can be initialized on demand
* (don't have app esp register handy here to init now)
*/
memset(ostd, 0, sizeof(*ostd));
ksynch_init_var(&ostd->suspended);
ksynch_init_var(&ostd->wakeup);
ksynch_init_var(&ostd->resumed);
ksynch_init_var(&ostd->terminated);
ksynch_init_var(&ostd->detached);
#ifdef RETURN_AFTER_CALL
/* We only need the stack bottom for the initial thread, and due to thread
* init now preceding vm_areas_init(), we initialize in find_executable_vm_areas()
*/
ostd->stack_bottom_pc = NULL;
#endif
ASSIGN_INIT_LOCK_FREE(ostd->suspend_lock, suspend_lock);
signal_thread_init(dcontext, os_data);
/* i#107, initialize thread area information,
* the value was first get in os_tls_init and stored in os_tls
*/
ostd->priv_lib_tls_base = os_tls->os_seg_info.priv_lib_tls_base;
ostd->priv_alt_tls_base = os_tls->os_seg_info.priv_alt_tls_base;
ostd->dr_tls_base = os_tls->os_seg_info.dr_tls_base;
LOG(THREAD, LOG_THREADS, 1, "TLS app lib base =" PFX "\n", os_tls->app_lib_tls_base);
LOG(THREAD, LOG_THREADS, 1, "TLS app alt base =" PFX "\n", os_tls->app_alt_tls_base);
LOG(THREAD, LOG_THREADS, 1, "TLS priv lib base =" PFX "\n", ostd->priv_lib_tls_base);
LOG(THREAD, LOG_THREADS, 1, "TLS priv alt base =" PFX "\n", ostd->priv_alt_tls_base);
LOG(THREAD, LOG_THREADS, 1, "TLS DynamoRIO base=" PFX "\n", ostd->dr_tls_base);
#ifdef X86
if (INTERNAL_OPTION(mangle_app_seg)) {
ostd->app_thread_areas = heap_alloc(
dcontext, sizeof(our_modify_ldt_t) * GDT_NUM_TLS_SLOTS HEAPACCT(ACCT_OTHER));
memcpy(ostd->app_thread_areas, os_tls->os_seg_info.app_thread_areas,
sizeof(our_modify_ldt_t) * GDT_NUM_TLS_SLOTS);
}
#endif
LOG(THREAD, LOG_THREADS, 1, "post-TLS-setup, cur %s base is " PFX "\n",
IF_X86_ELSE("gs", "tpidruro"),
get_segment_base(IF_X86_ELSE(SEG_GS, DR_REG_TPIDRURO)));
LOG(THREAD, LOG_THREADS, 1, "post-TLS-setup, cur %s base is " PFX "\n",
IF_X86_ELSE("fs", "tpidrurw"),
get_segment_base(IF_X86_ELSE(SEG_FS, DR_REG_TPIDRURW)));
#ifdef MACOS
/* XXX: do we need to free/close dcontext->thread_port? I don't think so. */
dcontext->thread_port = dynamorio_mach_syscall(MACH_thread_self_trap, 0);
LOG(THREAD, LOG_ALL, 1, "Mach thread port: %d\n", dcontext->thread_port);
#endif
}
/* os_data is a clone_record_t for signal_thread_inherit */
void
os_thread_init_finalize(dcontext_t *dcontext, void *os_data)
{
/* We do not want to record pending signals until at least synch_thread_init()
* is finished so we delay until here: but we need this inside the
* thread_initexit_lock (i#2779).
*/
signal_thread_inherit(dcontext, os_data);
}
void
os_thread_exit(dcontext_t *dcontext, bool other_thread)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
/* i#237/PR 498284: if we had a vfork child call execve we need to clean up
* the env vars.
*/
if (dcontext->thread_record->execve)
handle_execve_post(dcontext);
DELETE_LOCK(ostd->suspend_lock);
signal_thread_exit(dcontext, other_thread);
ksynch_free_var(&ostd->suspended);
ksynch_free_var(&ostd->wakeup);
ksynch_free_var(&ostd->resumed);
ksynch_free_var(&ostd->terminated);
ksynch_free_var(&ostd->detached);
#ifdef X86
if (ostd->clone_tls != NULL) {
if (!other_thread) {
/* Avoid faults in is_thread_tls_initialized() */
/* FIXME i#2088: we need to restore the app's aux seg, if any, instead. */
os_set_dr_tls_base(dcontext, NULL, (byte *)&uninit_tls);
}
/* We have to free in release build too b/c "local unprotected" is global. */
HEAP_TYPE_FREE(dcontext, ostd->clone_tls, os_local_state_t, ACCT_THREAD_MGT,
UNPROTECTED);
}
#endif
if (INTERNAL_OPTION(private_loader))
privload_tls_exit(IF_UNIT_TEST_ELSE(NULL, ostd->priv_lib_tls_base));
/* for non-debug we do fast exit path and don't free local heap */
DODEBUG({
if (MACHINE_TLS_IS_DR_TLS) {
#ifdef X86
heap_free(dcontext, ostd->app_thread_areas,
sizeof(our_modify_ldt_t) * GDT_NUM_TLS_SLOTS HEAPACCT(ACCT_OTHER));
#endif
}
heap_free(dcontext, ostd, sizeof(os_thread_data_t) HEAPACCT(ACCT_OTHER));
});
}
/* Happens in the parent prior to fork. */
static void
os_fork_pre(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
/* Otherwise a thread might wait for us. */
ASSERT_OWN_NO_LOCKS();
ASSERT(ostd->fork_threads == NULL && ostd->fork_num_threads == 0);
/* i#239: Synch with all other threads to ensure that they are holding no
* locks across the fork.
* FIXME i#26: Suspend signals received before initializing siginfo are
* squelched, so we won't be able to suspend threads that are initializing.
*/
LOG(GLOBAL, 2, LOG_SYSCALLS | LOG_THREADS,
"fork: synching with other threads to prevent deadlock in child\n");
if (!synch_with_all_threads(THREAD_SYNCH_SUSPENDED_VALID_MCONTEXT_OR_NO_XFER,
&ostd->fork_threads, &ostd->fork_num_threads,
THREAD_SYNCH_VALID_MCONTEXT,
/* If we fail to suspend a thread, there is a
* risk of deadlock in the child, so it's worth
* retrying on failure.
*/
THREAD_SYNCH_SUSPEND_FAILURE_RETRY)) {
/* If we failed to synch with all threads, we live with the possiblity
* of deadlock and continue as normal.
*/
LOG(GLOBAL, 1, LOG_SYSCALLS | LOG_THREADS,
"fork: synch failed, possible deadlock in child\n");
ASSERT_CURIOSITY(false);
}
vmm_heap_fork_pre(dcontext);
/* We go back to the code cache to execute the syscall, so we can't hold
* locks. If the synch succeeded, no one else is running, so it should be
* safe to release these locks. However, if there are any rogue threads,
* then releasing these locks will allow them to synch and create threads.
* Such threads could be running due to synch failure or presence of
* non-suspendable client threads. We keep our data in ostd to prevent some
* conflicts, but there are some unhandled corner cases.
*/
d_r_mutex_unlock(&thread_initexit_lock);
d_r_mutex_unlock(&all_threads_synch_lock);
}
/* Happens after the fork in both the parent and child. */
static void
os_fork_post(dcontext_t *dcontext, bool parent)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
/* Re-acquire the locks we released before the fork. */
d_r_mutex_lock(&all_threads_synch_lock);
d_r_mutex_lock(&thread_initexit_lock);
/* Resume the other threads that we suspended. */
if (parent) {
LOG(GLOBAL, 2, LOG_SYSCALLS | LOG_THREADS,
"fork: resuming other threads after fork\n");
}
end_synch_with_all_threads(ostd->fork_threads, ostd->fork_num_threads,
parent /*resume in parent, not in child*/);
ostd->fork_threads = NULL; /* Freed by end_synch_with_all_threads. */
ostd->fork_num_threads = 0;
vmm_heap_fork_post(dcontext, parent);
}
/* this one is called before child's new logfiles are set up */
void
os_fork_init(dcontext_t *dcontext)
{
int iter;
/* We use a larger data size than file_t to avoid clobbering our stack (i#991) */
ptr_uint_t fd;
ptr_uint_t flags;
/* Static assert would save debug build overhead: could use array bound trick */
ASSERT(sizeof(file_t) <= sizeof(ptr_uint_t));
/* i#239: If there were unsuspended threads across the fork, we could have
* forked while another thread held locks. We reset the locks and try to
* cope with any intermediate state left behind from the parent. If we
* encounter more deadlocks after fork, we can add more lock and data resets
* on a case by case basis.
*/
d_r_mutex_fork_reset(&all_threads_synch_lock);
d_r_mutex_fork_reset(&thread_initexit_lock);
os_fork_post(dcontext, false /*!parent*/);
/* re-populate cached data that contains pid */
pid_cached = get_process_id();
get_application_pid_helper(true);
get_application_name_helper(true, true /* not important */);
/* close all copies of parent files */
TABLE_RWLOCK(fd_table, write, lock);
iter = 0;
do {
iter = generic_hash_iterate_next(GLOBAL_DCONTEXT, fd_table, iter, &fd,
(void **)&flags);
if (iter < 0)
break;
if (TEST(OS_OPEN_CLOSE_ON_FORK, flags)) {
close_syscall((file_t)fd);
iter = generic_hash_iterate_remove(GLOBAL_DCONTEXT, fd_table, iter, fd);
}
} while (true);
TABLE_RWLOCK(fd_table, write, unlock);
}
static void
os_swap_dr_tls(dcontext_t *dcontext, bool to_app)
{
#ifdef X86
/* If the option is off, we really should swap it (xref i#107/i#2088 comments
* in os_swap_context()) but there are few consequences of not doing it, and we
* have no code set up separate from the i#2089 scheme here.
*/
if (!INTERNAL_OPTION(safe_read_tls_init))
return;
if (to_app) {
/* i#2089: we want the child to inherit a TLS with invalid .magic, but we
* need our own syscall execution and post-syscall code to have valid scratch
* and dcontext values. We can't clear our own magic b/c we don't know when
* the child will be scheduled, so we use a copy of our TLS. We carefully
* never have a valid magic there in case a prior child is still unscheduled.
*
* We assume the child will not modify this TLS copy in any way.
* CLONE_SETTLS touc * hes the other segment (we'll have to watch for
* addition of CLONE_SETTLS_AUX). The parent will use the scratch space
* returning from the syscall to d_r_dispatch, but we restore via os_clone_post()
* immediately before anybody calls get_thread_private_dcontext() or
* anything.
*/
/* FIXME i#2088: to preserve the app's aux seg, if any, we should pass it
* and the seg reg value via the clone record (like we do for ARM today).
*/
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
os_local_state_t *cur_tls = get_os_tls_from_dc(dcontext);
if (ostd->clone_tls == NULL) {
ostd->clone_tls = (os_local_state_t *)HEAP_TYPE_ALLOC(
dcontext, os_local_state_t, ACCT_THREAD_MGT, UNPROTECTED);
LOG(THREAD, LOG_THREADS, 2, "TLS copy is " PFX "\n", ostd->clone_tls);
}
/* Leave no window where a prior uninit child could read valid magic by
* invalidating prior to copying.
*/
cur_tls->magic = TLS_MAGIC_INVALID;
memcpy(ostd->clone_tls, cur_tls, sizeof(*ostd->clone_tls));
cur_tls->magic = TLS_MAGIC_VALID;
ostd->clone_tls->self = ostd->clone_tls;
os_set_dr_tls_base(dcontext, NULL, (byte *)ostd->clone_tls);
} else {
/* i#2089: restore the parent's DR TLS */
os_local_state_t *real_tls = get_os_tls_from_dc(dcontext);
/* For dr_app_start we can end up here with nothing to do, so we check. */
if (get_segment_base(SEG_TLS) != (byte *)real_tls) {
DEBUG_DECLARE(os_thread_data_t *ostd =
(os_thread_data_t *)dcontext->os_field);
ASSERT(get_segment_base(SEG_TLS) == (byte *)ostd->clone_tls);
/* We assume there's no need to copy the scratch slots back */
os_set_dr_tls_base(dcontext, real_tls, (byte *)real_tls);
}
}
#elif defined(AARCHXX)
/* For aarchxx we don't have a separate thread register for DR, and we
* always leave the DR pointer in the slot inside the app's or privlib's TLS.
* That means we have nothing to do here.
* For SYS_clone, we are ok with the parent's TLS being inherited until
* new_thread_setup() calls set_thread_register_from_clone_record().
*/
#endif
}
static void
os_new_thread_pre(void)
{
/* We use a barrier on new threads to ensure we make progress when
* attaching to an app that is continually making threads.
* XXX i#1305: if we fully suspend all threads during attach we can
* get rid of this barrier.
*/
wait_for_event(dr_attach_finished, 0);
ATOMIC_INC(int, uninit_thread_count);
}
/* This is called from pre_system_call() and before cloning a client thread in
* dr_create_client_thread. Hence os_clone_pre is used for app threads as well
* as client threads. Do not add anything that we do not want to happen while
* in DR mode.
*/
static void
os_clone_pre(dcontext_t *dcontext)
{
/* We switch the lib tls segment back to app's segment.
* Please refer to comment on os_switch_lib_tls.
*/
if (INTERNAL_OPTION(private_loader)) {
os_switch_lib_tls(dcontext, true /*to app*/);
}
os_swap_dr_tls(dcontext, true /*to app*/);
}
/* This is called from d_r_dispatch prior to post_system_call() and after
* cloning a client thread in dr_create_client_thread. Hence os_clone_post is
* used for app threads as well as client threads. Do not add anything that
* we do not want to happen while in DR mode.
*/
void
os_clone_post(dcontext_t *dcontext)
{
os_swap_dr_tls(dcontext, false /*to DR*/);
}
byte *
os_get_dr_tls_base(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
return ostd->dr_tls_base;
}
/* We only bother swapping the library segment if we're using the private
* loader.
*/
bool
os_should_swap_state(void)
{
#ifdef X86
/* -private_loader currently implies -mangle_app_seg, but let's be safe. */
return (INTERNAL_OPTION(mangle_app_seg) && INTERNAL_OPTION(private_loader));
#elif defined(AARCHXX)
return INTERNAL_OPTION(private_loader);
#endif
}
bool
os_using_app_state(dcontext_t *dcontext)
{
#ifdef X86
/* FIXME: This could be optimized to avoid the syscall by keeping state in
* the dcontext.
*/
if (INTERNAL_OPTION(mangle_app_seg)) {
return (get_segment_base(TLS_REG_LIB) ==
os_get_app_tls_base(dcontext, TLS_REG_LIB));
}
#endif
/* We're always in the app state if we're not mangling. */
return true;
}
/* Similar to PEB swapping on Windows, this call will switch between DR's
* private lib segment base and the app's segment base.
* i#107/i#2088: If the app wants to use SEG_TLS, we should also switch that back at
* this boundary, but there are many places where we simply assume it is always
* installed.
*/
void
os_swap_context(dcontext_t *dcontext, bool to_app, dr_state_flags_t flags)
{
if (os_should_swap_state())
os_switch_seg_to_context(dcontext, LIB_SEG_TLS, to_app);
if (TEST(DR_STATE_DR_TLS, flags))
os_swap_dr_tls(dcontext, to_app);
}
void
os_thread_under_dynamo(dcontext_t *dcontext)
{
os_swap_context(dcontext, false /*to dr*/, DR_STATE_GO_NATIVE);
signal_swap_mask(dcontext, false /*to dr*/);
start_itimer(dcontext);
}
void
os_thread_not_under_dynamo(dcontext_t *dcontext)
{
stop_itimer(dcontext);
signal_swap_mask(dcontext, true /*to app*/);
os_swap_context(dcontext, true /*to app*/, DR_STATE_GO_NATIVE);
}
void
os_process_under_dynamorio_initiate(dcontext_t *dcontext)
{
LOG(GLOBAL, LOG_THREADS, 1, "process now under DR\n");
/* We only support regular process-wide signal handlers for delayed takeover. */
/* i#2161: we ignore alarm signals during the attach process to avoid races. */
signal_reinstate_handlers(dcontext, true /*ignore alarm*/);
/* XXX: there's a tradeoff here: we have a race when we remove the hook
* because dr_app_stop() has no barrier and a thread sent native might
* resume from vsyscall after we remove the hook. However, if we leave the
* hook, then the next takeover signal might hit a native thread that's
* inside DR just to go back native after having hit the hook. For now we
* remove the hook and rely on translate_from_synchall_to_dispatch() moving
* threads from vsyscall to our gencode and not relying on the hook being
* present to finish up their go-native code.
*/
hook_vsyscall(dcontext, false);
}
void
os_process_under_dynamorio_complete(dcontext_t *dcontext)
{
/* i#2161: only now do we un-ignore alarm signals. */
signal_reinstate_alarm_handlers(dcontext);
IF_NO_MEMQUERY({
/* Update the memory cache (i#2037) now that we've taken over all the
* threads, if there may have been a gap between setup and start.
*/
if (dr_api_entry)
memcache_update_all_from_os();
});
}
void
os_process_not_under_dynamorio(dcontext_t *dcontext)
{
/* We only support regular process-wide signal handlers for mixed-mode control. */
signal_remove_handlers(dcontext);
unhook_vsyscall();
LOG(GLOBAL, LOG_THREADS, 1, "process no longer under DR\n");
}
bool
detach_do_not_translate(thread_record_t *tr)
{
return false;
}
void
detach_finalize_translation(thread_record_t *tr, priv_mcontext_t *mc)
{
/* Nothing to do. */
}
void
detach_finalize_cleanup(void)
{
/* Nothing to do. */
}
static pid_t
get_process_group_id()
{
return dynamorio_syscall(SYS_getpgid, 0);
}
process_id_t
get_parent_id(void)
{
return dynamorio_syscall(SYS_getppid, 0);
}
thread_id_t
get_sys_thread_id(void)
{
#ifdef MACOS
if (kernel_thread_groups)
return dynamorio_syscall(SYS_thread_selfid, 0);
#else
if (kernel_thread_groups)
return dynamorio_syscall(SYS_gettid, 0);
#endif
return dynamorio_syscall(SYS_getpid, 0);
}
thread_id_t
d_r_get_thread_id(void)
{
/* i#228/PR 494330: making a syscall here is a perf bottleneck since we call
* this routine in read and recursive locks so use the TLS value instead
*/
thread_id_t id = get_tls_thread_id();
if (id != INVALID_THREAD_ID)
return id;
else
return get_sys_thread_id();
}
thread_id_t
get_tls_thread_id(void)
{
ptr_int_t tid; /* can't use thread_id_t since it's 32-bits */
if (!is_thread_tls_initialized())
return INVALID_THREAD_ID;
READ_TLS_SLOT_IMM(TLS_THREAD_ID_OFFSET, tid);
/* it reads 8-bytes into the memory, which includes app_gs and app_fs.
* 0x000000007127357b <get_tls_thread_id+37>: mov %gs:(%rax),%rax
* 0x000000007127357f <get_tls_thread_id+41>: mov %rax,-0x8(%rbp)
* so we remove the TRUNCATE check and trucate it on return.
*/
return (thread_id_t)tid;
}
/* returns the thread-private dcontext pointer for the calling thread */
dcontext_t *
get_thread_private_dcontext(void)
{
#ifdef HAVE_TLS
dcontext_t *dcontext;
/* We have to check this b/c this is called from __errno_location prior
* to os_tls_init, as well as after os_tls_exit, and early in a new
* thread's initialization (see comments below on that).
*/
if (!is_thread_tls_initialized())
return standalone_library ? GLOBAL_DCONTEXT : NULL;
/* We used to check tid and return NULL to distinguish parent from child, but
* that was affecting performance (xref PR 207366: but I'm leaving the assert in
* for now so debug build will still incur it). So we fixed the cases that
* needed that:
*
* - dynamo_thread_init() calling is_thread_initialized() for a new thread
* created via clone or the start/stop interface: so we have
* is_thread_initialized() pay the d_r_get_thread_id() cost.
* - new_thread_setup()'s ENTER_DR_HOOK kstats, or a crash and the signal
* handler asking about dcontext: we have new_thread_dynamo_start()
* clear the segment register for us early on.
* - child of fork (ASSERT_OWN_NO_LOCKS, etc. on re-entering DR):
* here we just suppress the assert: we'll use this same dcontext.
* xref PR 209518 where w/o this fix we used to need an extra KSTOP.
*
* An alternative would be to have the parent thread clear the segment
* register, or even set up the child's TLS ahead of time ourselves
* (and special-case so that we know if at clone syscall the app state is not
* quite correct: but we're already stealing a register there: PR 286194).
* We could also have the kernel set up TLS for us (PR 285898).
*
* For hotp_only or non-full-control (native_exec, e.g.) (PR 212012), this
* routine is not the only issue: we have to catch all new threads since
* hotp_only gateways assume tls is set up.
* Xref PR 192231.
*/
/* PR 307698: this assert causes large slowdowns (also xref PR 207366) */
DOCHECK(CHKLVL_DEFAULT + 1, {
ASSERT(get_tls_thread_id() == get_sys_thread_id() ||
/* ok for fork as mentioned above */
pid_cached != get_process_id());
});
READ_TLS_SLOT_IMM(TLS_DCONTEXT_OFFSET, dcontext);
return dcontext;
#else
/* Assumption: no lock needed on a read => no race conditions between
* reading and writing same tid! Since both get and set are only for
* the current thread, they cannot both execute simultaneously for the
* same tid, right?
*/
thread_id_t tid = d_r_get_thread_id();
int i;
if (tls_table != NULL) {
for (i = 0; i < MAX_THREADS; i++) {
if (tls_table[i].tid == tid) {
return tls_table[i].dcontext;
}
}
}
return NULL;
#endif
}
/* sets the thread-private dcontext pointer for the calling thread */
void
set_thread_private_dcontext(dcontext_t *dcontext)
{
#ifdef HAVE_TLS
ASSERT(is_thread_tls_allocated());
WRITE_TLS_SLOT_IMM(TLS_DCONTEXT_OFFSET, dcontext);
#else
thread_id_t tid = d_r_get_thread_id();
int i;
bool found = false;
ASSERT(tls_table != NULL);
d_r_mutex_lock(&tls_lock);
for (i = 0; i < MAX_THREADS; i++) {
if (tls_table[i].tid == tid) {
if (dcontext == NULL) {
/* if setting to NULL, clear the entire slot for reuse */
tls_table[i].tid = 0;
}
tls_table[i].dcontext = dcontext;
found = true;
break;
}
}
if (!found) {
if (dcontext == NULL) {
/* don't do anything...but why would this happen? */
} else {
/* look for an empty slot */
for (i = 0; i < MAX_THREADS; i++) {
if (tls_table[i].tid == 0) {
tls_table[i].tid = tid;
tls_table[i].dcontext = dcontext;
found = true;
break;
}
}
}
}
d_r_mutex_unlock(&tls_lock);
ASSERT(found);
#endif
}
/* replaces old with new
* use for forking: child should replace parent's id with its own
*/
static void
replace_thread_id(thread_id_t old, thread_id_t new)
{
#ifdef HAVE_TLS
thread_id_t new_tid = new;
ASSERT(is_thread_tls_initialized());
DOCHECK(1, {
thread_id_t old_tid;
IF_LINUX_ELSE(READ_TLS_INT_SLOT_IMM(TLS_THREAD_ID_OFFSET, old_tid),
READ_TLS_SLOT_IMM(TLS_THREAD_ID_OFFSET, old_tid));
ASSERT(old_tid == old);
});
IF_LINUX_ELSE(WRITE_TLS_INT_SLOT_IMM(TLS_THREAD_ID_OFFSET, new_tid),
WRITE_TLS_SLOT_IMM(TLS_THREAD_ID_OFFSET, new_tid));
#else
int i;
d_r_mutex_lock(&tls_lock);
for (i = 0; i < MAX_THREADS; i++) {
if (tls_table[i].tid == old) {
tls_table[i].tid = new;
break;
}
}
d_r_mutex_unlock(&tls_lock);
#endif
}
/* translate native flags to platform independent protection bits */
static inline uint
osprot_to_memprot(uint prot)
{
uint mem_prot = 0;
if (TEST(PROT_EXEC, prot))
mem_prot |= MEMPROT_EXEC;
if (TEST(PROT_READ, prot))
mem_prot |= MEMPROT_READ;
if (TEST(PROT_WRITE, prot))
mem_prot |= MEMPROT_WRITE;
return mem_prot;
}
/* returns osprot flags preserving all native protection flags except
* for RWX, which are replaced according to memprot */
uint
osprot_replace_memprot(uint old_osprot, uint memprot)
{
/* Note only protection flags PROT_ are relevant to mprotect()
* and they are separate from any other MAP_ flags passed to mmap()
*/
uint new_osprot = memprot_to_osprot(memprot);
return new_osprot;
}
/* libc independence */
static inline long
mprotect_syscall(byte *p, size_t size, uint prot)
{
return dynamorio_syscall(SYS_mprotect, 3, p, size, prot);
}
/* free memory allocated from os_raw_mem_alloc */
bool
os_raw_mem_free(void *p, size_t size, uint flags, heap_error_code_t *error_code)
{
long rc;
ASSERT(error_code != NULL);
ASSERT(size > 0 && ALIGNED(size, PAGE_SIZE));
rc = munmap_syscall(p, size);
if (rc != 0) {
*error_code = -rc;
} else {
*error_code = HEAP_ERROR_SUCCESS;
}
return (rc == 0);
}
/* try to alloc memory at preferred from os directly,
* caller is required to handle thread synchronization and to update
*/
void *
os_raw_mem_alloc(void *preferred, size_t size, uint prot, uint flags,
heap_error_code_t *error_code)
{
byte *p;
uint os_prot = memprot_to_osprot(prot);
uint os_flags =
MAP_PRIVATE | MAP_ANONYMOUS | (TEST(RAW_ALLOC_32BIT, flags) ? MAP_32BIT : 0);
ASSERT(error_code != NULL);
/* should only be used on aligned pieces */
ASSERT(size > 0 && ALIGNED(size, PAGE_SIZE));
p = mmap_syscall(preferred, size, os_prot, os_flags, -1, 0);
if (!mmap_syscall_succeeded(p)) {
*error_code = -(heap_error_code_t)(ptr_int_t)p;
LOG(GLOBAL, LOG_HEAP, 3, "os_raw_mem_alloc %d bytes failed" PFX "\n", size, p);
return NULL;
}
if (preferred != NULL && p != preferred) {
*error_code = HEAP_ERROR_NOT_AT_PREFERRED;
os_raw_mem_free(p, size, flags, error_code);
LOG(GLOBAL, LOG_HEAP, 3, "os_raw_mem_alloc %d bytes failed" PFX "\n", size, p);
return NULL;
}
LOG(GLOBAL, LOG_HEAP, 2, "os_raw_mem_alloc: " SZFMT " bytes @ " PFX "\n", size, p);
return p;
}
#ifdef LINUX
void
init_emulated_brk(app_pc exe_end)
{
ASSERT(DYNAMO_OPTION(emulate_brk));
if (app_brk_map != NULL) {
return;
}
/* i#1004: emulate brk via a separate mmap. The real brk starts out empty, but
* we need at least a page to have an mmap placeholder. We also want to reserve
* enough memory to avoid a client lib or other mmap truncating the brk at a
* too-small size, which can crash the app (i#3982).
*/
# define BRK_INITIAL_SIZE 4 * 1024 * 1024
app_brk_map = mmap_syscall(exe_end, BRK_INITIAL_SIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
ASSERT(mmap_syscall_succeeded(app_brk_map));
app_brk_cur = app_brk_map;
app_brk_end = app_brk_map + BRK_INITIAL_SIZE;
LOG(GLOBAL, LOG_HEAP, 1, "%s: initial brk is " PFX "-" PFX "\n", __FUNCTION__,
app_brk_cur, app_brk_end);
}
static byte *
emulate_app_brk(dcontext_t *dcontext, byte *new_val)
{
byte *old_brk = app_brk_cur;
ASSERT(DYNAMO_OPTION(emulate_brk));
LOG(THREAD, LOG_HEAP, 2, "%s: cur=" PFX ", requested=" PFX "\n", __FUNCTION__,
app_brk_cur, new_val);
new_val = (byte *)ALIGN_FORWARD(new_val, PAGE_SIZE);
if (new_val == NULL || new_val == app_brk_cur ||
/* Not allowed to shrink below original base */
new_val < app_brk_map) {
/* Just return cur val */
} else if (new_val < app_brk_cur) {
/* Shrink */
if (munmap_syscall(new_val, app_brk_cur - new_val) == 0) {
app_brk_cur = new_val;
app_brk_end = new_val;
}
} else if (new_val < app_brk_end) {
/* We've already allocated the space */
app_brk_cur = new_val;
} else {
/* Expand */
byte *remap = (byte *)dynamorio_syscall(SYS_mremap, 4, app_brk_map,
app_brk_end - app_brk_map,
new_val - app_brk_map, 0 /*do not move*/);
if (mmap_syscall_succeeded(remap)) {
ASSERT(remap == app_brk_map);
app_brk_cur = new_val;
app_brk_end = new_val;
} else {
LOG(THREAD, LOG_HEAP, 1, "%s: mremap to " PFX " failed\n", __FUNCTION__,
new_val);
}
}
if (app_brk_cur != old_brk)
handle_app_brk(dcontext, app_brk_map, old_brk, app_brk_cur);
return app_brk_cur;
}
#endif /* LINUX */
#ifdef LINUX
DR_API
/* XXX: could add dr_raw_mem_realloc() instead of dr_raw_mremap() -- though there
* is no realloc for Windows: supposed to reserve yourself and then commit in
* pieces.
*/
void *
dr_raw_mremap(void *old_address, size_t old_size, size_t new_size, int flags,
void *new_address)
{
byte *res;
dr_mem_info_t info;
dcontext_t *dcontext = get_thread_private_dcontext();
/* i#173: we need prot + type from prior to mremap */
DEBUG_DECLARE(bool ok =)
query_memory_ex(old_address, &info);
/* XXX: this could be a large region w/ multiple protection regions
* inside. For now we assume our handling of it doesn't care.
*/
ASSERT(ok);
if (is_pretend_or_executable_writable(old_address))
info.prot |= DR_MEMPROT_WRITE;
/* we just unconditionally send the 5th param */
res = (byte *)dynamorio_syscall(SYS_mremap, 5, old_address, old_size, new_size, flags,
new_address);
handle_app_mremap(dcontext, res, new_size, old_address, old_size, info.prot,
info.size);
return res;
}
DR_API
void *
dr_raw_brk(void *new_address)
{
dcontext_t *dcontext = get_thread_private_dcontext();
if (DYNAMO_OPTION(emulate_brk)) {
/* i#1004: emulate brk via a separate mmap */
return (void *)emulate_app_brk(dcontext, (byte *)new_address);
} else {
/* We pay the cost of 2 syscalls. This should be infrequent enough that
* it doesn't mater.
*/
if (new_address == NULL) {
/* Just a query */
return (void *)dynamorio_syscall(SYS_brk, 1, new_address);
} else {
byte *old_brk = (byte *)dynamorio_syscall(SYS_brk, 1, 0);
byte *res = (byte *)dynamorio_syscall(SYS_brk, 1, new_address);
handle_app_brk(dcontext, NULL, old_brk, res);
return res;
}
}
}
#endif /* LINUX */
/* caller is required to handle thread synchronization and to update dynamo vm areas */
void
os_heap_free(void *p, size_t size, heap_error_code_t *error_code)
{
long rc;
ASSERT(error_code != NULL);
if (!dynamo_exited)
LOG(GLOBAL, LOG_HEAP, 4, "os_heap_free: %d bytes @ " PFX "\n", size, p);
rc = munmap_syscall(p, size);
if (rc != 0) {
*error_code = -rc;
} else {
*error_code = HEAP_ERROR_SUCCESS;
}
ASSERT(rc == 0);
}
/* reserve virtual address space without committing swap space for it,
and of course no physical pages since it will never be touched */
/* to be transparent, we do not use sbrk, and are
* instead using mmap, and asserting that all os_heap requests are for
* reasonably large pieces of memory */
void *
os_heap_reserve(void *preferred, size_t size, heap_error_code_t *error_code,
bool executable)
{
void *p;
uint prot = PROT_NONE;
#ifdef VMX86_SERVER
/* PR 365331: we need to be in the mmap_text region for code cache and
* gencode (PROT_EXEC).
*/
ASSERT(!os_in_vmkernel_userworld() || !executable || preferred == NULL ||
((byte *)preferred >= os_vmk_mmap_text_start() &&
((byte *)preferred) + size <= os_vmk_mmap_text_end()));
/* Note that a preferred address overrides PROT_EXEC and a mmap_data
* address will be honored, even though any execution there will fault.
*/
/* FIXME: note that PROT_EXEC => read access, so our guard pages and other
* non-committed memory, while not writable, is readable.
* Plus, we can't later clear all prot bits for userworld mmap due to PR 107872
* (PR 365748 covers fixing this for us).
* But in most uses we should get our preferred vmheap and shouldn't run
* out of vmheap, so this should be a corner-case issue.
*/
if (executable)
prot = PROT_EXEC;
#endif
/* should only be used on aligned pieces */
ASSERT(size > 0 && ALIGNED(size, PAGE_SIZE));
ASSERT(error_code != NULL);
/* FIXME: note that this memory is in fact still committed - see man mmap */
/* FIXME: case 2347 on Linux or -vm_reserve should be set to false */
/* FIXME: Need to actually get a mmap-ing with |MAP_NORESERVE */
p = mmap_syscall(
preferred, size, prot,
MAP_PRIVATE |
MAP_ANONYMOUS IF_X64(| (DYNAMO_OPTION(heap_in_lower_4GB) ? MAP_32BIT : 0)),
-1, 0);
if (!mmap_syscall_succeeded(p)) {
*error_code = -(heap_error_code_t)(ptr_int_t)p;
LOG(GLOBAL, LOG_HEAP, 4, "os_heap_reserve %d bytes failed " PFX "\n", size, p);
return NULL;
} else if (preferred != NULL && p != preferred) {
/* We didn't get the preferred address. To harmonize with windows behavior and
* give greater control we fail the reservation. */
heap_error_code_t dummy;
*error_code = HEAP_ERROR_NOT_AT_PREFERRED;
os_heap_free(p, size, &dummy);
ASSERT(dummy == HEAP_ERROR_SUCCESS);
LOG(GLOBAL, LOG_HEAP, 4,
"os_heap_reserve %d bytes at " PFX " not preferred " PFX "\n", size,
preferred, p);
return NULL;
} else {
*error_code = HEAP_ERROR_SUCCESS;
}
LOG(GLOBAL, LOG_HEAP, 2, "os_heap_reserve: %d bytes @ " PFX "\n", size, p);
#ifdef VMX86_SERVER
/* PR 365331: ensure our memory is all in the mmap_text region */
ASSERT(!os_in_vmkernel_userworld() || !executable ||
((byte *)p >= os_vmk_mmap_text_start() &&
((byte *)p) + size <= os_vmk_mmap_text_end()));
#endif
#if defined(ANDROID) && defined(DEBUG)
/* We don't label in release to be more transparent */
dynamorio_syscall(SYS_prctl, 5, PR_SET_VMA, PR_SET_VMA_ANON_NAME, p, size,
"DynamoRIO-internal");
#endif
return p;
}
static bool
find_free_memory_in_region(byte *start, byte *end, size_t size, byte **found_start OUT,
byte **found_end OUT)
{
memquery_iter_t iter;
/* XXX: despite /proc/sys/vm/mmap_min_addr == PAGE_SIZE, mmap won't
* give me that address if I use it as a hint.
*/
app_pc last_end = (app_pc)(PAGE_SIZE * 16);
bool found = false;
memquery_iterator_start(&iter, NULL, false /*won't alloc*/);
while (memquery_iterator_next(&iter)) {
if (iter.vm_start >= start &&
MIN(iter.vm_start, end) - MAX(last_end, start) >= size) {
if (found_start != NULL)
*found_start = MAX(last_end, start);
if (found_end != NULL)
*found_end = MIN(iter.vm_start, end);
found = true;
break;
}
if (iter.vm_end >= end)
break;
last_end = iter.vm_end;
}
memquery_iterator_stop(&iter);
return found;
}
void *
os_heap_reserve_in_region(void *start, void *end, size_t size,
heap_error_code_t *error_code, bool executable)
{
byte *p = NULL;
byte *try_start = NULL, *try_end = NULL;
uint iters = 0;
ASSERT(ALIGNED(start, PAGE_SIZE) && ALIGNED(end, PAGE_SIZE));
ASSERT(ALIGNED(size, PAGE_SIZE));
LOG(GLOBAL, LOG_HEAP, 3,
"os_heap_reserve_in_region: " SZFMT " bytes in " PFX "-" PFX "\n", size, start,
end);
/* if no restriction on location use regular os_heap_reserve() */
if (start == (void *)PTR_UINT_0 && end == (void *)POINTER_MAX)
return os_heap_reserve(NULL, size, error_code, executable);
/* loop to handle races */
#define RESERVE_IN_REGION_MAX_ITERS 128
while (find_free_memory_in_region(start, end, size, &try_start, &try_end)) {
/* If there's space we'd prefer the end, to avoid the common case of
* a large binary + heap at attach where we're likely to reserve
* right at the start of the brk: we'd prefer to leave more brk space.
*/
p = os_heap_reserve(try_end - size, size, error_code, executable);
if (p != NULL) {
ASSERT(*error_code == HEAP_ERROR_SUCCESS);
ASSERT(p >= (byte *)start && p + size <= (byte *)end);
break;
}
if (++iters > RESERVE_IN_REGION_MAX_ITERS) {
ASSERT_NOT_REACHED();
break;
}
}
if (p == NULL)
*error_code = HEAP_ERROR_CANT_RESERVE_IN_REGION;
else
*error_code = HEAP_ERROR_SUCCESS;
LOG(GLOBAL, LOG_HEAP, 2,
"os_heap_reserve_in_region: reserved " SZFMT " bytes @ " PFX " in " PFX "-" PFX
"\n",
size, p, start, end);
return p;
}
/* commit previously reserved with os_heap_reserve pages */
/* returns false when out of memory */
/* A replacement of os_heap_alloc can be constructed by using os_heap_reserve
and os_heap_commit on a subset of the reserved pages. */
/* caller is required to handle thread synchronization */
bool
os_heap_commit(void *p, size_t size, uint prot, heap_error_code_t *error_code)
{
uint os_prot = memprot_to_osprot(prot);
long res;
/* should only be used on aligned pieces */
ASSERT(size > 0 && ALIGNED(size, PAGE_SIZE));
ASSERT(p);
ASSERT(error_code != NULL);
/* FIXME: note that the memory would not be not truly committed if we have */
/* not actually marked a mmap-ing without MAP_NORESERVE */
res = mprotect_syscall(p, size, os_prot);
if (res != 0) {
*error_code = -res;
return false;
} else {
*error_code = HEAP_ERROR_SUCCESS;
}
LOG(GLOBAL, LOG_HEAP, 2, "os_heap_commit: %d bytes @ " PFX "\n", size, p);
return true;
}
/* caller is required to handle thread synchronization and to update dynamo vm areas */
void
os_heap_decommit(void *p, size_t size, heap_error_code_t *error_code)
{
int rc;
ASSERT(error_code != NULL);
if (!dynamo_exited)
LOG(GLOBAL, LOG_HEAP, 4, "os_heap_decommit: %d bytes @ " PFX "\n", size, p);
*error_code = HEAP_ERROR_SUCCESS;
/* FIXME: for now do nothing since os_heap_reserve has in fact committed the memory */
rc = 0;
/* TODO:
p = mmap_syscall(p, size, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
we should either do a mremap()
or we can do a munmap() followed 'quickly' by a mmap() -
also see above the comment that os_heap_reserve() in fact is not so lightweight
*/
ASSERT(rc == 0);
}
bool
os_heap_systemwide_overcommit(heap_error_code_t last_error_code)
{
/* FIXME: conservative answer yes */
return true;
}
bool
os_heap_get_commit_limit(size_t *commit_used, size_t *commit_limit)
{
/* FIXME - NYI */
return false;
}
/* yield the current thread */
void
os_thread_yield()
{
#ifdef MACOS
/* XXX i#1291: use raw syscall instead */
swtch_pri(0);
#else
dynamorio_syscall(SYS_sched_yield, 0);
#endif
}
bool
thread_signal(process_id_t pid, thread_id_t tid, int signum)
{
#ifdef MACOS
/* FIXME i#58: this takes in a thread port. Need to map thread id to port.
* Need to figure out whether we support raw Mach threads w/o pthread on top.
*/
ASSERT_NOT_IMPLEMENTED(false);
return false;
#else
/* FIXME: for non-NPTL use SYS_kill */
/* Note that the pid is equivalent to the thread group id.
* However, we can have threads sharing address space but not pid
* (if created via CLONE_VM but not CLONE_THREAD), so make sure to
* use the pid of the target thread, not our pid.
*/
return (dynamorio_syscall(SYS_tgkill, 3, pid, tid, signum) == 0);
#endif
}
static bool
known_thread_signal(thread_record_t *tr, int signum)
{
#ifdef MACOS
ptr_int_t res;
if (tr->dcontext == NULL)
return FALSE;
res = dynamorio_syscall(SYS___pthread_kill, 2, tr->dcontext->thread_port, signum);
LOG(THREAD_GET, LOG_ALL, 3, "%s: signal %d to port %d => %ld\n", __FUNCTION__, signum,
tr->dcontext->thread_port, res);
return res == 0;
#else
return thread_signal(tr->pid, tr->id, signum);
#endif
}
void
os_thread_sleep(uint64 milliseconds)
{
#ifdef MACOS
semaphore_t sem = MACH_PORT_NULL;
int res;
#else
struct timespec remain;
int count = 0;
#endif
struct timespec req;
req.tv_sec = (milliseconds / 1000);
/* docs say can go up to 1000000000, but doesn't work on FC9 */
req.tv_nsec = (milliseconds % 1000) * 1000000;
#ifdef MACOS
if (sem == MACH_PORT_NULL) {
DEBUG_DECLARE(kern_return_t res =)
semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, 0);
ASSERT(res == KERN_SUCCESS);
}
res =
dynamorio_syscall(SYSNUM_NO_CANCEL(SYS___semwait_signal), 6, sem, MACH_PORT_NULL,
1, 1, (int64_t)req.tv_sec, (int32_t)req.tv_nsec);
if (res == -EINTR) {
/* FIXME i#58: figure out how much time elapsed and re-wait */
}
#else
/* FIXME: if we need accurate sleeps in presence of itimers we should
* be using SYS_clock_nanosleep w/ an absolute time instead of relative
*/
while (dynamorio_syscall(SYS_nanosleep, 2, &req, &remain) == -EINTR) {
/* interrupted by signal or something: finish the interval */
ASSERT_CURIOSITY_ONCE(remain.tv_sec <= req.tv_sec &&
(remain.tv_sec < req.tv_sec ||
/* there seems to be some rounding, and sometimes
* remain nsec > req nsec (I've seen 40K diff)
*/
req.tv_nsec - remain.tv_nsec < 100000 ||
req.tv_nsec - remain.tv_nsec > -100000));
/* not unusual for client threads to use itimers and have their run
* routine sleep forever
*/
if (count++ > 3 && !IS_CLIENT_THREAD(get_thread_private_dcontext())) {
ASSERT_NOT_REACHED();
break; /* paranoid */
}
req = remain;
}
#endif
}
bool
os_thread_suspend(thread_record_t *tr)
{
os_thread_data_t *ostd = (os_thread_data_t *)tr->dcontext->os_field;
ASSERT(ostd != NULL);
/* See synch comments in os_thread_resume: the mutex held there
* prevents prematurely sending a re-suspend signal.
*/
d_r_mutex_lock(&ostd->suspend_lock);
ostd->suspend_count++;
ASSERT(ostd->suspend_count > 0);
/* If already suspended, do not send another signal. However, we do
* need to ensure the target is suspended in case of a race, so we can't
* just return.
*/
if (ostd->suspend_count == 1) {
/* PR 212090: we use a custom signal handler to suspend. We wait
* here until the target reaches the suspend point, and leave it
* up to the caller to check whether it is a safe suspend point,
* to match Windows behavior.
*/
ASSERT(ksynch_get_value(&ostd->suspended) == 0);
if (!known_thread_signal(tr, SUSPEND_SIGNAL)) {
ostd->suspend_count--;
d_r_mutex_unlock(&ostd->suspend_lock);
return false;
}
}
/* we can unlock before the wait loop b/c we're using a separate "resumed"
* int and os_thread_resume holds the lock across its wait. this way a resume
* can proceed as soon as the suspended thread is suspended, before the
* suspending thread gets scheduled again.
*/
d_r_mutex_unlock(&ostd->suspend_lock);
while (ksynch_get_value(&ostd->suspended) == 0) {
/* For Linux, waits only if the suspended flag is not set as 1. Return value
* doesn't matter because the flag will be re-checked.
*/
/* We time out and assert in debug build to provide better diagnostics than a
* silent hang. We can't safely return false b/c the synch model here
* assumes there will not be a retry until the target reaches the suspend
* point. Xref i#2779.
*/
#define SUSPEND_DEBUG_TIMEOUT_MS 5000
if (ksynch_wait(&ostd->suspended, 0, SUSPEND_DEBUG_TIMEOUT_MS) == -ETIMEDOUT) {
ASSERT_CURIOSITY(false && "failed to suspend thread in 5s");
}
if (ksynch_get_value(&ostd->suspended) == 0) {
/* If it still has to wait, give up the cpu. */
os_thread_yield();
}
}
return true;
}
bool
os_thread_resume(thread_record_t *tr)
{
os_thread_data_t *ostd = (os_thread_data_t *)tr->dcontext->os_field;
ASSERT(ostd != NULL);
/* This mutex prevents sending a re-suspend signal before the target
* reaches a safe post-resume point from a first suspend signal.
* Given that race, we can't just use atomic_add_exchange_int +
* atomic_dec_becomes_zero on suspend_count.
*/
d_r_mutex_lock(&ostd->suspend_lock);
ASSERT(ostd->suspend_count > 0);
/* PR 479750: if do get here and target is not suspended then abort
* to avoid possible deadlocks
*/
if (ostd->suspend_count == 0) {
d_r_mutex_unlock(&ostd->suspend_lock);
return true; /* the thread is "resumed", so success status */
}
ostd->suspend_count--;
if (ostd->suspend_count > 0) {
d_r_mutex_unlock(&ostd->suspend_lock);
return true; /* still suspended */
}
ksynch_set_value(&ostd->wakeup, 1);
ksynch_wake(&ostd->wakeup);
while (ksynch_get_value(&ostd->resumed) == 0) {
/* For Linux, waits only if the resumed flag is not set as 1. Return value
* doesn't matter because the flag will be re-checked.
*/
ksynch_wait(&ostd->resumed, 0, 0);
if (ksynch_get_value(&ostd->resumed) == 0) {
/* If it still has to wait, give up the cpu. */
os_thread_yield();
}
}
ksynch_set_value(&ostd->wakeup, 0);
ksynch_set_value(&ostd->resumed, 0);
d_r_mutex_unlock(&ostd->suspend_lock);
return true;
}
bool
os_thread_terminate(thread_record_t *tr)
{
/* PR 297902: for NPTL sending SIGKILL will take down the whole group:
* so instead we send SIGUSR2 and have a flag set telling
* target thread to execute SYS_exit
*/
os_thread_data_t *ostd = (os_thread_data_t *)tr->dcontext->os_field;
ASSERT(ostd != NULL);
ostd->terminate = true;
/* Even if the thread is currently suspended, it's simpler to send it
* another signal than to resume it.
*/
return known_thread_signal(tr, SUSPEND_SIGNAL);
}
bool
is_thread_terminated(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
ASSERT(ostd != NULL);
return (ksynch_get_value(&ostd->terminated) == 1);
}
static void
os_wait_thread_futex(KSYNCH_TYPE *var)
{
while (ksynch_get_value(var) == 0) {
/* On Linux, waits only if var is not set as 1. Return value
* doesn't matter because var will be re-checked.
*/
ksynch_wait(var, 0, 0);
if (ksynch_get_value(var) == 0) {
/* If it still has to wait, give up the cpu. */
os_thread_yield();
}
}
}
void
os_wait_thread_terminated(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
ASSERT(ostd != NULL);
os_wait_thread_futex(&ostd->terminated);
}
void
os_wait_thread_detached(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
ASSERT(ostd != NULL);
os_wait_thread_futex(&ostd->detached);
}
void
os_signal_thread_detach(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
ASSERT(ostd != NULL);
ostd->do_detach = true;
}
bool
thread_get_mcontext(thread_record_t *tr, priv_mcontext_t *mc)
{
/* PR 212090: only works when target is suspended by us, and
* we then take the signal context
*/
os_thread_data_t *ostd = (os_thread_data_t *)tr->dcontext->os_field;
ASSERT(ostd != NULL);
ASSERT(ostd->suspend_count > 0);
if (ostd->suspend_count == 0)
return false;
ASSERT(ostd->suspended_sigcxt != NULL);
sigcontext_to_mcontext(mc, ostd->suspended_sigcxt, DR_MC_ALL);
IF_ARM(dr_set_isa_mode(tr->dcontext, get_sigcontext_isa_mode(ostd->suspended_sigcxt),
NULL));
return true;
}
bool
thread_set_mcontext(thread_record_t *tr, priv_mcontext_t *mc)
{
/* PR 212090: only works when target is suspended by us, and
* we then replace the signal context
*/
os_thread_data_t *ostd = (os_thread_data_t *)tr->dcontext->os_field;
ASSERT(ostd != NULL);
ASSERT(ostd->suspend_count > 0);
if (ostd->suspend_count == 0)
return false;
ASSERT(ostd->suspended_sigcxt != NULL);
mcontext_to_sigcontext(ostd->suspended_sigcxt, mc, DR_MC_ALL);
IF_ARM(
set_sigcontext_isa_mode(ostd->suspended_sigcxt, dr_get_isa_mode(tr->dcontext)));
return true;
}
/* Only one of mc and dmc can be non-NULL. */
bool
os_context_to_mcontext(dr_mcontext_t *dmc, priv_mcontext_t *mc, os_cxt_ptr_t osc)
{
if (dmc != NULL)
sigcontext_to_mcontext(dr_mcontext_as_priv_mcontext(dmc), &osc, dmc->flags);
else if (mc != NULL)
sigcontext_to_mcontext(mc, &osc, DR_MC_ALL);
else
return false;
return true;
}
/* Only one of mc and dmc can be non-NULL. */
bool
mcontext_to_os_context(os_cxt_ptr_t osc, dr_mcontext_t *dmc, priv_mcontext_t *mc)
{
if (dmc != NULL)
mcontext_to_sigcontext(&osc, dr_mcontext_as_priv_mcontext(dmc), dmc->flags);
else if (mc != NULL)
mcontext_to_sigcontext(&osc, mc, DR_MC_ALL);
else
return false;
return true;
}
bool
is_thread_currently_native(thread_record_t *tr)
{
return (!tr->under_dynamo_control ||
/* start/stop doesn't change under_dynamo_control and has its own field */
(tr->dcontext != NULL && tr->dcontext->currently_stopped));
}
#ifdef LINUX /* XXX i#58: just until we have Mac support */
static void
client_thread_run(void)
{
void (*func)(void *param);
dcontext_t *dcontext;
byte *xsp;
GET_STACK_PTR(xsp);
void *crec = get_clone_record((reg_t)xsp);
/* i#2335: we support setup separate from start, and we want to allow a client
* to create a client thread during init, but we do not support that thread
* executing until the app has started (b/c we have no signal handlers in place).
*/
/* i#3973: in addition to _executing_ a client thread before the
* app has started, if we even create the thread before
* dynamo_initialized is set, we will not copy tls blocks. By
* waiting for the app to be started before dynamo_thread_init is
* called, we ensure this race condition can never happen, since
* dynamo_initialized will always be set before the app is started.
*/
wait_for_event(dr_app_started, 0);
IF_DEBUG(int rc =)
dynamo_thread_init(get_clone_record_dstack(crec), NULL, crec, true);
ASSERT(rc != -1); /* this better be a new thread */
dcontext = get_thread_private_dcontext();
ASSERT(dcontext != NULL);
LOG(THREAD, LOG_ALL, 1, "\n***** CLIENT THREAD %d *****\n\n", d_r_get_thread_id());
/* We stored the func and args in particular clone record fields */
func = (void (*)(void *param))dcontext->next_tag;
/* Reset any inherited mask (i#2337). */
signal_swap_mask(dcontext, false /*to DR*/);
void *arg = (void *)get_clone_record_app_xsp(crec);
LOG(THREAD, LOG_ALL, 1, "func=" PFX ", arg=" PFX "\n", func, arg);
(*func)(arg);
LOG(THREAD, LOG_ALL, 1, "\n***** CLIENT THREAD %d EXITING *****\n\n",
d_r_get_thread_id());
block_cleanup_and_terminate(dcontext, SYS_exit, 0, 0, false /*just thread*/,
IF_MACOS_ELSE(dcontext->thread_port, 0), 0);
}
#endif
/* i#41/PR 222812: client threads
* * thread must have dcontext since many API routines require one and we
* don't expose GLOBAL_DCONTEXT (xref PR 243008, PR 216936, PR 536058)
* * reversed the old design of not using dstack (partly b/c want dcontext)
* and I'm using the same parent-creates-dstack and clone_record_t design
* to create linux threads: dstack should be big enough for client threads
* (xref PR 202669)
* * reversed the old design of explicit dr_terminate_client_thread(): now
* the thread is auto-terminated and stack cleaned up on return from run
* function
*/
DR_API bool
dr_create_client_thread(void (*func)(void *param), void *arg)
{
#ifdef LINUX
dcontext_t *dcontext = get_thread_private_dcontext();
byte *xsp;
/* We do not pass SIGCHLD since don't want signal to parent and don't support
* waiting on child.
* We do not pass CLONE_THREAD so that the new thread is in its own thread
* group, allowing it to have private itimers and not receive any signals
* sent to the app's thread groups. It also makes the thread not show up in
* the thread list for the app, making it more invisible.
*/
uint flags = CLONE_VM | CLONE_FS | CLONE_FILES |
CLONE_SIGHAND
/* CLONE_THREAD required. Signals and itimers are private anyway. */
IF_VMX86(| (os_in_vmkernel_userworld() ? CLONE_THREAD : 0));
pre_second_thread();
/* need to share signal handler table, prior to creating clone record */
handle_clone(dcontext, flags);
ATOMIC_INC(int, uninit_thread_count);
void *crec = create_clone_record(dcontext, (reg_t *)&xsp, NULL, NULL);
/* make sure client_thread_run can get the func and arg, and that
* signal_thread_inherit gets the right syscall info
*/
set_clone_record_fields(crec, (reg_t)arg, (app_pc)func, SYS_clone, flags);
LOG(THREAD, LOG_ALL, 1, "dr_create_client_thread xsp=" PFX " dstack=" PFX "\n", xsp,
get_clone_record_dstack(crec));
/* i#501 switch to app's tls before creating client thread.
* i#3526 switch DR's tls to an invalid one before cloning, and switch lib_tls
* to the app's.
*/
os_clone_pre(dcontext);
# ifdef AARCHXX
/* We need to invalidate DR's TLS to avoid get_thread_private_dcontext() finding one
* and hitting asserts in dynamo_thread_init lock calls -- yet we don't want to for
* app threads, so we're doing this here and not in os_clone_pre().
* XXX: Find a way to put this in os_clone_* to simplify the code?
*/
void *tls = (void *)read_thread_register(LIB_SEG_TLS);
write_thread_register(NULL);
# endif
thread_id_t newpid = dynamorio_clone(flags, xsp, NULL, NULL, NULL, client_thread_run);
/* i#3526 switch DR's tls back to the original one before cloning. */
os_clone_post(dcontext);
# ifdef AARCHXX
write_thread_register(tls);
# endif
/* i#501 the app's tls was switched in os_clone_pre. */
if (INTERNAL_OPTION(private_loader))
os_switch_lib_tls(dcontext, false /*to dr*/);
if (newpid < 0) {
LOG(THREAD, LOG_ALL, 1, "client thread creation failed: %d\n", newpid);
return false;
} else if (newpid == 0) {
/* dynamorio_clone() should have called client_thread_run directly */
ASSERT_NOT_REACHED();
return false;
}
return true;
#else
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#58: implement on Mac */
return false;
#endif
}
int
get_num_processors(void)
{
static uint num_cpu = 0; /* cached value */
if (!num_cpu) {
#ifdef MACOS
DEBUG_DECLARE(bool ok =)
sysctl_query(CTL_HW, HW_NCPU, &num_cpu, sizeof(num_cpu));
ASSERT(ok);
#else
/* We used to use get_nprocs_conf, but that's in libc, so now we just
* look at the /sys filesystem ourselves, which is what glibc does.
*/
uint local_num_cpus = 0;
file_t cpu_dir = os_open_directory("/sys/devices/system/cpu", OS_OPEN_READ);
dir_iterator_t iter;
ASSERT(cpu_dir != INVALID_FILE &&
"/sys must be mounted: mount -t sysfs sysfs /sys");
os_dir_iterator_start(&iter, cpu_dir);
while (os_dir_iterator_next(&iter)) {
int dummy_num;
if (sscanf(iter.name, "cpu%d", &dummy_num) == 1)
local_num_cpus++;
}
os_close(cpu_dir);
num_cpu = local_num_cpus;
#endif
ASSERT(num_cpu);
}
return num_cpu;
}
/* i#46: To support -no_private_loader, we have to call the dlfcn family of
* routines in libdl.so. When we do early injection, there is no loader to
* resolve these imports, so they will crash. Early injection is incompatible
* with -no_private_loader, so this should never happen.
*/
shlib_handle_t
load_shared_library(const char *name, bool reachable)
{
#ifdef STATIC_LIBRARY
if (os_files_same(name, get_application_name())) {
/* The private loader falls back to dlsym() and friends for modules it
* doesn't recognize, so this works without disabling the private loader.
*/
return dlopen(NULL, RTLD_LAZY); /* Gets a handle to the exe. */
}
#endif
/* We call locate_and_load_private_library() to support searching for
* a pathless name.
*/
if (INTERNAL_OPTION(private_loader))
return (shlib_handle_t)locate_and_load_private_library(name, reachable);
#if defined(STATIC_LIBRARY) || defined(MACOS)
ASSERT(!DYNAMO_OPTION(early_inject));
return dlopen(name, RTLD_LAZY);
#else
/* -no_private_loader is no longer supported in our default builds.
* If we want it for hybrid mode we should add a new build param and include
* the libdl calls here under that param.
*/
ASSERT_NOT_REACHED();
return NULL;
#endif
}
shlib_routine_ptr_t
lookup_library_routine(shlib_handle_t lib, const char *name)
{
if (INTERNAL_OPTION(private_loader)) {
return (shlib_routine_ptr_t)get_private_library_address((app_pc)lib, name);
}
#if defined(STATIC_LIBRARY) || defined(MACOS)
ASSERT(!DYNAMO_OPTION(early_inject));
return dlsym(lib, name);
#else
ASSERT_NOT_REACHED(); /* -no_private_loader is no longer supported: see above */
return NULL;
#endif
}
void
unload_shared_library(shlib_handle_t lib)
{
if (INTERNAL_OPTION(private_loader)) {
unload_private_library(lib);
} else {
#if defined(STATIC_LIBRARY) || defined(MACOS)
ASSERT(!DYNAMO_OPTION(early_inject));
if (!DYNAMO_OPTION(avoid_dlclose)) {
dlclose(lib);
}
#else
ASSERT_NOT_REACHED(); /* -no_private_loader is no longer supported: see above */
#endif
}
}
void
shared_library_error(char *buf, int maxlen)
{
const char *err;
if (INTERNAL_OPTION(private_loader)) {
err = "error in private loader";
} else {
#if defined(STATIC_LIBRARY) || defined(MACOS)
ASSERT(!DYNAMO_OPTION(early_inject));
err = dlerror();
if (err == NULL) {
err = "dlerror returned NULL";
}
#else
ASSERT_NOT_REACHED(); /* -no_private_loader is no longer supported */
err = "unknown error";
#endif
}
strncpy(buf, err, maxlen - 1);
buf[maxlen - 1] = '\0'; /* strncpy won't put on trailing null if maxes out */
}
/* addr is any pointer known to lie within the library.
* for linux, one of addr or name is needed; for windows, neither is needed.
*/
bool
shared_library_bounds(IN shlib_handle_t lib, IN byte *addr, IN const char *name,
OUT byte **start, OUT byte **end)
{
ASSERT(start != NULL && end != NULL);
/* PR 366195: dlopen() handle truly is opaque, so we have to use either
* addr or name
*/
ASSERT(addr != NULL || name != NULL);
*start = addr;
if (INTERNAL_OPTION(private_loader)) {
privmod_t *mod;
/* look for private library first */
acquire_recursive_lock(&privload_lock);
mod = privload_lookup_by_base((app_pc)lib);
if (name != NULL && mod == NULL)
mod = privload_lookup(name);
if (mod != NULL && !mod->externally_loaded) {
*start = mod->base;
if (end != NULL)
*end = mod->base + mod->size;
release_recursive_lock(&privload_lock);
return true;
}
release_recursive_lock(&privload_lock);
}
return (memquery_library_bounds(name, start, end, NULL, 0, NULL, 0) > 0);
}
static int
fcntl_syscall(int fd, int cmd, long arg)
{
return dynamorio_syscall(SYSNUM_NO_CANCEL(SYS_fcntl), 3, fd, cmd, arg);
}
/* dups curfd to a private fd.
* returns -1 if unsuccessful.
*/
file_t
fd_priv_dup(file_t curfd)
{
file_t newfd = -1;
if (DYNAMO_OPTION(steal_fds) > 0) {
/* RLIMIT_NOFILES is 1 greater than max and F_DUPFD starts at given value */
/* XXX: if > linux 2.6.24, can use F_DUPFD_CLOEXEC to avoid later call:
* so how do we tell if the flag is supported? try calling once at init?
*/
newfd = fcntl_syscall(curfd, F_DUPFD, min_dr_fd);
if (newfd < 0) {
/* We probably ran out of fds, esp if debug build and there are
* lots of threads. Should we track how many we've given out to
* avoid a failed syscall every time after?
*/
SYSLOG_INTERNAL_WARNING_ONCE("ran out of stolen fd space");
/* Try again but this time in the app space, somewhere high up
* to avoid issues like tcsh assuming it can own fds 3-5 for
* piping std{in,out,err} (xref the old -open_tcsh_fds option).
*/
newfd = fcntl_syscall(curfd, F_DUPFD, min_dr_fd / 2);
}
}
return newfd;
}
bool
fd_mark_close_on_exec(file_t fd)
{
/* we assume FD_CLOEXEC is the only flag and don't bother w/ F_GETFD */
if (fcntl_syscall(fd, F_SETFD, FD_CLOEXEC) != 0) {
SYSLOG_INTERNAL_WARNING("unable to mark file %d as close-on-exec", fd);
return false;
}
return true;
}
void
fd_table_add(file_t fd, uint flags)
{
if (fd_table != NULL) {
TABLE_RWLOCK(fd_table, write, lock);
DODEBUG({
/* i#1010: If the fd is already in the table, chances are it's a
* stale logfile fd left behind by a vforked or cloned child that
* called execve. Avoid an assert if that happens.
*/
bool present = generic_hash_remove(GLOBAL_DCONTEXT, fd_table, (ptr_uint_t)fd);
ASSERT_CURIOSITY_ONCE(!present && "stale fd not cleaned up");
});
generic_hash_add(GLOBAL_DCONTEXT, fd_table, (ptr_uint_t)fd,
/* store the flags, w/ a set bit to ensure not 0 */
(void *)(ptr_uint_t)(flags | OS_OPEN_RESERVED));
TABLE_RWLOCK(fd_table, write, unlock);
} else {
#ifdef DEBUG
num_fd_add_pre_heap++;
/* we add main_logfile in d_r_os_init() */
ASSERT(num_fd_add_pre_heap == 1 && "only main_logfile should come here");
#endif
}
}
static bool
fd_is_dr_owned(file_t fd)
{
ptr_uint_t flags;
ASSERT(fd_table != NULL);
TABLE_RWLOCK(fd_table, read, lock);
flags = (ptr_uint_t)generic_hash_lookup(GLOBAL_DCONTEXT, fd_table, (ptr_uint_t)fd);
TABLE_RWLOCK(fd_table, read, unlock);
return (flags != 0);
}
static bool
fd_is_in_private_range(file_t fd)
{
return (DYNAMO_OPTION(steal_fds) > 0 && min_dr_fd > 0 && fd >= min_dr_fd);
}
file_t
os_open_protected(const char *fname, int os_open_flags)
{
file_t dup;
file_t res = os_open(fname, os_open_flags);
if (res < 0)
return res;
/* we could have os_open() always switch to a private fd but it's probably
* not worth the extra syscall for temporary open/close sequences so we
* only use it for persistent files
*/
dup = fd_priv_dup(res);
if (dup >= 0) {
close_syscall(res);
res = dup;
fd_mark_close_on_exec(res);
} /* else just keep original */
/* ditto here, plus for things like config.c opening files we can't handle
* grabbing locks and often don't have heap available so no fd_table
*/
fd_table_add(res, os_open_flags);
return res;
}
void
os_close_protected(file_t f)
{
ASSERT(fd_table != NULL || dynamo_exited);
if (fd_table != NULL) {
TABLE_RWLOCK(fd_table, write, lock);
generic_hash_remove(GLOBAL_DCONTEXT, fd_table, (ptr_uint_t)f);
TABLE_RWLOCK(fd_table, write, unlock);
}
os_close(f);
}
bool
os_get_current_dir(char *buf, size_t bufsz)
{
#ifdef MACOS
static char noheap_buf[MAXPATHLEN];
bool res = false;
file_t fd = os_open(".", OS_OPEN_READ);
int len;
/* F_GETPATH assumes a buffer of size MAXPATHLEN */
char *fcntl_buf;
if (dynamo_heap_initialized)
fcntl_buf = global_heap_alloc(MAXPATHLEN HEAPACCT(ACCT_OTHER));
else
fcntl_buf = noheap_buf;
if (fd == INVALID_FILE)
goto cwd_error;
if (fcntl_syscall(fd, F_GETPATH, (long)fcntl_buf) != 0)
goto cwd_error;
len = snprintf(buf, bufsz, "%s", fcntl_buf);
buf[bufsz - 1] = '\0';
return (len > 0 && len < bufsz);
cwd_error:
if (dynamo_heap_initialized)
global_heap_free(fcntl_buf, MAXPATHLEN HEAPACCT(ACCT_OTHER));
os_close(fd);
return res;
#else
return (dynamorio_syscall(SYS_getcwd, 2, buf, bufsz) > 0);
#endif
}
ssize_t
os_write(file_t f, const void *buf, size_t count)
{
return write_syscall(f, buf, count);
}
/* There are enough differences vs the shared drlibc_os.c version that we override
* it here. We use a loop to ensure reachability for the core.
*/
byte *
os_map_file(file_t f, size_t *size INOUT, uint64 offs, app_pc addr, uint prot,
map_flags_t map_flags)
{
int flags;
byte *map = NULL;
#if defined(X64)
bool loop = false;
uint iters = 0;
# define MAX_MMAP_LOOP_ITERS 100
byte *region_start = NULL, *region_end = NULL;
#else
uint pg_offs;
ASSERT_TRUNCATE(pg_offs, uint, offs / PAGE_SIZE);
pg_offs = (uint)(offs / PAGE_SIZE);
#endif
#ifdef VMX86_SERVER
flags = MAP_PRIVATE; /* MAP_SHARED not supported yet */
#else
flags = TEST(MAP_FILE_COPY_ON_WRITE, map_flags) ? MAP_PRIVATE : MAP_SHARED;
#endif
#if defined(X64)
/* Allocate memory from reachable range for image: or anything (pcache
* in particular): for low 4GB, easiest to just pass MAP_32BIT (which is
* low 2GB, but good enough).
*/
if (DYNAMO_OPTION(heap_in_lower_4GB) &&
!TESTANY(MAP_FILE_FIXED | MAP_FILE_APP, map_flags))
flags |= MAP_32BIT;
#endif
/* Allows memory request instead of mapping a file,
* so we can request memory from a particular address with fixed argument */
if (f == -1)
flags |= MAP_ANONYMOUS;
if (TEST(MAP_FILE_FIXED, map_flags))
flags |= MAP_FIXED;
#if defined(X64)
if (!TEST(MAP_32BIT, flags) && TEST(MAP_FILE_REACHABLE, map_flags)) {
vmcode_get_reachable_region(®ion_start, ®ion_end);
/* addr need not be NULL: we'll use it if it's in the region */
ASSERT(!TEST(MAP_FILE_FIXED, map_flags));
/* Loop to handle races */
loop = true;
}
if ((!TEST(MAP_32BIT, flags) && TEST(MAP_FILE_REACHABLE, map_flags) &&
(is_vmm_reserved_address(addr, *size, NULL, NULL) ||
/* Try to honor a library's preferred address. This does open up a race
* window during attach where another thread could take this spot,
* and with this current code we'll never go back and try to get VMM
* memory. We live with that as being rare rather than complicate the code.
*/
!rel32_reachable_from_current_vmcode(addr))) ||
(TEST(MAP_FILE_FIXED, map_flags) && !TEST(MAP_FILE_VMM_COMMIT, map_flags) &&
is_vmm_reserved_address(addr, *size, NULL, NULL))) {
if (DYNAMO_OPTION(vm_reserve)) {
/* Try to get space inside the vmcode reservation. */
map = heap_reserve_for_external_mapping(addr, *size,
VMM_SPECIAL_MMAP | VMM_REACHABLE);
if (map != NULL) {
addr = map;
flags |= MAP_FIXED;
}
}
}
while (!loop ||
(addr != NULL && addr >= region_start && addr + *size <= region_end) ||
find_free_memory_in_region(region_start, region_end, *size, &addr, NULL)) {
#endif
map = mmap_syscall(addr, *size, memprot_to_osprot(prot), flags, f,
/* x86 Linux mmap uses offset in pages */
IF_LINUX_ELSE(IF_X64_ELSE(offs, pg_offs), offs));
if (!mmap_syscall_succeeded(map)) {
LOG(THREAD_GET, LOG_SYSCALLS, 2, "%s failed: " PIFX "\n", __func__, map);
map = NULL;
}
#if defined(X64)
else if (loop && (map < region_start || map + *size > region_end)) {
/* Try again: probably a race. Hopefully our notion of "there's a free
* region big enough" matches the kernel's, else we'll loop forever
* (which we try to catch w/ a max iters count).
*/
munmap_syscall(map, *size);
map = NULL;
} else
break;
if (!loop)
break;
if (++iters > MAX_MMAP_LOOP_ITERS) {
ASSERT_NOT_REACHED();
map = NULL;
break;
}
addr = NULL; /* pick a new one */
}
#endif
return map;
}
bool
os_unmap_file(byte *map, size_t size)
{
if (DYNAMO_OPTION(vm_reserve) && is_vmm_reserved_address(map, size, NULL, NULL)) {
/* XXX i#3570: We'd prefer to have the VMM perform this to ensure it matches
* how it originally reserved the memory. To do that would we expose a way
* to ask for MAP_FIXED in os_heap_reserve*()?
*/
byte *addr = mmap_syscall(map, size, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (!mmap_syscall_succeeded(addr))
return false;
return heap_unreserve_for_external_mapping(map, size,
VMM_SPECIAL_MMAP | VMM_REACHABLE);
}
long res = munmap_syscall(map, size);
return (res == 0);
}
#ifdef LINUX
static void
os_get_memory_file_shm_path(const char *name, OUT char *buf, size_t bufsz)
{
snprintf(buf, bufsz, "/dev/shm/%s.%d", name, get_process_id());
buf[bufsz - 1] = '\0';
}
#endif
file_t
os_create_memory_file(const char *name, size_t size)
{
#ifdef LINUX
char path[MAXIMUM_PATH];
file_t fd;
/* We need an in-memory file. We prefer the new memfd_create over /dev/shm (it
* has no name conflict issues, stale files left around on a crash, or
* reliance on tmpfs).
*/
# ifdef SYS_memfd_create
snprintf(path, BUFFER_SIZE_ELEMENTS(path), "/%s.%d", name, get_process_id());
NULL_TERMINATE_BUFFER(path);
fd = dynamorio_syscall(SYS_memfd_create, 2, path, 0);
# else
fd = -ENOSYS;
# endif
if (fd == -ENOSYS) {
/* Fall back on /dev/shm. */
os_get_memory_file_shm_path(name, path, BUFFER_SIZE_ELEMENTS(path));
NULL_TERMINATE_BUFFER(path);
fd = open_syscall(path, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
if (fd == -EEXIST) {
/* We assume a stale file from some prior crash. */
SYSLOG_INTERNAL_WARNING("Removing presumed-stale %s", path);
os_delete_file(path);
fd = open_syscall(path, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
}
}
if (fd < 0)
return INVALID_FILE;
/* Work around an IMA (kernel optional feature "Integrity Measurement
* Architecture") slowdown where the first executable mmap causes a hash
* to be computed of the entire file size, which can take 5 or 10
* *seconds* for gigabyte files. This is only done once, so if we
* trigger it while the file is tiny, we can avoid the delay later.
*/
byte *temp_map = mmap_syscall(0, PAGE_SIZE, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
if (mmap_syscall_succeeded(temp_map))
munmap_syscall(temp_map, PAGE_SIZE);
/* Else, not fatal: this may not be destined for a later executable mapping anyway. */
if (dynamorio_syscall(SYS_ftruncate, 2, fd, size) < 0) {
close_syscall(fd);
return INVALID_FILE;
}
file_t priv_fd = fd_priv_dup(fd);
close_syscall(fd); /* Close the old descriptor on success *and* error. */
if (priv_fd < 0) {
return INVALID_FILE;
}
fd = priv_fd;
fd_mark_close_on_exec(fd); /* We could use MFD_CLOEXEC for memfd_create. */
return fd;
#else
ASSERT_NOT_IMPLEMENTED(false && "i#3556 NYI for Mac");
return INVALID_FILE;
#endif
}
void
os_delete_memory_file(const char *name, file_t fd)
{
#ifdef LINUX
/* There is no need to delete a memfd_create path, but if we used shm we need
* to clean it up. We blindly do this rather than trying to record whether
* we created this file.
*/
char path[MAXIMUM_PATH];
os_get_memory_file_shm_path(name, path, BUFFER_SIZE_ELEMENTS(path));
NULL_TERMINATE_BUFFER(path);
os_delete_file(path);
close_syscall(fd);
#else
ASSERT_NOT_IMPLEMENTED(false && "i#3556 NYI for Mac");
#endif
}
bool
os_get_disk_free_space(/*IN*/ file_t file_handle,
/*OUT*/ uint64 *AvailableQuotaBytes /*OPTIONAL*/,
/*OUT*/ uint64 *TotalQuotaBytes /*OPTIONAL*/,
/*OUT*/ uint64 *TotalVolumeBytes /*OPTIONAL*/)
{
/* libc struct seems to match kernel's */
struct statfs stat;
ptr_int_t res = dynamorio_syscall(SYS_fstatfs, 2, file_handle, &stat);
if (res != 0) {
LOG(THREAD_GET, LOG_SYSCALLS, 2, "%s failed: " PIFX "\n", __func__, res);
return false;
}
LOG(GLOBAL, LOG_STATS, 3,
"os_get_disk_free_space: avail=" SZFMT ", free=" SZFMT ", bsize=" SZFMT "\n",
stat.f_bavail, stat.f_bfree, stat.f_bsize);
if (AvailableQuotaBytes != NULL)
*AvailableQuotaBytes = ((uint64)stat.f_bavail * stat.f_bsize);
/* no support for quotas */
if (TotalQuotaBytes != NULL)
*TotalQuotaBytes = ((uint64)stat.f_bavail * stat.f_bsize);
if (TotalVolumeBytes != NULL) /* despite name this is how much is free */
*TotalVolumeBytes = ((uint64)stat.f_bfree * stat.f_bsize);
return true;
}
#ifdef LINUX
static bool
symlink_is_self_exe(const char *path)
{
/* Look for "/proc/%d/exe" where %d exists in /proc/self/task/%d,
* or "/proc/self/exe". Rule out the exe link for another process
* (though it could also be under DR we have no simple way to obtain
* its actual app path).
*/
# define SELF_LEN_LEADER 6 /* "/proc/" */
# define SELF_LEN_TRAILER 4 /* "/exe" */
# define SELF_LEN_MAX 18
size_t len = strlen(path);
if (strcmp(path, "/proc/self/exe") == 0)
return true;
if (len < SELF_LEN_MAX && /* /proc/nnnnnn/exe */
strncmp(path, "/proc/", SELF_LEN_LEADER) == 0 &&
strncmp(path + len - SELF_LEN_TRAILER, "/exe", SELF_LEN_TRAILER) == 0) {
int pid;
if (sscanf(path + SELF_LEN_LEADER, "%d", &pid) == 1) {
char task[32];
snprintf(task, BUFFER_SIZE_ELEMENTS(task), "/proc/self/task/%d", pid);
NULL_TERMINATE_BUFFER(task);
return os_file_exists(task, true /*dir*/);
}
}
return false;
}
#endif
void
exit_process_syscall(long status)
{
/* We now assume SYS_exit_group is defined: not building on old machines,
* but will execute there. We try exit_group and if it fails we use exit.
*
* FIXME: if no exit_group, kill all other threads (==processes in same addr
* space) manually? Presumably we got here b/c at an unsafe point to do
* full exit? Or is that not true: what about dr_abort()?
*/
dynamorio_syscall(SYSNUM_EXIT_PROCESS, 1, status);
/* would assert that result is -ENOSYS but assert likely calls us => infinite loop */
exit_thread_syscall(status);
ASSERT_NOT_REACHED();
}
void
exit_thread_syscall(long status)
{
#ifdef MACOS
mach_port_t thread_port = dynamorio_mach_syscall(MACH_thread_self_trap, 0);
/* FIXME i#1403: on MacOS we fail to free the app's stack: we need to pass it to
* bsdthread_terminate.
*/
dynamorio_syscall(SYSNUM_EXIT_THREAD, 4, 0, 0, thread_port, 0);
#else
dynamorio_syscall(SYSNUM_EXIT_THREAD, 1, status);
#endif
}
/* FIXME: this one will not be easily internationalizable
yet it is easier to have a syslog based Unix implementation with real strings.
*/
void
os_syslog(syslog_event_type_t priority, uint message_id, uint substitutions_num,
va_list args)
{
int native_priority;
switch (priority) {
case SYSLOG_INFORMATION: native_priority = LOG_INFO; break;
case SYSLOG_WARNING: native_priority = LOG_WARNING; break;
case SYSLOG_CRITICAL: native_priority = LOG_CRIT; break;
case SYSLOG_ERROR: native_priority = LOG_ERR; break;
default: ASSERT_NOT_REACHED();
}
/* can amount to passing a format string (careful here) to vsyslog */
/* Never let user controlled data in the format string! */
ASSERT_NOT_IMPLEMENTED(false);
}
/* This is subject to races, but should only happen at init/attach when
* there should only be one live thread.
*/
static bool
safe_read_via_query(const void *base, size_t size, void *out_buf, size_t *bytes_read)
{
bool res = false;
size_t num_read = 0;
ASSERT(!fault_handling_initialized);
/* XXX: in today's init ordering, allmem will never be initialized when we come
* here, but we check it nevertheless to be general in case this routine is
* ever called at some later time
*/
if (IF_MEMQUERY_ELSE(false, memcache_initialized()))
res = is_readable_without_exception_internal(base, size, false /*use allmem*/);
else
res = is_readable_without_exception_query_os((void *)base, size);
if (res) {
memcpy(out_buf, base, size);
num_read = size;
}
if (bytes_read != NULL)
*bytes_read = num_read;
return res;
}
bool
safe_read_ex(const void *base, size_t size, void *out_buf, size_t *bytes_read)
{
STATS_INC(num_safe_reads);
/* XXX i#350: we'd like to always use safe_read_fast() and remove this extra
* call layer, but safe_read_fast() requires fault handling to be set up.
* We do set up an early signal handler in d_r_os_init(),
* but there is still be a window prior to that with no handler.
*/
if (!fault_handling_initialized) {
return safe_read_via_query(base, size, out_buf, bytes_read);
} else {
return safe_read_fast(base, size, out_buf, bytes_read);
}
}
bool
safe_read_if_fast(const void *base, size_t size, void *out_buf)
{
if (!fault_handling_initialized) {
memcpy(out_buf, base, size);
return true;
} else {
return safe_read_ex(base, size, out_buf, NULL);
}
}
/* FIXME - fold this together with safe_read_ex() (is a lot of places to update) */
bool
d_r_safe_read(const void *base, size_t size, void *out_buf)
{
return safe_read_ex(base, size, out_buf, NULL);
}
bool
safe_write_ex(void *base, size_t size, const void *in_buf, size_t *bytes_written)
{
return safe_write_try_except(base, size, in_buf, bytes_written);
}
/* is_readable_without_exception checks to see that all bytes with addresses
* from pc to pc+size-1 are readable and that reading from there won't
* generate an exception. if 'from_os' is true, check what the os thinks
* the prot bits are instead of using the all memory list.
*/
static bool
is_readable_without_exception_internal(const byte *pc, size_t size, bool query_os)
{
uint prot = MEMPROT_NONE;
byte *check_pc = (byte *)ALIGN_BACKWARD(pc, PAGE_SIZE);
if (size > ((byte *)POINTER_MAX - pc))
size = (byte *)POINTER_MAX - pc;
do {
bool rc = query_os ? get_memory_info_from_os(check_pc, NULL, NULL, &prot)
: get_memory_info(check_pc, NULL, NULL, &prot);
if (!rc || !TESTANY(MEMPROT_READ | MEMPROT_EXEC, prot))
return false;
if (POINTER_OVERFLOW_ON_ADD(check_pc, PAGE_SIZE))
break;
check_pc += PAGE_SIZE;
} while (check_pc < pc + size);
return true;
}
bool
is_readable_without_exception(const byte *pc, size_t size)
{
/* case 9745 / i#853: We've had problems with all_memory_areas not being
* accurate in the past. Parsing proc maps is too slow for some apps, so we
* use a runtime option.
*/
bool query_os = IF_MEMQUERY_ELSE(true, !DYNAMO_OPTION(use_all_memory_areas));
return is_readable_without_exception_internal(pc, size, query_os);
}
/* Identical to is_readable_without_exception except that the os is queried
* for info on the indicated region */
bool
is_readable_without_exception_query_os(byte *pc, size_t size)
{
return is_readable_without_exception_internal(pc, size, true);
}
bool
is_readable_without_exception_query_os_noblock(byte *pc, size_t size)
{
if (memquery_from_os_will_block())
return false;
return is_readable_without_exception_internal(pc, size, true);
}
bool
is_user_address(byte *pc)
{
/* FIXME: NYI */
/* note returning true will always skip the case 9022 logic on Linux */
return true;
}
/* change protections on memory region starting at pc of length length
* this does not update the all memory area info
*/
bool
os_set_protection(byte *pc, size_t length, uint prot /*MEMPROT_*/)
{
app_pc start_page = (app_pc)PAGE_START(pc);
uint num_bytes = ALIGN_FORWARD(length + (pc - start_page), PAGE_SIZE);
long res = 0;
uint flags = memprot_to_osprot(prot);
DOSTATS({
/* once on each side of prot, to get on right side of writability */
if (!TEST(PROT_WRITE, flags)) {
STATS_INC(protection_change_calls);
STATS_ADD(protection_change_pages, num_bytes / PAGE_SIZE);
}
});
res = mprotect_syscall((void *)start_page, num_bytes, flags);
if (res != 0)
return false;
LOG(THREAD_GET, LOG_VMAREAS, 3,
"change_prot(" PFX ", " PIFX ", %s) => "
"mprotect(" PFX ", " PIFX ", %d)==%d pages\n",
pc, length, memprot_string(prot), start_page, num_bytes, flags,
num_bytes / PAGE_SIZE);
DOSTATS({
/* once on each side of prot, to get on right side of writability */
if (TEST(PROT_WRITE, flags)) {
STATS_INC(protection_change_calls);
STATS_ADD(protection_change_pages, num_bytes / PAGE_SIZE);
}
});
return true;
}
/* change protections on memory region starting at pc of length length */
bool
set_protection(byte *pc, size_t length, uint prot /*MEMPROT_*/)
{
if (os_set_protection(pc, length, prot) == false)
return false;
#ifndef HAVE_MEMINFO_QUERY
else {
app_pc start_page = (app_pc)PAGE_START(pc);
uint num_bytes = ALIGN_FORWARD(length + (pc - start_page), PAGE_SIZE);
memcache_update_locked(start_page, start_page + num_bytes, prot,
-1 /*type unchanged*/, true /*exists*/);
}
#endif
return true;
}
/* change protections on memory region starting at pc of length length */
bool
change_protection(byte *pc, size_t length, bool writable)
{
if (writable)
return make_writable(pc, length);
else
make_unwritable(pc, length);
return true;
}
/* make pc's page writable */
bool
make_writable(byte *pc, size_t size)
{
long res;
app_pc start_page = (app_pc)PAGE_START(pc);
size_t prot_size = (size == 0) ? PAGE_SIZE : size;
uint prot = PROT_EXEC | PROT_READ | PROT_WRITE;
/* if can get current protection then keep old read/exec flags.
* this is crucial on modern linux kernels which refuse to mark stack +x.
*/
if (!is_in_dynamo_dll(pc) /*avoid allmem assert*/ &&
#ifdef STATIC_LIBRARY
/* FIXME i#975: is_in_dynamo_dll() is always false for STATIC_LIBRARY,
* but we can't call get_memory_info() until allmem is initialized. Our
* uses before then are for patching x86.asm, which is OK.
*/
IF_NO_MEMQUERY(memcache_initialized() &&)
#endif
get_memory_info(pc, NULL, NULL, &prot))
prot |= PROT_WRITE;
ASSERT(start_page == pc && ALIGN_FORWARD(size, PAGE_SIZE) == size);
res = mprotect_syscall((void *)start_page, prot_size, prot);
LOG(THREAD_GET, LOG_VMAREAS, 3, "make_writable: pc " PFX " -> " PFX "-" PFX " %d\n",
pc, start_page, start_page + prot_size, res);
ASSERT(res == 0);
if (res != 0)
return false;
STATS_INC(protection_change_calls);
STATS_ADD(protection_change_pages, size / PAGE_SIZE);
#ifndef HAVE_MEMINFO_QUERY
/* update all_memory_areas list with the protection change */
if (memcache_initialized()) {
memcache_update_locked(start_page, start_page + prot_size,
osprot_to_memprot(prot), -1 /*type unchanged*/,
true /*exists*/);
}
#endif
return true;
}
/* like make_writable but adds COW */
bool
make_copy_on_writable(byte *pc, size_t size)
{
/* FIXME: for current usage this should be fine */
return make_writable(pc, size);
}
/* make pc's page unwritable */
void
make_unwritable(byte *pc, size_t size)
{
long res;
app_pc start_page = (app_pc)PAGE_START(pc);
size_t prot_size = (size == 0) ? PAGE_SIZE : size;
uint prot = PROT_EXEC | PROT_READ;
/* if can get current protection then keep old read/exec flags.
* this is crucial on modern linux kernels which refuse to mark stack +x.
*/
if (!is_in_dynamo_dll(pc) /*avoid allmem assert*/ &&
#ifdef STATIC_LIBRARY
/* FIXME i#975: is_in_dynamo_dll() is always false for STATIC_LIBRARY,
* but we can't call get_memory_info() until allmem is initialized. Our
* uses before then are for patching x86.asm, which is OK.
*/
IF_NO_MEMQUERY(memcache_initialized() &&)
#endif
get_memory_info(pc, NULL, NULL, &prot))
prot &= ~PROT_WRITE;
ASSERT(start_page == pc && ALIGN_FORWARD(size, PAGE_SIZE) == size);
/* inc stats before making unwritable, in case messing w/ data segment */
STATS_INC(protection_change_calls);
STATS_ADD(protection_change_pages, size / PAGE_SIZE);
res = mprotect_syscall((void *)start_page, prot_size, prot);
LOG(THREAD_GET, LOG_VMAREAS, 3, "make_unwritable: pc " PFX " -> " PFX "-" PFX "\n",
pc, start_page, start_page + prot_size);
ASSERT(res == 0);
#ifndef HAVE_MEMINFO_QUERY
/* update all_memory_areas list with the protection change */
if (memcache_initialized()) {
memcache_update_locked(start_page, start_page + prot_size,
osprot_to_memprot(prot), -1 /*type unchanged*/,
false /*!exists*/);
}
#endif
}
/****************************************************************************/
/* SYSTEM CALLS */
/* SYS_ defines are in /usr/include/bits/syscall.h
* numbers used by libc are in /usr/include/asm/unistd.h
* kernel defines are in /usr/src/linux-2.4/include/asm-i386/unistd.h
* kernel function names are in /usr/src/linux/arch/i386/kernel/entry.S
*
* For now, we've copied the SYS/NR defines from syscall.h and unistd.h
* and put them in our own local syscall.h.
*/
/* num_raw should be the xax register value.
* For a live system call, dcontext_live should be passed (for examining
* the dcontext->last_exit and exit_reason flags); otherwise, gateway should
* be passed.
*/
int
os_normalized_sysnum(int num_raw, instr_t *gateway, dcontext_t *dcontext)
{
#ifdef MACOS
/* The x64 encoding indicates the syscall type in the top 8 bits.
* We drop the 0x2000000 for BSD so we can use the SYS_ enum constants.
* That leaves 0x1000000 for Mach and 0x3000000 for Machdep.
* On 32-bit, a different encoding is used: we transform that
* to the x64 encoding minus BSD.
*/
int interrupt = 0;
int num = 0;
if (gateway != NULL) {
if (instr_is_interrupt(gateway))
interrupt = instr_get_interrupt_number(gateway);
} else {
ASSERT(dcontext != NULL);
if (TEST(LINK_SPECIAL_EXIT, dcontext->last_exit->flags)) {
if (dcontext->upcontext.upcontext.exit_reason ==
EXIT_REASON_NI_SYSCALL_INT_0x81)
interrupt = 0x81;
else {
ASSERT(dcontext->upcontext.upcontext.exit_reason ==
EXIT_REASON_NI_SYSCALL_INT_0x82);
interrupt = 0x82;
}
}
}
# ifdef X64
if (num_raw >> 24 == 0x2)
return (int)(num_raw & 0xffffff); /* Drop BSD bit */
else
num = (int)num_raw; /* Keep Mach and Machdep bits */
# else
if ((ptr_int_t)num_raw < 0) /* Mach syscall */
return (SYSCALL_NUM_MARKER_MACH | -(int)num_raw);
else {
/* Bottom 16 bits are the number, top are arg size. */
num = (int)(num_raw & 0xffff);
}
# endif
if (interrupt == 0x81)
num |= SYSCALL_NUM_MARKER_MACH;
else if (interrupt == 0x82)
num |= SYSCALL_NUM_MARKER_MACHDEP;
return num;
#else
return num_raw;
#endif
}
static bool
ignorable_system_call_normalized(int num)
{
switch (num) {
#if defined(SYS_exit_group)
case SYS_exit_group:
#endif
case SYS_exit:
#ifdef MACOS
case SYS_bsdthread_terminate:
#endif
#ifdef LINUX
case SYS_brk:
# ifdef SYS_uselib
case SYS_uselib:
# endif
#endif
#if defined(X64) || !defined(ARM)
case SYS_mmap:
#endif
#if !defined(X64) && !defined(MACOS)
case SYS_mmap2:
#endif
case SYS_munmap:
#ifdef LINUX
case SYS_mremap:
#endif
case SYS_mprotect:
#ifdef ANDROID
case SYS_prctl:
#endif
case SYS_execve:
#ifdef LINUX
case SYS_clone3:
case SYS_clone:
#elif defined(MACOS)
case SYS_bsdthread_create:
case SYS_posix_spawn:
#endif
#ifdef SYS_fork
case SYS_fork:
#endif
#ifdef SYS_vfork
case SYS_vfork:
#endif
case SYS_kill:
#if defined(SYS_tkill)
case SYS_tkill:
#endif
#if defined(SYS_tgkill)
case SYS_tgkill:
#endif
#if defined(LINUX) && !defined(X64) && !defined(ARM)
case SYS_signal:
#endif
#ifdef MACOS
case SYS_sigsuspend_nocancel:
#endif
#if !defined(X64) || defined(MACOS)
case SYS_sigaction:
case SYS_sigsuspend:
case SYS_sigpending:
case SYS_sigreturn:
case SYS_sigprocmask:
#endif
#ifdef LINUX
case SYS_rt_sigreturn:
case SYS_rt_sigaction:
case SYS_rt_sigprocmask:
case SYS_rt_sigpending:
# ifdef SYS_rt_sigtimedwait_time64
case SYS_rt_sigtimedwait_time64:
# endif
case SYS_rt_sigtimedwait:
case SYS_rt_sigqueueinfo:
case SYS_rt_sigsuspend:
# ifdef SYS_signalfd
case SYS_signalfd:
# endif
case SYS_signalfd4:
#endif
case SYS_sigaltstack:
#if defined(LINUX) && !defined(X64) && !defined(ARM)
case SYS_sgetmask:
case SYS_ssetmask:
#endif
case SYS_setitimer:
case SYS_getitimer:
#ifdef MACOS
case SYS_close_nocancel:
#endif
#ifdef SYS_close_range
case SYS_close_range:
#endif
case SYS_close:
#ifdef SYS_dup2
case SYS_dup2:
#endif
#ifdef LINUX
case SYS_dup3:
#endif
#ifdef MACOS
case SYS_fcntl_nocancel:
#endif
case SYS_fcntl:
#if defined(X64) || !defined(ARM)
case SYS_getrlimit:
#endif
#if defined(LINUX) && !defined(X64)
case SYS_ugetrlimit:
#endif
case SYS_setrlimit:
#ifdef LINUX
case SYS_prlimit64:
#endif
#if defined(LINUX) && defined(X86)
/* i#784: app may have behavior relying on SIGALRM */
case SYS_alarm:
#endif
/* i#107: syscall might change/query app's seg memory
* need stop app from clobbering our GDT slot.
*/
#if defined(LINUX) && defined(X86) && defined(X64)
case SYS_arch_prctl:
#endif
#if defined(LINUX) && defined(X86)
case SYS_set_thread_area:
case SYS_get_thread_area:
/* FIXME: we might add SYS_modify_ldt later. */
#endif
#if defined(LINUX) && defined(ARM)
/* syscall changes app's thread register */
case SYS_set_tls:
case SYS_cacheflush:
#endif
#if defined(LINUX)
/* Syscalls change procsigmask */
# ifdef SYS_pselect6_time64
case SYS_pselect6_time64:
# endif
case SYS_pselect6:
# ifdef SYS_ppoll_time64
case SYS_ppoll_time64:
# endif
case SYS_ppoll:
case SYS_epoll_pwait:
/* Used as a lazy trigger. */
case SYS_rseq:
#endif
#ifdef DEBUG
# ifdef MACOS
case SYS_open_nocancel:
# endif
# ifdef SYS_open
case SYS_open:
# endif
#endif
return false;
#ifdef LINUX
# ifdef SYS_readlink
case SYS_readlink:
# endif
case SYS_readlinkat: return !DYNAMO_OPTION(early_inject);
#endif
#ifdef SYS_openat2
case SYS_openat2:
#endif
case SYS_openat: return IS_STRING_OPTION_EMPTY(xarch_root);
default:
#ifdef VMX86_SERVER
if (is_vmkuw_sysnum(num))
return vmkuw_ignorable_system_call(num);
#endif
return true;
}
}
bool
ignorable_system_call(int num_raw, instr_t *gateway, dcontext_t *dcontext_live)
{
return ignorable_system_call_normalized(
os_normalized_sysnum(num_raw, gateway, dcontext_live));
}
typedef struct {
unsigned long addr;
unsigned long len;
unsigned long prot;
unsigned long flags;
unsigned long fd;
unsigned long offset;
} mmap_arg_struct_t;
static inline reg_t *
sys_param_addr(dcontext_t *dcontext, int num)
{
/* we force-inline get_mcontext() and so don't take it as a param */
priv_mcontext_t *mc = get_mcontext(dcontext);
#if defined(X86) && defined(X64)
switch (num) {
case 0: return &mc->xdi;
case 1: return &mc->xsi;
case 2: return &mc->xdx;
case 3: return &mc->r10; /* since rcx holds retaddr for syscall instr */
case 4: return &mc->r8;
case 5: return &mc->r9;
default: CLIENT_ASSERT(false, "invalid system call parameter number");
}
#else
# ifdef MACOS
/* XXX: if we don't end up using dcontext->sys_was_int here, we could
* make that field Linux-only.
*/
/* For 32-bit, the args are passed on the stack, above a retaddr slot
* (regardless of whether using a sysenter or int gateway).
*/
return ((reg_t *)mc->esp) + 1 /*retaddr*/ + num;
# endif
/* even for vsyscall where ecx (syscall) or esp (sysenter) are saved into
* ebp, the original parameter registers are not yet changed pre-syscall,
* except for ebp, which is pushed on the stack:
* 0xffffe400 55 push %ebp %esp -> %esp (%esp)
* 0xffffe401 89 cd mov %ecx -> %ebp
* 0xffffe403 0f 05 syscall -> %ecx
*
* 0xffffe400 51 push %ecx %esp -> %esp (%esp)
* 0xffffe401 52 push %edx %esp -> %esp (%esp)
* 0xffffe402 55 push %ebp %esp -> %esp (%esp)
* 0xffffe403 89 e5 mov %esp -> %ebp
* 0xffffe405 0f 34 sysenter -> %esp
*/
switch (num) {
case 0: return &mc->IF_X86_ELSE(xbx, r0);
case 1: return &mc->IF_X86_ELSE(xcx, r1);
case 2: return &mc->IF_X86_ELSE(xdx, r2);
case 3: return &mc->IF_X86_ELSE(xsi, r3);
case 4: return &mc->IF_X86_ELSE(xdi, r4);
/* FIXME: do a safe_read: but what about performance?
* See the #if 0 below, as well. */
case 5:
return IF_X86_ELSE((dcontext->sys_was_int ? &mc->xbp : ((reg_t *)mc->xsp)),
&mc->r5);
# ifdef ARM
/* AArch32 supposedly has 7 args in some cases. */
case 6: return &mc->r6;
# endif
default: CLIENT_ASSERT(false, "invalid system call parameter number");
}
#endif
return 0;
}
static inline reg_t
sys_param(dcontext_t *dcontext, int num)
{
return *sys_param_addr(dcontext, num);
}
void
set_syscall_param(dcontext_t *dcontext, int param_num, reg_t new_value)
{
*sys_param_addr(dcontext, param_num) = new_value;
}
static inline bool
syscall_successful(priv_mcontext_t *mc, int normalized_sysnum)
{
#ifdef MACOS
if (TEST(SYSCALL_NUM_MARKER_MACH, normalized_sysnum)) {
/* XXX: Mach syscalls vary (for some KERN_SUCCESS=0 is success,
* for others that return mach_port_t 0 is failure (I think?).
* We defer to drsyscall.
*/
return ((ptr_int_t)MCXT_SYSCALL_RES(mc) >= 0);
} else
return !TEST(EFLAGS_CF, mc->xflags);
#else
if (normalized_sysnum == IF_X64_ELSE(SYS_mmap, SYS_mmap2) ||
# if !defined(ARM) && !defined(X64)
normalized_sysnum == SYS_mmap ||
# endif
normalized_sysnum == SYS_mremap)
return mmap_syscall_succeeded((byte *)MCXT_SYSCALL_RES(mc));
return ((ptr_int_t)MCXT_SYSCALL_RES(mc) >= 0);
#endif
}
/* For non-Mac, this does nothing to indicate "success": you can pass -errno.
* For Mac, this clears CF and just sets xax. To return a 64-bit value in
* 32-bit mode, the caller must explicitly set xdx as well (we don't always
* do so b/c syscalls that just return 32-bit values do not touch xdx).
*/
static inline void
set_success_return_val(dcontext_t *dcontext, reg_t val)
{
/* since always coming from d_r_dispatch now, only need to set mcontext */
priv_mcontext_t *mc = get_mcontext(dcontext);
#ifdef MACOS
/* On MacOS, success is determined by CF, except for Mach syscalls, but
* there it doesn't hurt to set CF.
*/
mc->xflags &= ~(EFLAGS_CF);
#endif
MCXT_SYSCALL_RES(mc) = val;
}
/* Always pass a positive value for errno */
static inline void
set_failure_return_val(dcontext_t *dcontext, uint errno_val)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
#ifdef MACOS
/* On MacOS, success is determined by CF, and errno is positive */
mc->xflags |= EFLAGS_CF;
MCXT_SYSCALL_RES(mc) = errno_val;
#else
MCXT_SYSCALL_RES(mc) = -(int)errno_val;
#endif
}
DR_API
reg_t
dr_syscall_get_param(void *drcontext, int param_num)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall,
"dr_syscall_get_param() can only be called from pre-syscall event");
return sys_param(dcontext, param_num);
}
DR_API
void
dr_syscall_set_param(void *drcontext, int param_num, reg_t new_value)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_param() can only be called from a syscall event");
*sys_param_addr(dcontext, param_num) = new_value;
}
DR_API
reg_t
dr_syscall_get_result(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(dcontext->client_data->in_post_syscall,
"dr_syscall_get_param() can only be called from post-syscall event");
return MCXT_SYSCALL_RES(get_mcontext(dcontext));
}
DR_API
bool
dr_syscall_get_result_ex(void *drcontext, dr_syscall_result_info_t *info INOUT)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
CLIENT_ASSERT(dcontext->client_data->in_post_syscall,
"only call dr_syscall_get_param_ex() from post-syscall event");
CLIENT_ASSERT(info != NULL, "invalid parameter");
CLIENT_ASSERT(info->size == sizeof(*info), "invalid dr_syscall_result_info_t size");
if (info->size != sizeof(*info))
return false;
info->value = MCXT_SYSCALL_RES(mc);
info->succeeded = syscall_successful(mc, dcontext->sys_num);
if (info->use_high) {
/* MacOS has some 32-bit syscalls that return 64-bit values in
* xdx:xax, but the other syscalls don't clear xdx, so we can't easily
* return a 64-bit value all the time.
*/
IF_X86_ELSE({ info->high = mc->xdx; }, { ASSERT_NOT_REACHED(); });
}
if (info->use_errno) {
if (info->succeeded)
info->errno_value = 0;
else {
info->errno_value = (uint)IF_LINUX(-(int)) MCXT_SYSCALL_RES(mc);
}
}
return true;
}
DR_API
void
dr_syscall_set_result(void *drcontext, reg_t value)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_result() can only be called from a syscall event");
/* For non-Mac, the caller can still pass -errno and this will work */
set_success_return_val(dcontext, value);
}
DR_API
bool
dr_syscall_set_result_ex(void *drcontext, dr_syscall_result_info_t *info)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_result() can only be called from a syscall event");
CLIENT_ASSERT(info->size == sizeof(*info), "invalid dr_syscall_result_info_t size");
if (info->size != sizeof(*info))
return false;
if (info->use_errno) {
if (info->succeeded) {
/* a weird case but we let the user combine these */
set_success_return_val(dcontext, info->errno_value);
} else
set_failure_return_val(dcontext, info->errno_value);
} else {
if (info->succeeded)
set_success_return_val(dcontext, info->value);
else {
/* use this to set CF, even though it might negate the value */
set_failure_return_val(dcontext, (uint)info->value);
/* now set the value, overriding set_failure_return_val() */
MCXT_SYSCALL_RES(mc) = info->value;
}
if (info->use_high) {
/* MacOS has some 32-bit syscalls that return 64-bit values in
* xdx:xax.
*/
IF_X86_ELSE({ mc->xdx = info->high; }, { ASSERT_NOT_REACHED(); });
}
}
return true;
}
DR_API
void
dr_syscall_set_sysnum(void *drcontext, int new_num)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_sysnum() can only be called from a syscall event");
MCXT_SYSNUM_REG(mc) = new_num;
}
DR_API
void
dr_syscall_invoke_another(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(dcontext->client_data->in_post_syscall,
"dr_syscall_invoke_another() can only be called from post-syscall "
"event");
LOG(THREAD, LOG_SYSCALLS, 2, "invoking additional syscall on client request\n");
dcontext->client_data->invoke_another_syscall = true;
#ifdef X86
if (get_syscall_method() == SYSCALL_METHOD_SYSENTER) {
priv_mcontext_t *mc = get_mcontext(dcontext);
/* restore xbp to xsp */
mc->xbp = mc->xsp;
}
#endif /* X86 */
/* for x64 we don't need to copy xcx into r10 b/c we use r10 as our param */
}
static inline bool
is_thread_create_syscall_helper(ptr_uint_t sysnum, uint64 flags)
{
#ifdef MACOS
/* XXX i#1403: we need earlier injection to intercept
* bsdthread_register in order to capture workqueue threads.
*/
return (sysnum == SYS_bsdthread_create || sysnum == SYS_vfork);
#else
# ifdef SYS_vfork
if (sysnum == SYS_vfork)
return true;
# endif
# ifdef LINUX
if ((sysnum == SYS_clone || sysnum == SYS_clone3) && TEST(CLONE_VM, flags))
return true;
# endif
return false;
#endif
}
bool
is_thread_create_syscall(dcontext_t *dcontext _IF_LINUX(void *maybe_clone_args))
{
priv_mcontext_t *mc = get_mcontext(dcontext);
uint64 flags = sys_param(dcontext, 0);
ptr_uint_t sysnum = MCXT_SYSNUM_REG(mc);
#ifdef LINUX
/* For clone3, we use flags from the clone_args that was obtained using a
* a safe read from the user-provided syscall args.
*/
if (sysnum == SYS_clone3) {
ASSERT(maybe_clone_args != NULL);
flags = ((clone3_syscall_args_t *)maybe_clone_args)->flags;
}
#endif
return is_thread_create_syscall_helper(sysnum, flags);
}
#ifdef LINUX
static ptr_uint_t
get_stored_clone3_flags(dcontext_t *dcontext)
{
return ((uint64)dcontext->sys_param4 << 32) | dcontext->sys_param3;
}
#endif
bool
was_thread_create_syscall(dcontext_t *dcontext)
{
uint64 flags = dcontext->sys_param0;
#ifdef LINUX
if (dcontext->sys_num == SYS_clone3)
flags = get_stored_clone3_flags(dcontext);
#endif
return is_thread_create_syscall_helper(dcontext->sys_num, flags);
}
bool
is_sigreturn_syscall_number(int sysnum)
{
#ifdef MACOS
return sysnum == SYS_sigreturn;
#else
return (IF_NOT_X64(sysnum == SYS_sigreturn ||) sysnum == SYS_rt_sigreturn);
#endif
}
bool
is_sigreturn_syscall(dcontext_t *dcontext)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
return is_sigreturn_syscall_number(MCXT_SYSNUM_REG(mc));
}
bool
was_sigreturn_syscall(dcontext_t *dcontext)
{
return is_sigreturn_syscall_number(dcontext->sys_num);
}
/* process a signal this process/thread is sending to itself */
static void
handle_self_signal(dcontext_t *dcontext, uint sig)
{
/* FIXME PR 297903: watch for all DEFAULT_TERMINATE signals,
* and for any thread in the group, not just self.
*
* FIXME PR 297033: watch for SIGSTOP and SIGCONT.
*
* With -intercept_all_signals, we only need to watch for SIGKILL
* and SIGSTOP here, and we avoid the FIXMEs below. If it's fine
* for DR not to clean up on a SIGKILL, then SIGSTOP is all that's
* left (at least once we have PR 297033 and are intercepting the
* various STOP variations and CONT).
*/
if (sig == SIGABRT && !DYNAMO_OPTION(intercept_all_signals)) {
LOG(GLOBAL, LOG_TOP | LOG_SYSCALLS, 1,
"thread " TIDFMT " sending itself a SIGABRT\n", d_r_get_thread_id());
KSTOP(num_exits_dir_syscall);
/* FIXME: need to check whether app has a handler for SIGABRT! */
/* FIXME PR 211180/6723: this will do SYS_exit rather than the SIGABRT.
* Should do set_default_signal_action(SIGABRT) (and set a flag so
* no races w/ another thread re-installing?) and then SYS_kill.
*/
block_cleanup_and_terminate(dcontext, SYSNUM_EXIT_THREAD, -1, 0,
(is_last_app_thread() && !dynamo_exited),
IF_MACOS_ELSE(dcontext->thread_port, 0), 0);
ASSERT_NOT_REACHED();
}
}
/***************************************************************************
* EXECVE
*/
/* when adding here, also add to the switch in handle_execve if necessary */
enum {
ENV_PROP_RUNUNDER,
ENV_PROP_OPTIONS,
ENV_PROP_EXECVE_LOGDIR,
ENV_PROP_EXE_PATH,
ENV_PROP_CONFIGDIR,
};
static const char *const env_to_propagate[] = {
/* these must line up with the enum */
DYNAMORIO_VAR_RUNUNDER,
DYNAMORIO_VAR_OPTIONS,
/* DYNAMORIO_VAR_EXECVE_LOGDIR is different from DYNAMORIO_VAR_LOGDIR:
* - DYNAMORIO_VAR_LOGDIR: a parent dir inside which a new dir will be created;
* - DYNAMORIO_VAR_EXECVE_LOGDIR: the same subdir with the pre-execve process.
* Xref comment in create_log_dir about their precedence.
*/
DYNAMORIO_VAR_EXECVE_LOGDIR,
/* i#909: needed for early injection */
DYNAMORIO_VAR_EXE_PATH,
/* these will only be propagated if they exist */
DYNAMORIO_VAR_CONFIGDIR,
};
#define NUM_ENV_TO_PROPAGATE (sizeof(env_to_propagate) / sizeof(env_to_propagate[0]))
/* Called at pre-SYS_execve to append DR vars in the target process env vars list.
* For late injection via libdrpreload, we call this for *all children, because
* even if -no_follow_children is specified, a whitelist will still ask for takeover
* and it's libdrpreload who checks the whitelist.
* For -early, however, we check the config ahead of time and only call this routine
* if we in fact want to inject.
* XXX i#1679: these parent vs child differences bring up corner cases of which
* config dir takes precedence (if the child clears the HOME env var, e.g.).
*/
static void
add_dr_env_vars(dcontext_t *dcontext, char *inject_library_path, const char *app_path)
{
char **envp = (char **)sys_param(dcontext, 2);
int idx, j, preload = -1, ldpath = -1;
int num_old, num_new, sz;
bool need_var[NUM_ENV_TO_PROPAGATE];
int prop_idx[NUM_ENV_TO_PROPAGATE];
bool ldpath_us = false, preload_us = false;
char **new_envp, *var, *old;
/* check if any var needs to be propagated */
for (j = 0; j < NUM_ENV_TO_PROPAGATE; j++) {
prop_idx[j] = -1;
if (get_config_val(env_to_propagate[j]) == NULL)
need_var[j] = false;
else
need_var[j] = true;
}
/* Special handling for DYNAMORIO_VAR_EXECVE_LOGDIR:
* we only need it if follow_children is true and PROCESS_DIR exists.
*/
if (DYNAMO_OPTION(follow_children) && get_log_dir(PROCESS_DIR, NULL, NULL))
need_var[ENV_PROP_EXECVE_LOGDIR] = true;
else
need_var[ENV_PROP_EXECVE_LOGDIR] = false;
if (DYNAMO_OPTION(early_inject))
need_var[ENV_PROP_EXE_PATH] = true;
/* iterate the env in target process */
if (envp == NULL) {
LOG(THREAD, LOG_SYSCALLS, 3, "\tenv is NULL\n");
idx = 0;
} else {
for (idx = 0; envp[idx] != NULL; idx++) {
/* execve env vars should never be set here */
ASSERT(strstr(envp[idx], DYNAMORIO_VAR_EXECVE) != envp[idx]);
for (j = 0; j < NUM_ENV_TO_PROPAGATE; j++) {
if (strstr(envp[idx], env_to_propagate[j]) == envp[idx]) {
/* If conflict between env and cfg, we assume those env vars
* are for DR usage only, and replace them with cfg value.
*/
prop_idx[j] = idx; /* remember the index for replacing later */
break;
}
}
if (!DYNAMO_OPTION(early_inject) &&
strstr(envp[idx], "LD_LIBRARY_PATH=") == envp[idx]) {
ldpath = idx;
if (strstr(envp[idx], inject_library_path) != NULL)
ldpath_us = true;
}
if (!DYNAMO_OPTION(early_inject) &&
strstr(envp[idx], "LD_PRELOAD=") == envp[idx]) {
preload = idx;
if (strstr(envp[idx], DYNAMORIO_PRELOAD_NAME) != NULL &&
strstr(envp[idx], get_dynamorio_library_path()) != NULL) {
preload_us = true;
}
}
LOG(THREAD, LOG_SYSCALLS, 3, "\tenv %d: %s\n", idx, envp[idx]);
}
}
/* We want to add new env vars, so we create a new envp
* array. We have to deallocate them and restore the old
* envp if execve fails; if execve succeeds, the address
* space is reset so we don't need to do anything.
*/
num_old = idx;
/* how many new env vars we need add */
num_new = 2 + /* execve indicator var plus final NULL */
(DYNAMO_OPTION(early_inject)
? 0
: (((preload < 0) ? 1 : 0) + ((ldpath < 0) ? 1 : 0)));
for (j = 0; j < NUM_ENV_TO_PROPAGATE; j++) {
if ((DYNAMO_OPTION(follow_children) || j == ENV_PROP_EXE_PATH) && need_var[j] &&
prop_idx[j] < 0)
num_new++;
}
/* setup new envp */
new_envp =
heap_alloc(dcontext, sizeof(char *) * (num_old + num_new) HEAPACCT(ACCT_OTHER));
/* copy old envp */
memcpy(new_envp, envp, sizeof(char *) * num_old);
/* change/add preload and ldpath if necessary */
if (!DYNAMO_OPTION(early_inject) && !preload_us) {
int idx_preload;
LOG(THREAD, LOG_SYSCALLS, 1,
"WARNING: execve env does NOT preload DynamoRIO, forcing it!\n");
if (preload >= 0) {
/* replace the existing preload */
const char *dr_lib_path = get_dynamorio_library_path();
sz = strlen(envp[preload]) + strlen(DYNAMORIO_PRELOAD_NAME) +
strlen(dr_lib_path) + 3;
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
old = envp[preload] + strlen("LD_PRELOAD=");
snprintf(var, sz, "LD_PRELOAD=%s %s %s", DYNAMORIO_PRELOAD_NAME, dr_lib_path,
old);
idx_preload = preload;
} else {
/* add new preload */
const char *dr_lib_path = get_dynamorio_library_path();
sz = strlen("LD_PRELOAD=") + strlen(DYNAMORIO_PRELOAD_NAME) +
strlen(dr_lib_path) + 2;
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
snprintf(var, sz, "LD_PRELOAD=%s %s", DYNAMORIO_PRELOAD_NAME, dr_lib_path);
idx_preload = idx++;
}
*(var + sz - 1) = '\0'; /* null terminate */
new_envp[idx_preload] = var;
LOG(THREAD, LOG_SYSCALLS, 2, "\tnew env %d: %s\n", idx_preload,
new_envp[idx_preload]);
}
if (!DYNAMO_OPTION(early_inject) && !ldpath_us) {
int idx_ldpath;
if (ldpath >= 0) {
sz = strlen(envp[ldpath]) + strlen(inject_library_path) + 2;
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
old = envp[ldpath] + strlen("LD_LIBRARY_PATH=");
snprintf(var, sz, "LD_LIBRARY_PATH=%s:%s", inject_library_path, old);
idx_ldpath = ldpath;
} else {
sz = strlen("LD_LIBRARY_PATH=") + strlen(inject_library_path) + 1;
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
snprintf(var, sz, "LD_LIBRARY_PATH=%s", inject_library_path);
idx_ldpath = idx++;
}
*(var + sz - 1) = '\0'; /* null terminate */
new_envp[idx_ldpath] = var;
LOG(THREAD, LOG_SYSCALLS, 2, "\tnew env %d: %s\n", idx_ldpath,
new_envp[idx_ldpath]);
}
/* propagating DR env vars */
for (j = 0; j < NUM_ENV_TO_PROPAGATE; j++) {
const char *val = "";
if (!need_var[j])
continue;
if (!DYNAMO_OPTION(follow_children) && j != ENV_PROP_EXE_PATH)
continue;
switch (j) {
case ENV_PROP_RUNUNDER:
ASSERT(strcmp(env_to_propagate[j], DYNAMORIO_VAR_RUNUNDER) == 0);
/* Must pass RUNUNDER_ALL to get child injected if has no app config.
* If rununder var is already set we assume it's set to 1.
*/
ASSERT((RUNUNDER_ON | RUNUNDER_ALL) == 0x3); /* else, update "3" */
val = "3";
break;
case ENV_PROP_OPTIONS:
ASSERT(strcmp(env_to_propagate[j], DYNAMORIO_VAR_OPTIONS) == 0);
val = d_r_option_string;
break;
case ENV_PROP_EXECVE_LOGDIR:
/* we use PROCESS_DIR for DYNAMORIO_VAR_EXECVE_LOGDIR */
ASSERT(strcmp(env_to_propagate[j], DYNAMORIO_VAR_EXECVE_LOGDIR) == 0);
ASSERT(get_log_dir(PROCESS_DIR, NULL, NULL));
break;
case ENV_PROP_EXE_PATH:
ASSERT(strcmp(env_to_propagate[j], DYNAMORIO_VAR_EXE_PATH) == 0);
val = app_path;
break;
default:
val = getenv(env_to_propagate[j]);
if (val == NULL)
val = "";
break;
}
if (j == ENV_PROP_EXECVE_LOGDIR) {
uint logdir_length;
get_log_dir(PROCESS_DIR, NULL, &logdir_length);
/* logdir_length includes the terminating NULL */
sz = strlen(DYNAMORIO_VAR_EXECVE_LOGDIR) + logdir_length + 1 /* '=' */;
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
snprintf(var, sz, "%s=", DYNAMORIO_VAR_EXECVE_LOGDIR);
get_log_dir(PROCESS_DIR, var + strlen(var), &logdir_length);
} else {
sz = strlen(env_to_propagate[j]) + strlen(val) + 2 /* '=' + null */;
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
snprintf(var, sz, "%s=%s", env_to_propagate[j], val);
}
*(var + sz - 1) = '\0'; /* null terminate */
prop_idx[j] = (prop_idx[j] >= 0) ? prop_idx[j] : idx++;
new_envp[prop_idx[j]] = var;
LOG(THREAD, LOG_SYSCALLS, 2, "\tnew env %d: %s\n", prop_idx[j],
new_envp[prop_idx[j]]);
}
if (!DYNAMO_OPTION(follow_children) && !DYNAMO_OPTION(early_inject)) {
if (prop_idx[ENV_PROP_RUNUNDER] >= 0) {
/* disable auto-following of this execve, yet still allow preload
* on other side to inject if config file exists.
* kind of hacky mangle here:
*/
ASSERT(!need_var[ENV_PROP_RUNUNDER]);
ASSERT(new_envp[prop_idx[ENV_PROP_RUNUNDER]][0] == 'D');
new_envp[prop_idx[ENV_PROP_RUNUNDER]][0] = 'X';
}
}
sz = strlen(DYNAMORIO_VAR_EXECVE) + 4;
/* we always pass this var to indicate "post-execve" */
var = heap_alloc(dcontext, sizeof(char) * sz HEAPACCT(ACCT_OTHER));
/* PR 458917: we overload this to also pass our gdt index */
ASSERT(os_tls_get_gdt_index(dcontext) < 100 &&
os_tls_get_gdt_index(dcontext) >= -1); /* only 2 chars allocated */
snprintf(var, sz, "%s=%02d", DYNAMORIO_VAR_EXECVE, os_tls_get_gdt_index(dcontext));
*(var + sz - 1) = '\0'; /* null terminate */
new_envp[idx++] = var;
LOG(THREAD, LOG_SYSCALLS, 2, "\tnew env %d: %s\n", idx - 1, new_envp[idx - 1]);
/* must end with NULL */
new_envp[idx++] = NULL;
ASSERT((num_new + num_old) == idx);
/* update syscall param */
*sys_param_addr(dcontext, 2) = (reg_t)new_envp; /* OUT */
/* store for reset in case execve fails, and for cleanup if
* this is a vfork thread
*/
dcontext->sys_param0 = (reg_t)envp;
dcontext->sys_param1 = (reg_t)new_envp;
}
static ssize_t
script_file_reader(const char *pathname, void *buf, size_t count)
{
/* FIXME i#2090: Check file is executable. */
file_t file = os_open(pathname, OS_OPEN_READ);
size_t len;
if (file == INVALID_FILE)
return -1;
len = os_read(file, buf, count);
os_close(file);
return len;
}
/* For early injection, recognise when the executable is a script ("#!") and
* modify the syscall parameters to invoke a script interpreter instead. In
* this case we will have allocated memory here but we expect the caller to
* do a non-failing execve of libdynamorio.so and therefore not to have to
* free the memory. That is one reason for checking that the (final) script
* interpreter really is an executable binary.
* We recognise one error case here and return the non-zero error code (ELOOP)
* but in other cases we leave it up to the caller to detect the error, which
* it may do by attempting to exec the path natively, expecting this to fail,
* though there is the obvious danger that the file might have been modified
* just before the exec.
* We do not, and cannot easily, handle a file that is executable but not
* readable. Currently such files will be executed without DynamoRIO though
* in some situations it would be more helpful to stop with an error.
*
* XXX: There is a minor transparency bug with misformed binaries. For example,
* execve can return EINVAL if the ELF executable has more than one PT_INTERP
* segment but we do not check this and so under DynamoRIO the error would be
* detected only after the exec, if we are following the child.
*
* FIXME i#2091: There is a memory leak if a script is recognised, and it is
* later decided not to inject (see where should_inject is set), and the exec
* fails, because in this case there is no mechanism for freeing the memory
* allocated in this function. This function should return sufficient information
* for the caller to free the memory, which it can do so before the exec if it
* reverts to the original syscall arguments and execs the script.
*/
static int
handle_execve_script(dcontext_t *dcontext)
{
char *fname = (char *)sys_param(dcontext, 0);
char **orig_argv = (char **)sys_param(dcontext, 1);
script_interpreter_t *script;
int ret = 0;
script = global_heap_alloc(sizeof(*script) HEAPACCT(ACCT_OTHER));
if (!find_script_interpreter(script, fname, script_file_reader))
goto free_and_return;
if (script->argc == 0) {
ret = ELOOP;
goto free_and_return;
}
/* Check that the final interpreter is an executable binary. */
{
file_t file = os_open(script->argv[0], OS_OPEN_READ);
bool is64;
if (file == INVALID_FILE)
goto free_and_return;
if (!module_file_is_module64(file, &is64, NULL)) {
os_close(file);
goto free_and_return;
}
}
{
size_t i, orig_argc = 0;
char **new_argv;
/* Concatenate new arguments and original arguments. */
while (orig_argv[orig_argc] != NULL)
++orig_argc;
if (orig_argc == 0)
orig_argc = 1;
new_argv = global_heap_alloc((script->argc + orig_argc + 1) *
sizeof(char *) HEAPACCT(ACCT_OTHER));
for (i = 0; i < script->argc; i++)
new_argv[i] = script->argv[i];
new_argv[script->argc] = fname; /* replaces orig_argv[0] */
for (i = 1; i < orig_argc; i++)
new_argv[script->argc + i] = orig_argv[i];
new_argv[script->argc + orig_argc] = NULL;
/* Modify syscall parameters. */
*sys_param_addr(dcontext, 0) = (reg_t)new_argv[0];
*sys_param_addr(dcontext, 1) = (reg_t)new_argv;
}
return 0;
free_and_return:
global_heap_free(script, sizeof(*script) HEAPACCT(ACCT_OTHER));
return ret;
}
static int
handle_execve(dcontext_t *dcontext)
{
/* in /usr/src/linux/arch/i386/kernel/process.c:
* asmlinkage int sys_execve(struct pt_regs regs) { ...
* error = do_execve(filename, (char **) regs.xcx, (char **) regs.xdx, ®s);
* in fs/exec.c:
* int do_execve(char * filename, char ** argv, char ** envp, struct pt_regs * regs)
*/
/* We need to make sure we get injected into the new image:
* we simply make sure LD_PRELOAD contains us, and that our directory
* is on LD_LIBRARY_PATH (seems not to work to put absolute paths in
* LD_PRELOAD).
* FIXME: this doesn't work for setuid programs
*
* For -follow_children we also pass the current DYNAMORIO_RUNUNDER and
* DYNAMORIO_OPTIONS and logdir to the new image to support a simple
* run-all-children model without bothering w/ setting up config files for
* children, and to support injecting across execve that does not
* preserve $HOME.
* FIXME i#287/PR 546544: we'll need to propagate DYNAMORIO_AUTOINJECT too
* once we use it in preload
*/
/* FIXME i#191: supposed to preserve things like pending signal
* set across execve: going to ignore for now
*/
char *fname;
bool x64 = IF_X64_ELSE(true, false);
bool expect_to_fail = false;
bool should_inject;
file_t file;
char *inject_library_path;
char rununder_buf[16]; /* just an integer printed in ascii */
bool app_specific, from_env, rununder_on;
#if defined(LINUX) || defined(DEBUG)
const char **argv;
#endif
if (DYNAMO_OPTION(follow_children) && DYNAMO_OPTION(early_inject)) {
int ret = handle_execve_script(dcontext);
if (ret != 0)
return ret;
}
fname = (char *)sys_param(dcontext, 0);
#if defined(LINUX) || defined(DEBUG)
argv = (const char **)sys_param(dcontext, 1);
#endif
#ifdef LINUX
if (DYNAMO_OPTION(early_inject) && symlink_is_self_exe(fname)) {
/* i#907: /proc/self/exe points at libdynamorio.so. Make sure we run
* the right thing here.
*/
fname = get_application_name();
}
#endif
LOG(GLOBAL, LOG_ALL, 1,
"\n---------------------------------------------------------------------------"
"\n");
LOG(THREAD, LOG_ALL, 1,
"\n---------------------------------------------------------------------------"
"\n");
DODEBUG({
int i;
SYSLOG_INTERNAL_INFO("-- execve %s --", fname);
LOG(THREAD, LOG_SYSCALLS, 1, "syscall: execve %s\n", fname);
LOG(GLOBAL, LOG_TOP | LOG_SYSCALLS, 1, "execve %s\n", fname);
if (d_r_stats->loglevel >= 3) {
if (argv == NULL) {
LOG(THREAD, LOG_SYSCALLS, 3, "\targs are NULL\n");
} else {
for (i = 0; argv[i] != NULL; i++) {
LOG(THREAD, LOG_SYSCALLS, 2, "\targ %d: len=%d\n", i,
strlen(argv[i]));
LOG(THREAD, LOG_SYSCALLS, 3, "\targ %d: %s\n", i, argv[i]);
}
}
}
});
/* i#237/PR 498284: if we're a vfork "thread" we're really in a different
* process and if we exec then the parent process will still be alive. We
* can't easily clean our own state (dcontext, dstack, etc.) up in our
* parent process: we need it to invoke the syscall and the syscall might
* fail. We could expand cleanup_and_terminate to also be able to invoke
* SYS_execve: but execve seems more likely to fail than termination
* syscalls. Our solution is to mark this thread as "execve" and hide it
* from regular thread queries; we clean it up in the process-exiting
* synch_with_thread(), or if the same parent thread performs another vfork
* (to prevent heap accumulation from repeated vfork+execve). Since vfork
* on linux suspends the parent, there cannot be any races with the execve
* syscall completing: there can't even be peer vfork threads, so we could
* set a flag and clean up in d_r_dispatch, but that seems overkill. (If vfork
* didn't suspend the parent we'd need to touch a marker file or something
* to know the execve was finished.)
*/
mark_thread_execve(dcontext->thread_record, true);
#ifdef STATIC_LIBRARY
/* no way we can inject, we just lose control */
SYSLOG_INTERNAL_WARNING("WARNING: static DynamoRIO library, losing control on "
"execve");
return 0;
#endif
/* Issue 20: handle cross-architecture execve */
file = os_open(fname, OS_OPEN_READ);
if (file != INVALID_FILE) {
if (!module_file_is_module64(file, &x64,
NULL /*only care about primary==execve*/))
expect_to_fail = true;
os_close(file);
} else
expect_to_fail = true;
inject_library_path =
IF_X64_ELSE(x64, !x64) ? dynamorio_library_path : dynamorio_alt_arch_path;
should_inject = DYNAMO_OPTION(follow_children);
if (get_config_val_other_app(get_short_name(fname), get_process_id(),
x64 ? DR_PLATFORM_64BIT : DR_PLATFORM_32BIT,
DYNAMORIO_VAR_RUNUNDER, rununder_buf,
BUFFER_SIZE_ELEMENTS(rununder_buf), &app_specific,
&from_env, NULL /* 1config is ok */)) {
if (should_inject_from_rununder(rununder_buf, app_specific, from_env,
&rununder_on))
should_inject = rununder_on;
}
if (should_inject)
add_dr_env_vars(dcontext, inject_library_path, fname);
else {
dcontext->sys_param0 = 0;
dcontext->sys_param1 = 0;
}
#ifdef LINUX
/* We have to be accurate with expect_to_fail as we cannot come back
* and fail the syscall once the kernel execs DR!
*/
if (should_inject && DYNAMO_OPTION(early_inject) && !expect_to_fail) {
/* i#909: change the target image to libdynamorio.so */
const char *drpath = IF_X64_ELSE(x64, !x64) ? dynamorio_library_filepath
: dynamorio_alt_arch_filepath;
TRY_EXCEPT(dcontext, /* try */
{
if (symlink_is_self_exe(argv[0])) {
/* we're out of sys_param entries so we assume argv[0] == fname
*/
dcontext->sys_param3 = (reg_t)argv;
argv[0] = fname; /* XXX: handle readable but not writable! */
} else
dcontext->sys_param3 = 0; /* no restore in post */
dcontext->sys_param4 =
(reg_t)fname; /* store for restore in post */
*sys_param_addr(dcontext, 0) = (reg_t)drpath;
LOG(THREAD, LOG_SYSCALLS, 2, "actual execve on: %s\n",
(char *)sys_param(dcontext, 0));
},
/* except */
{
dcontext->sys_param3 = 0; /* no restore in post */
dcontext->sys_param4 = 0; /* no restore in post */
LOG(THREAD, LOG_SYSCALLS, 2,
"argv is unreadable, expect execve to fail\n");
});
} else {
dcontext->sys_param3 = 0; /* no restore in post */
dcontext->sys_param4 = 0; /* no restore in post */
}
#endif
/* we need to clean up the .1config file here. if the execve fails,
* we'll just live w/o dynamic option re-read.
*/
d_r_config_exit();
return 0;
}
static void
handle_execve_post(dcontext_t *dcontext)
{
/* if we get here it means execve failed (doesn't return on success),
* or we did an execve from a vfork and its memory changes are visible
* in the parent process.
* we have to restore env to how it was and free the allocated heap.
*/
char **old_envp = (char **)dcontext->sys_param0;
char **new_envp = (char **)dcontext->sys_param1;
#ifdef STATIC_LIBRARY
/* nothing to clean up */
return;
#endif
#ifdef LINUX
if (dcontext->sys_param4 != 0) {
/* restore original /proc/.../exe */
*sys_param_addr(dcontext, 0) = dcontext->sys_param4;
if (dcontext->sys_param3 != 0) {
/* restore original argv[0] */
const char **argv = (const char **)dcontext->sys_param3;
argv[0] = (const char *)dcontext->sys_param4;
}
}
#endif
if (new_envp != NULL) {
int i;
LOG(THREAD, LOG_SYSCALLS, 2, "\tcleaning up our env vars\n");
/* we replaced existing ones and/or added new ones.
* we can't compare to old_envp b/c it may have changed by now.
*/
for (i = 0; new_envp[i] != NULL; i++) {
if (is_dynamo_address((byte *)new_envp[i])) {
heap_free(dcontext, new_envp[i],
sizeof(char) * (strlen(new_envp[i]) + 1) HEAPACCT(ACCT_OTHER));
}
}
i++; /* need to de-allocate final null slot too */
heap_free(dcontext, new_envp, sizeof(char *) * i HEAPACCT(ACCT_OTHER));
/* restore prev envp if we're post-syscall */
if (!dcontext->thread_record->execve)
*sys_param_addr(dcontext, 2) = (reg_t)old_envp;
}
}
/* i#237/PR 498284: to avoid accumulation of thread state we clean up a vfork
* child who invoked execve here so we have at most one outstanding thread. we
* also clean up at process exit and before thread creation. we could do this
* in d_r_dispatch but too rare to be worth a flag check there.
*/
static void
cleanup_after_vfork_execve(dcontext_t *dcontext)
{
thread_record_t **threads;
int num_threads, i;
if (num_execve_threads == 0)
return;
d_r_mutex_lock(&thread_initexit_lock);
get_list_of_threads_ex(&threads, &num_threads, true /*include execve*/);
for (i = 0; i < num_threads; i++) {
if (threads[i]->execve) {
LOG(THREAD, LOG_SYSCALLS, 2, "cleaning up earlier vfork thread " TIDFMT "\n",
threads[i]->id);
dynamo_other_thread_exit(threads[i]);
}
}
d_r_mutex_unlock(&thread_initexit_lock);
global_heap_free(threads,
num_threads * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT));
}
static void
set_stdfile_fileno(stdfile_t **stdfile, file_t file_no)
{
#ifdef STDFILE_FILENO
(*stdfile)->STDFILE_FILENO = file_no;
#else
# warning stdfile_t is opaque; DynamoRIO will not set fds of libc FILEs.
/* i#1973: musl libc support (and potentially other non-glibcs) */
/* only called by handle_close_pre(), so warning is specific to that. */
SYSLOG_INTERNAL_WARNING_ONCE(
"DynamoRIO cannot set the file descriptors of private libc FILEs on "
"this platform. Client usage of stdio.h stdin, stdout, or stderr may "
"no longer work as expected, because the app is closing the UNIX fds "
"backing these.");
#endif
}
/* returns whether to execute syscall */
static bool
handle_close_generic_pre(dcontext_t *dcontext, file_t fd, bool set_return_val)
{
LOG(THREAD, LOG_SYSCALLS, 3, "syscall: close fd %d\n", fd);
/* prevent app from closing our files */
if (fd_is_dr_owned(fd)) {
SYSLOG_INTERNAL_WARNING_ONCE("app trying to close DR file(s)");
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"WARNING: app trying to close DR file %d! Not allowing it.\n", fd);
if (set_return_val) {
if (DYNAMO_OPTION(fail_on_stolen_fds)) {
set_failure_return_val(dcontext, EBADF);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else
set_success_return_val(dcontext, 0);
}
return false; /* do not execute syscall */
}
/* Xref PR 258731 - duplicate STDOUT/STDERR when app closes them so we (or
* a client) can continue to use them for logging. */
if (DYNAMO_OPTION(dup_stdout_on_close) && fd == STDOUT) {
our_stdout = fd_priv_dup(fd);
if (our_stdout < 0) /* no private fd available */
our_stdout = dup_syscall(fd);
if (our_stdout >= 0)
fd_mark_close_on_exec(our_stdout);
fd_table_add(our_stdout, 0);
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"WARNING: app is closing stdout=%d - duplicating descriptor for "
"DynamoRIO usage got %d.\n",
fd, our_stdout);
if (privmod_stdout != NULL && INTERNAL_OPTION(private_loader)) {
/* update the privately loaded libc's stdout _fileno. */
set_stdfile_fileno(privmod_stdout, our_stdout);
}
}
if (DYNAMO_OPTION(dup_stderr_on_close) && fd == STDERR) {
our_stderr = fd_priv_dup(fd);
if (our_stderr < 0) /* no private fd available */
our_stderr = dup_syscall(fd);
if (our_stderr >= 0)
fd_mark_close_on_exec(our_stderr);
fd_table_add(our_stderr, 0);
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"WARNING: app is closing stderr=%d - duplicating descriptor for "
"DynamoRIO usage got %d.\n",
fd, our_stderr);
if (privmod_stderr != NULL && INTERNAL_OPTION(private_loader)) {
/* update the privately loaded libc's stderr _fileno. */
set_stdfile_fileno(privmod_stderr, our_stderr);
}
}
if (DYNAMO_OPTION(dup_stdin_on_close) && fd == STDIN) {
our_stdin = fd_priv_dup(fd);
if (our_stdin < 0) /* no private fd available */
our_stdin = dup_syscall(fd);
if (our_stdin >= 0)
fd_mark_close_on_exec(our_stdin);
fd_table_add(our_stdin, 0);
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"WARNING: app is closing stdin=%d - duplicating descriptor for "
"DynamoRIO usage got %d.\n",
fd, our_stdin);
if (privmod_stdin != NULL && INTERNAL_OPTION(private_loader)) {
/* update the privately loaded libc's stdout _fileno. */
set_stdfile_fileno(privmod_stdin, our_stdin);
}
}
return true;
}
static bool
handle_close_pre(dcontext_t *dcontext)
{
return handle_close_generic_pre(dcontext, (uint)sys_param(dcontext, 0),
true /*set_return_val*/);
}
#ifdef SYS_close_range
static bool
handle_close_range_pre(dcontext_t *dcontext, file_t fd)
{
return handle_close_generic_pre(dcontext, fd, false /*set_return_val*/);
}
#endif
/***************************************************************************/
/* Used to obtain the pc of the syscall instr itself when the dcontext dc
* is currently in a syscall handler.
* Alternatively for sysenter we could set app_sysenter_instr_addr for Linux.
*/
#define SYSCALL_PC(dc) \
((get_syscall_method() == SYSCALL_METHOD_INT || \
get_syscall_method() == SYSCALL_METHOD_SYSCALL) \
? (ASSERT(SYSCALL_LENGTH == INT_LENGTH), POST_SYSCALL_PC(dc) - INT_LENGTH) \
: (vsyscall_syscall_end_pc - SYSENTER_LENGTH))
static void
handle_exit(dcontext_t *dcontext)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
bool exit_process = false;
if (dcontext->sys_num == SYSNUM_EXIT_PROCESS) {
/* We can have multiple thread groups within the same address space.
* We need to know whether this is the only group left.
* FIXME: we can have races where new threads are created after our
* check: we'll live with that for now, but the right approach is to
* suspend all threads via synch_with_all_threads(), do the check,
* and if exit_process then exit w/o resuming: though have to
* coordinate lock access w/ cleanup_and_terminate.
* Xref i#94. Xref PR 541760.
*/
process_id_t mypid = get_process_id();
thread_record_t **threads;
int num_threads, i;
exit_process = true;
d_r_mutex_lock(&thread_initexit_lock);
get_list_of_threads(&threads, &num_threads);
for (i = 0; i < num_threads; i++) {
if (threads[i]->pid != mypid && !IS_CLIENT_THREAD(threads[i]->dcontext)) {
exit_process = false;
break;
}
}
if (!exit_process) {
/* We need to clean up the other threads in our group here. */
thread_id_t myid = d_r_get_thread_id();
priv_mcontext_t mcontext;
DEBUG_DECLARE(thread_synch_result_t synch_res;)
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"SYS_exit_group %d not final group: %d cleaning up just "
"threads in group\n",
get_process_id(), d_r_get_thread_id());
/* Set where we are to handle reciprocal syncs */
copy_mcontext(mc, &mcontext);
mc->pc = SYSCALL_PC(dcontext);
for (i = 0; i < num_threads; i++) {
if (threads[i]->id != myid && threads[i]->pid == mypid) {
/* See comments in dynamo_process_exit_cleanup(): we terminate
* to make cleanup easier, but may want to switch to shifting
* the target thread to a stack-free loop.
*/
DEBUG_DECLARE(synch_res =)
synch_with_thread(
threads[i]->id, true /*block*/, true /*have initexit lock*/,
THREAD_SYNCH_VALID_MCONTEXT, THREAD_SYNCH_TERMINATED_AND_CLEANED,
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE);
/* initexit lock may be released and re-acquired in course of
* doing the synch so we may have races where the thread
* exits on its own (or new threads appear): we'll live
* with those for now.
*/
ASSERT(synch_res == THREAD_SYNCH_RESULT_SUCCESS);
}
}
copy_mcontext(&mcontext, mc);
}
d_r_mutex_unlock(&thread_initexit_lock);
global_heap_free(
threads, num_threads * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT));
}
if (is_last_app_thread() && !dynamo_exited) {
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"SYS_exit%s(%d) in final thread " TIDFMT " of " PIDFMT
" => exiting DynamoRIO\n",
(dcontext->sys_num == SYSNUM_EXIT_PROCESS) ? "_group" : "",
MCXT_SYSNUM_REG(mc), d_r_get_thread_id(), get_process_id());
/* we want to clean up even if not automatic startup! */
automatic_startup = true;
exit_process = true;
} else {
LOG(THREAD, LOG_TOP | LOG_THREADS | LOG_SYSCALLS, 1,
"SYS_exit%s(%d) in thread " TIDFMT " of " PIDFMT " => cleaning up %s\n",
(dcontext->sys_num == SYSNUM_EXIT_PROCESS) ? "_group" : "",
MCXT_SYSNUM_REG(mc), d_r_get_thread_id(), get_process_id(),
exit_process ? "process" : "thread");
}
KSTOP(num_exits_dir_syscall);
block_cleanup_and_terminate(dcontext, MCXT_SYSNUM_REG(mc), sys_param(dcontext, 0),
sys_param(dcontext, 1), exit_process,
/* SYS_bsdthread_terminate has 2 more args */
sys_param(dcontext, 2), sys_param(dcontext, 3));
}
#if defined(LINUX) && defined(X86) /* XXX i#58: until we have Mac support */
static bool
os_set_app_thread_area(dcontext_t *dcontext, our_modify_ldt_t *user_desc)
{
# ifdef X86
int i;
os_thread_data_t *ostd = dcontext->os_field;
our_modify_ldt_t *desc = (our_modify_ldt_t *)ostd->app_thread_areas;
if (user_desc->seg_not_present == 1) {
/* find an empty one to update */
for (i = 0; i < GDT_NUM_TLS_SLOTS; i++) {
if (desc[i].seg_not_present == 1)
break;
}
if (i < GDT_NUM_TLS_SLOTS) {
user_desc->entry_number = GDT_SELECTOR(i + tls_min_index());
memcpy(&desc[i], user_desc, sizeof(*user_desc));
} else
return false;
} else {
/* If we used early injection, this might be ld.so trying to set up TLS. We
* direct the app to use the GDT entry we already set up for our private
* libraries, but only the first time it requests TLS.
*/
if (user_desc->entry_number == -1 && return_stolen_lib_tls_gdt) {
d_r_mutex_lock(&set_thread_area_lock);
if (return_stolen_lib_tls_gdt) {
uint selector = read_thread_register(LIB_SEG_TLS);
uint index = SELECTOR_INDEX(selector);
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
return_stolen_lib_tls_gdt = false;
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
user_desc->entry_number = index;
LOG(GLOBAL, LOG_THREADS, 2,
"%s: directing app to use "
"selector 0x%x for first call to set_thread_area\n",
__FUNCTION__, selector);
}
d_r_mutex_unlock(&set_thread_area_lock);
}
/* update the specific one */
i = user_desc->entry_number - tls_min_index();
if (i < 0 || i >= GDT_NUM_TLS_SLOTS)
return false;
LOG(GLOBAL, LOG_THREADS, 2,
"%s: change selector 0x%x base from " PFX " to " PFX "\n", __FUNCTION__,
GDT_SELECTOR(user_desc->entry_number), desc[i].base_addr,
user_desc->base_addr);
memcpy(&desc[i], user_desc, sizeof(*user_desc));
}
/* if not conflict with dr's tls, perform the syscall */
if (!INTERNAL_OPTION(private_loader) &&
GDT_SELECTOR(user_desc->entry_number) != read_thread_register(SEG_TLS) &&
GDT_SELECTOR(user_desc->entry_number) != read_thread_register(LIB_SEG_TLS))
return false;
# elif defined(ARM)
/* FIXME i#1551: NYI on ARM */
ASSERT_NOT_IMPLEMENTED(false);
# endif /* X86/ARM */
return true;
}
static bool
os_get_app_thread_area(dcontext_t *dcontext, our_modify_ldt_t *user_desc)
{
# ifdef X86
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
our_modify_ldt_t *desc = (our_modify_ldt_t *)ostd->app_thread_areas;
int i = user_desc->entry_number - tls_min_index();
if (i < 0 || i >= GDT_NUM_TLS_SLOTS)
return false;
if (desc[i].seg_not_present == 1)
return false;
# elif defined(ARM)
/* FIXME i#1551: NYI on ARM */
ASSERT_NOT_IMPLEMENTED(false);
# endif /* X86/ARM */
return true;
}
#endif
/* This function is used for switch lib tls segment on creating thread.
* We switch to app's lib tls seg before thread creation system call, i.e.
* clone and vfork, and switch back to dr's lib tls seg after the system call.
* They are only called on parent thread, not the child thread.
* The child thread's tls is setup in os_tls_app_seg_init.
*/
/* XXX: It looks like the Linux kernel has some dependency on the segment
* descriptor. If using dr's segment descriptor, the created thread will have
* access violation for tls not being setup. However, it works fine if we switch
* the descriptor to app's segment descriptor before creating the thread.
* We should be able to remove this function later if we find the problem.
*/
static bool
os_switch_lib_tls(dcontext_t *dcontext, bool to_app)
{
return os_switch_seg_to_context(dcontext, LIB_SEG_TLS, to_app);
}
#ifdef X86
/* dcontext can be NULL if !to_app */
static bool
os_switch_seg_to_base(dcontext_t *dcontext, os_local_state_t *os_tls, reg_id_t seg,
bool to_app, app_pc base)
{
bool res = false;
ASSERT(dcontext != NULL);
ASSERT(IF_X86_ELSE((seg == SEG_FS || seg == SEG_GS),
(seg == DR_REG_TPIDRURW || DR_REG_TPIDRURO)));
switch (os_tls->tls_type) {
# if defined(X64) && !defined(MACOS)
case TLS_TYPE_ARCH_PRCTL: {
res = tls_set_fs_gs_segment_base(os_tls->tls_type, seg, base, NULL);
ASSERT(res);
LOG(GLOBAL, LOG_THREADS, 2,
"%s %s: arch_prctl successful for thread " TIDFMT " base " PFX "\n",
__FUNCTION__, to_app ? "to app" : "to DR", d_r_get_thread_id(), base);
if (seg == SEG_TLS && base == NULL) {
/* Set the selector to 0 so we don't think TLS is available. */
/* FIXME i#107: Still assumes app isn't using SEG_TLS. */
reg_t zero = 0;
WRITE_DR_SEG(zero);
}
break;
}
# endif
case TLS_TYPE_GDT: {
our_modify_ldt_t desc;
uint index;
uint selector;
if (to_app) {
selector = os_tls->app_lib_tls_reg;
index = SELECTOR_INDEX(selector);
} else {
index = (seg == LIB_SEG_TLS ? tls_priv_lib_index() : tls_dr_index());
ASSERT(index != -1 && "TLS indices not initialized");
selector = GDT_SELECTOR(index);
}
if (selector != 0) {
if (to_app) {
our_modify_ldt_t *areas =
((os_thread_data_t *)dcontext->os_field)->app_thread_areas;
ASSERT((index >= tls_min_index()) &&
((index - tls_min_index()) <= GDT_NUM_TLS_SLOTS));
desc = areas[index - tls_min_index()];
} else {
tls_init_descriptor(&desc, base, GDT_NO_SIZE_LIMIT, index);
}
res = tls_set_fs_gs_segment_base(os_tls->tls_type, seg, NULL, &desc);
ASSERT(res);
} else {
/* For a selector of zero, we just reset the segment to zero. We
* don't need to call set_thread_area.
*/
res = true; /* Indicate success. */
}
/* XXX i#2098: it's unsafe to call LOG here in between GDT and register changes */
/* i558 update lib seg reg to enforce the segment changes */
if (seg == SEG_TLS)
WRITE_DR_SEG(selector);
else
WRITE_LIB_SEG(selector);
LOG(THREAD, LOG_LOADER, 2, "%s: switching to %s, setting %s to 0x%x\n",
__FUNCTION__, (to_app ? "app" : "dr"), reg_names[seg], selector);
LOG(THREAD, LOG_LOADER, 2,
"%s %s: set_thread_area successful for thread " TIDFMT " base " PFX "\n",
__FUNCTION__, to_app ? "to app" : "to DR", d_r_get_thread_id(), base);
break;
}
case TLS_TYPE_LDT: {
uint index;
uint selector;
if (to_app) {
selector = os_tls->app_lib_tls_reg;
index = SELECTOR_INDEX(selector);
} else {
index = (seg == LIB_SEG_TLS ? tls_priv_lib_index() : tls_dr_index());
ASSERT(index != -1 && "TLS indices not initialized");
selector = LDT_SELECTOR(index);
}
LOG(THREAD, LOG_LOADER, 2, "%s: switching to %s, setting %s to 0x%x\n",
__FUNCTION__, (to_app ? "app" : "dr"), reg_names[seg], selector);
if (seg == SEG_TLS)
WRITE_DR_SEG(selector);
else
WRITE_LIB_SEG(selector);
LOG(THREAD, LOG_LOADER, 2,
"%s %s: ldt selector swap successful for thread " TIDFMT "\n", __FUNCTION__,
to_app ? "to app" : "to DR", d_r_get_thread_id());
break;
}
default: ASSERT_NOT_REACHED(); return false;
}
ASSERT((!to_app && seg == SEG_TLS) ||
BOOLS_MATCH(to_app, os_using_app_state(dcontext)));
return res;
}
static bool
os_set_dr_tls_base(dcontext_t *dcontext, os_local_state_t *tls, byte *base)
{
if (tls == NULL) {
ASSERT(dcontext != NULL);
tls = get_os_tls_from_dc(dcontext);
}
return os_switch_seg_to_base(dcontext, tls, SEG_TLS, false, base);
}
#endif /* X86 */
static bool
os_switch_seg_to_context(dcontext_t *dcontext, reg_id_t seg, bool to_app)
{
os_local_state_t *os_tls = get_os_tls_from_dc(dcontext);
#ifdef X86
app_pc base;
/* we can only update the executing thread's segment (i#920) */
ASSERT_MESSAGE(CHKLVL_ASSERTS + 1 /*expensive*/, "can only act on executing thread",
/* i#2089: a clone syscall, or when native, temporarily puts in
* invalid TLS, so we don't check get_thread_private_dcontext().
*/
is_thread_tls_allocated() &&
dcontext->owning_thread == get_sys_thread_id());
if (to_app) {
base = os_get_app_tls_base(dcontext, seg);
} else {
base = os_get_priv_tls_base(dcontext, seg);
}
return os_switch_seg_to_base(dcontext, os_tls, seg, to_app, base);
#elif defined(AARCHXX)
bool res = false;
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
ASSERT(INTERNAL_OPTION(private_loader));
if (to_app) {
/* We need to handle being called when we're already in the requested state. */
ptr_uint_t cur_seg = read_thread_register(LIB_SEG_TLS);
if ((void *)cur_seg == os_tls->app_lib_tls_base)
return true;
bool app_mem_valid = true;
if (os_tls->app_lib_tls_base == NULL)
app_mem_valid = false;
else {
uint prot;
bool rc = get_memory_info(os_tls->app_lib_tls_base, NULL, NULL, &prot);
/* Rule out a garbage value, which happens in our own test
* common.allasm_aarch_isa.
* Also rule out an unwritable region, which seems to happen on arm
* where at process init the thread reg points at rodata in libc
* until properly set to a writable mmap later.
*/
if (!rc || !TESTALL(MEMPROT_READ | MEMPROT_WRITE, prot))
app_mem_valid = false;
}
if (!app_mem_valid) {
/* XXX i#1578: For pure-asm apps that do not use libc, the app may have no
* thread register value. For detach we would like to write a 0 back into
* the thread register, but it complicates our exit code, which wants access
* to DR's TLS between dynamo_thread_exit_common()'s call to
* dynamo_thread_not_under_dynamo() and its call to
* set_thread_private_dcontext(NULL). For now we just leave our privlib
* segment in there. It seems rather unlikely to cause a problem: app code
* is unlikely to read the thread register; it's going to assume it owns it
* and will just blindly write to it.
*/
return true;
}
/* On switching to app's TLS, we need put DR's TLS base into app's TLS
* at the same offset so it can be loaded on entering code cache.
* Otherwise, the context switch code on entering fcache will fault on
* accessing DR's TLS.
* The app's TLS slot value is stored into privlib's TLS slot for
* later restore on switching back to privlib's TLS.
*/
byte **priv_lib_tls_swap_slot =
(byte **)(ostd->priv_lib_tls_base + DR_TLS_BASE_OFFSET);
byte **app_lib_tls_swap_slot =
(byte **)(os_tls->app_lib_tls_base + DR_TLS_BASE_OFFSET);
LOG(THREAD, LOG_LOADER, 3,
"%s: switching to app: app slot=&" PFX " *" PFX ", priv slot=&" PFX " *" PFX
"\n",
__FUNCTION__, app_lib_tls_swap_slot, *app_lib_tls_swap_slot,
priv_lib_tls_swap_slot, *priv_lib_tls_swap_slot);
byte *dr_tls_base = *priv_lib_tls_swap_slot;
*priv_lib_tls_swap_slot = *app_lib_tls_swap_slot;
*app_lib_tls_swap_slot = dr_tls_base;
LOG(THREAD, LOG_LOADER, 2, "%s: switching to %s, setting coproc reg to 0x%x\n",
__FUNCTION__, (to_app ? "app" : "dr"), os_tls->app_lib_tls_base);
res = write_thread_register(os_tls->app_lib_tls_base);
} else {
/* We need to handle being called when we're already in the requested state. */
ptr_uint_t cur_seg = read_thread_register(LIB_SEG_TLS);
if ((void *)cur_seg == ostd->priv_lib_tls_base)
return true;
/* Restore the app's TLS slot that we used for storing DR's TLS base,
* and put DR's TLS base back to privlib's TLS slot.
*/
byte **priv_lib_tls_swap_slot =
(byte **)(ostd->priv_lib_tls_base + DR_TLS_BASE_OFFSET);
byte **app_lib_tls_swap_slot =
(byte **)(os_tls->app_lib_tls_base + DR_TLS_BASE_OFFSET);
byte *dr_tls_base = *app_lib_tls_swap_slot;
LOG(THREAD, LOG_LOADER, 3,
"%s: switching to DR: app slot=&" PFX " *" PFX ", priv slot=&" PFX " *" PFX
"\n",
__FUNCTION__, app_lib_tls_swap_slot, *app_lib_tls_swap_slot,
priv_lib_tls_swap_slot, *priv_lib_tls_swap_slot);
*app_lib_tls_swap_slot = *priv_lib_tls_swap_slot;
*priv_lib_tls_swap_slot = dr_tls_base;
LOG(THREAD, LOG_LOADER, 2, "%s: switching to %s, setting coproc reg to 0x%x\n",
__FUNCTION__, (to_app ? "app" : "dr"), ostd->priv_lib_tls_base);
res = write_thread_register(ostd->priv_lib_tls_base);
}
LOG(THREAD, LOG_LOADER, 2, "%s %s: set_tls swap success=%d for thread " TIDFMT "\n",
__FUNCTION__, to_app ? "to app" : "to DR", res, d_r_get_thread_id());
return res;
#endif /* X86/AARCHXX */
}
#ifdef LINUX
static bool
handle_clone_pre(dcontext_t *dcontext)
{
/* For the clone syscall, in /usr/src/linux/arch/i386/kernel/process.c
* 32-bit params: flags, newsp, ptid, tls, ctid
* 64-bit params: should be the same yet tls (for ARCH_SET_FS) is in r8?!?
* I don't see how sys_clone gets its special args: shouldn't it
* just get pt_regs as a "special system call"?
* sys_clone(unsigned long clone_flags, unsigned long newsp,
* void __user *parent_tid, void __user *child_tid, struct pt_regs *regs)
*/
uint64_t flags;
/* For the clone3 syscall, DR creates its own copy of clone_args for two
* reasons: to ensure that the app-provided clone_args is readable
* without any fault, and to avoid modifying the app's clone_args in the
* is_thread_create_syscall case (see below).
*/
clone3_syscall_args_t *dr_clone_args = NULL, *app_clone_args = NULL;
uint app_clone_args_size = 0;
if (dcontext->sys_num == SYS_clone3) {
if (is_clone3_enosys) {
/* We know that clone3 will return ENOSYS, so we skip the pre-syscall
* handling and fail early.
*/
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning ENOSYS to app for clone3\n");
set_failure_return_val(dcontext, ENOSYS);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
return false;
}
app_clone_args_size =
(uint)sys_param(dcontext, SYSCALL_PARAM_CLONE3_CLONE_ARGS_SIZE);
if (app_clone_args_size < CLONE_ARGS_SIZE_VER0) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EINVAL to app for clone3\n");
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
return false;
}
app_clone_args =
(clone3_syscall_args_t *)sys_param(dcontext, SYSCALL_PARAM_CLONE3_CLONE_ARGS);
/* Note that the struct clone_args being used by the app may have
* less/more fields than DR's internal struct (clone3_syscall_args_t).
* For creating DR's copy of the app's clone_args object, we need to
* allocate as much space as specified by the app in the clone3
* syscall's args.
*/
dr_clone_args = (clone3_syscall_args_t *)heap_alloc(
dcontext, app_clone_args_size HEAPACCT(ACCT_OTHER));
if (!d_r_safe_read(app_clone_args, app_clone_args_size, dr_clone_args)) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EFAULT to app for clone3\n");
set_failure_return_val(dcontext, EFAULT);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
heap_free(dcontext, dr_clone_args, app_clone_args_size HEAPACCT(ACCT_OTHER));
return false;
}
flags = dr_clone_args->flags;
/* Save for post_system_call */
/* We need to save the pointer to the app's clone_args so that we can restore it
* post-syscall.
*/
dcontext->sys_param0 = (reg_t)app_clone_args;
/* For freeing the allocated memory. */
dcontext->sys_param1 = (reg_t)dr_clone_args;
dcontext->sys_param2 = (reg_t)app_clone_args_size;
/* clone3 flags are 64-bit even on 32-bit systems. So we need to split them across
* two reg_t vars on 32-bit. We do it on 64-bit systems as well for simpler code.
*/
dcontext->sys_param3 = (reg_t)(flags & CLONE3_FLAGS_4_BYTE_MASK);
ASSERT((flags >> 32 & ~CLONE3_FLAGS_4_BYTE_MASK) == 0);
dcontext->sys_param4 = (reg_t)((flags >> 32));
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: clone3 with args: flags = 0x" HEX64_FORMAT_STRING
", exit_signal = 0x" HEX64_FORMAT_STRING ", stack = 0x" HEX64_FORMAT_STRING
", stack_size = 0x" HEX64_FORMAT_STRING "\n",
dr_clone_args->flags, dr_clone_args->exit_signal, dr_clone_args->stack,
dr_clone_args->stack_size);
} else {
flags = (uint)sys_param(dcontext, 0);
/* Save for post_system_call.
* Unlike clone3, here the flags are 32-bit, so truncation is okay.
*/
dcontext->sys_param0 = (reg_t)flags;
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: clone with args: flags = " PFX ", stack = " PFX
", tid_field_parent = " PFX ", tid_field_child = " PFX ", thread_ptr = " PFX
"\n",
sys_param(dcontext, 0), sys_param(dcontext, 1), sys_param(dcontext, 2),
sys_param(dcontext, 3), sys_param(dcontext, 4));
}
handle_clone(dcontext, flags);
if ((flags & CLONE_VM) == 0) {
LOG(THREAD, LOG_SYSCALLS, 1, "\tWARNING: CLONE_VM not set!\n");
}
/* i#1010: If we have private fds open (usually logfiles), we should
* clean those up before they get reused by a new thread.
* XXX: Ideally we'd do this in fd_table_add(), but we can't acquire
* thread_initexit_lock there.
*/
cleanup_after_vfork_execve(dcontext);
/* For thread creation clone syscalls a clone_record_t structure
* containing the pc after the app's syscall instr and other data
* (see i#27) is placed at the bottom of the dstack (which is allocated
* by create_clone_record() - it also saves app stack and switches
* to dstack). xref i#149/PR 403015.
* Note: This must be done after sys_param0 is set.
*/
if (is_thread_create_syscall(dcontext, dr_clone_args)) {
if (dcontext->sys_num == SYS_clone3) {
/* create_clone_record modifies some fields in clone_args for the
* clone3 syscall. Instead of reusing the app's copy of
* clone_args and modifying it, we choose to use our own copy.
* Under CLONE_VM, the parent and child threads have a pointer to
* the same app clone_args. By using our own copy of clone_args
* for the syscall, we obviate the need to restore the modified
* fields in the app's copy after the syscall in either the parent
* or the child thread, which can be racy under CLONE_VM as the
* parent and/or child threads may need to access/modify it. By
* using a copy instead, both parent and child threads only
* need to restore their own SYSCALL_PARAM_CLONE3_CLONE_ARGS reg
* to the pointer to the app's clone_args. It is saved in the
* clone record for the child thread, and in sys_param0 for the
* parent thread. The DR copy of clone_args is freed by the parent
* thread in the post-syscall handling of clone3; as it is used
* only by the parent thread, there is no use-after-free danger here.
*/
ASSERT(app_clone_args != NULL && dr_clone_args != NULL);
*sys_param_addr(dcontext, SYSCALL_PARAM_CLONE3_CLONE_ARGS) =
(reg_t)dr_clone_args;
/* The pointer to the app's clone_args was saved in sys_param0 above. */
create_clone_record(dcontext, NULL, dr_clone_args, app_clone_args);
} else {
/* We replace the app-provided stack pointer with our own stack
* pointer in create_clone_record. Save the original pointer so
* that we can restore it post-syscall in the parent. The same is
* restored in the child in restore_clone_param_from_clone_record.
*/
dcontext->sys_param1 = sys_param(dcontext, SYSCALL_PARAM_CLONE_STACK);
create_clone_record(dcontext,
sys_param_addr(dcontext, SYSCALL_PARAM_CLONE_STACK), NULL,
NULL);
}
os_clone_pre(dcontext);
os_new_thread_pre();
} else {
/* This is really a fork. */
if (dcontext->sys_num == SYS_clone3) {
/* We free this memory before the actual fork, to avoid having to free
* it in the parent *and* the child later.
*/
ASSERT(app_clone_args_size == (uint)dcontext->sys_param2);
ASSERT(dr_clone_args == (clone3_syscall_args_t *)dcontext->sys_param1);
heap_free(dcontext, dr_clone_args, app_clone_args_size HEAPACCT(ACCT_OTHER));
/* We do not need these anymore for the fork case. */
dcontext->sys_param1 = 0;
dcontext->sys_param2 = 0;
}
os_fork_pre(dcontext);
}
return true;
}
#endif
/* System call interception: put any special handling here
* Arguments come from the pusha right before the call
*/
/* WARNING: flush_fragments_and_remove_region assumes that pre and post system
* call handlers do not examine or modify fcache or its fragments in any
* way except for calling flush_fragments_and_remove_region!
*/
/* WARNING: All registers are IN values, but NOT OUT values --
* must set mcontext's register for that.
*/
/* Returns false if system call should NOT be executed (in which case,
* post_system_call() will *not* be called!).
* Returns true if system call should go ahead
*/
/* XXX: split out specific handlers into separate routines
*/
bool
pre_system_call(dcontext_t *dcontext)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
bool execute_syscall = true;
dr_where_am_i_t old_whereami = dcontext->whereami;
dcontext->whereami = DR_WHERE_SYSCALL_HANDLER;
/* FIXME We haven't yet done the work to detect which syscalls we
* can determine a priori will fail. Once we do, we will set the
* expect_last_syscall_to_fail to true for those case, and can
* confirm in post_system_call() that the syscall failed as
* expected.
*/
DODEBUG(dcontext->expect_last_syscall_to_fail = false;);
/* save key register values for post_system_call (they get clobbered
* in syscall itself)
*/
dcontext->sys_num = os_normalized_sysnum((int)MCXT_SYSNUM_REG(mc), NULL, dcontext);
RSTATS_INC(pre_syscall);
DOSTATS({
if (ignorable_system_call_normalized(dcontext->sys_num))
STATS_INC(pre_syscall_ignorable);
});
LOG(THREAD, LOG_SYSCALLS, 2, "system call %d\n", dcontext->sys_num);
#if defined(LINUX) && defined(X86)
/* PR 313715: If we fail to hook the vsyscall page (xref PR 212570, PR 288330)
* we fall back on int, but we have to tweak syscall param #5 (ebp)
* Once we have PR 288330 we can remove this.
*/
if (should_syscall_method_be_sysenter() && !dcontext->sys_was_int) {
dcontext->sys_xbp = mc->xbp;
/* not using SAFE_READ due to performance concerns (we do this for
* every single system call on systems where we can't hook vsyscall!)
*/
TRY_EXCEPT(dcontext, /* try */ { mc->xbp = *(reg_t *)mc->xsp; }, /* except */
{
ASSERT_NOT_REACHED();
mc->xbp = 0;
});
}
#endif
switch (dcontext->sys_num) {
case SYSNUM_EXIT_PROCESS:
#if defined(LINUX) && VMX86_SERVER
if (os_in_vmkernel_32bit()) {
/* on esx 3.5 => ENOSYS, so wait for SYS_exit */
LOG(THREAD, LOG_SYSCALLS, 2, "on esx35 => ignoring exitgroup\n");
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
break;
}
#endif
/* fall-through */
case SYSNUM_EXIT_THREAD: {
handle_exit(dcontext);
break;
}
/****************************************************************************/
/* MEMORY REGIONS */
#if defined(LINUX) && !defined(X64) && !defined(ARM)
case SYS_mmap: {
/* in /usr/src/linux/arch/i386/kernel/sys_i386.c:
asmlinkage int old_mmap(struct mmap_arg_struct_t *arg)
*/
mmap_arg_struct_t *arg = (mmap_arg_struct_t *)sys_param(dcontext, 0);
mmap_arg_struct_t arg_buf;
if (d_r_safe_read(arg, sizeof(mmap_arg_struct_t), &arg_buf)) {
void *addr = (void *)arg->addr;
size_t len = (size_t)arg->len;
uint prot = (uint)arg->prot;
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: mmap addr=" PFX " size=" PIFX " prot=0x%x"
" flags=" PIFX " offset=" PIFX " fd=%d\n",
addr, len, prot, arg->flags, arg->offset, arg->fd);
/* Check for overlap with existing code or patch-proof regions */
if (addr != NULL &&
!app_memory_pre_alloc(dcontext, addr, len, osprot_to_memprot(prot),
!TEST(MAP_FIXED, arg->flags),
false /*we'll update in post*/,
false /*unknown*/)) {
/* Rather than failing or skipping the syscall we'd like to just
* remove the hint -- but we don't want to write to app memory, so
* we do fail. We could set up our own mmap_arg_struct_t but
* we'd need dedicate per-thread storage, and SYS_mmap is obsolete.
*/
execute_syscall = false;
set_failure_return_val(dcontext, ENOMEM);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
break;
}
}
/* post_system_call does the work */
dcontext->sys_param0 = (reg_t)arg;
break;
}
#endif
case IF_MACOS_ELSE(SYS_mmap, IF_X64_ELSE(SYS_mmap, SYS_mmap2)): {
/* in /usr/src/linux/arch/i386/kernel/sys_i386.c:
asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
*/
void *addr = (void *)sys_param(dcontext, 0);
size_t len = (size_t)sys_param(dcontext, 1);
uint prot = (uint)sys_param(dcontext, 2);
uint flags = (uint)sys_param(dcontext, 3);
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: mmap2 addr=" PFX " size=" PIFX " prot=0x%x"
" flags=" PIFX " offset=" PIFX " fd=%d\n",
addr, len, prot, flags, sys_param(dcontext, 5), sys_param(dcontext, 4));
/* Check for overlap with existing code or patch-proof regions */
/* Try to see whether it's an image, though we can't tell for addr==NULL
* (typical for 1st mmap).
*/
bool image = addr != NULL && !TEST(MAP_ANONYMOUS, flags) &&
mmap_check_for_module_overlap(addr, len, TEST(PROT_READ, prot), 0, true);
if (addr != NULL &&
!app_memory_pre_alloc(dcontext, addr, len, osprot_to_memprot(prot),
!TEST(MAP_FIXED, flags), false /*we'll update in post*/,
image /*best estimate*/)) {
if (!TEST(MAP_FIXED, flags)) {
/* Rather than failing or skipping the syscall we just remove
* the hint which should eliminate any overlap.
*/
*sys_param_addr(dcontext, 0) = 0;
} else {
execute_syscall = false;
set_failure_return_val(dcontext, ENOMEM);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
break;
}
}
/* post_system_call does the work */
dcontext->sys_param0 = (reg_t)addr;
dcontext->sys_param1 = len;
dcontext->sys_param2 = prot;
dcontext->sys_param3 = flags;
break;
}
/* must flush stale fragments when we see munmap/mremap */
case SYS_munmap: {
/* in /usr/src/linux/mm/mmap.c:
asmlinkage long sys_munmap(unsigned long addr, uint len)
*/
app_pc addr = (void *)sys_param(dcontext, 0);
size_t len = (size_t)sys_param(dcontext, 1);
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: munmap addr=" PFX " size=" PFX "\n", addr,
len);
RSTATS_INC(num_app_munmaps);
/* FIXME addr is supposed to be on a page boundary so we
* could detect that condition here and set
* expect_last_syscall_to_fail.
*/
/* save params in case an undo is needed in post_system_call */
dcontext->sys_param0 = (reg_t)addr;
dcontext->sys_param1 = len;
/* We assume that the unmap will succeed and so are conservative
* and remove the region from exec areas and flush all fragments
* prior to issuing the syscall. If the unmap fails, we try to
* recover in post_system_call() by re-adding the region. This
* approach has its shortcomings -- see comments below in
* post_system_call().
*/
/* Check for unmapping a module. */
os_get_module_info_lock();
if (module_overlaps(addr, len)) {
/* FIXME - handle unmapping more than one module at once, or only unmapping
* part of a module (for which case should adjust view size? or treat as full
* unmap?). Theoretical for now as we haven't seen this. */
module_area_t *ma = module_pc_lookup(addr);
ASSERT_CURIOSITY(ma != NULL);
ASSERT_CURIOSITY(addr == ma->start);
/* XREF 307599 on rounding module end to the next PAGE boundary */
ASSERT_CURIOSITY((app_pc)ALIGN_FORWARD(addr + len, PAGE_SIZE) == ma->end);
os_get_module_info_unlock();
/* i#210:
* we only think a module is removed if its first memory region
* is unloaded (unmapped).
* XREF i#160 to fix the real problem of handling module splitting.
*/
if (ma != NULL && ma->start == addr)
module_list_remove(addr, ALIGN_FORWARD(len, PAGE_SIZE));
} else
os_get_module_info_unlock();
app_memory_deallocation(dcontext, (app_pc)addr, len,
false /* don't own thread_initexit_lock */,
true /* image, FIXME: though not necessarily */);
/* FIXME: case 4983 use is_elf_so_header() */
#ifndef HAVE_MEMINFO_QUERY
memcache_lock();
memcache_remove(addr, addr + len);
memcache_unlock();
#endif
break;
}
#ifdef LINUX
case SYS_mremap: {
/* in /usr/src/linux/mm/mmap.c:
asmlinkage unsigned long sys_mremap(unsigned long addr,
unsigned long old_len, unsigned long new_len,
unsigned long flags, unsigned long new_addr)
*/
dr_mem_info_t info;
app_pc addr = (void *)sys_param(dcontext, 0);
size_t old_len = (size_t)sys_param(dcontext, 1);
size_t new_len = (size_t)sys_param(dcontext, 2);
DEBUG_DECLARE(bool ok;)
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: mremap addr=" PFX " size=" PFX "\n", addr,
old_len);
/* post_system_call does the work */
dcontext->sys_param0 = (reg_t)addr;
dcontext->sys_param1 = old_len;
dcontext->sys_param2 = new_len;
/* i#173
* we need memory type and prot to set the
* new memory region in the post_system_call
*/
DEBUG_DECLARE(ok =)
query_memory_ex(addr, &info);
ASSERT(ok);
dcontext->sys_param3 = info.prot;
dcontext->sys_param4 = info.type;
DOCHECK(1, {
/* we don't expect to see remappings of modules */
os_get_module_info_lock();
ASSERT_CURIOSITY(!module_overlaps(addr, old_len));
os_get_module_info_unlock();
});
break;
}
#endif
case SYS_mprotect: {
/* in /usr/src/linux/mm/mprotect.c:
asmlinkage long sys_mprotect(unsigned long start, uint len,
unsigned long prot)
*/
uint res;
DEBUG_DECLARE(size_t size;)
app_pc addr = (void *)sys_param(dcontext, 0);
size_t len = (size_t)sys_param(dcontext, 1);
uint prot = (uint)sys_param(dcontext, 2);
uint old_memprot = MEMPROT_NONE, new_memprot;
bool exists = true;
/* save params in case an undo is needed in post_system_call */
dcontext->sys_param0 = (reg_t)addr;
dcontext->sys_param1 = len;
dcontext->sys_param2 = prot;
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: mprotect addr=" PFX " size=" PFX " prot=%s\n", addr, len,
memprot_string(osprot_to_memprot(prot)));
if (!get_memory_info(addr, NULL, IF_DEBUG_ELSE(&size, NULL), &old_memprot)) {
exists = false;
/* Xref PR 413109, PR 410921: if the start, or any page, is not mapped,
* this should fail with ENOMEM. We used to force-fail it to avoid
* asserts in our own allmem update code, but there are cases where a
* seemingly unmapped page succeeds (i#1912: next page of grows-down
* initial stack). Thus we let it go through.
*/
LOG(THREAD, LOG_SYSCALLS, 2,
"\t" PFX " isn't mapped: probably mprotect will fail\n", addr);
} else {
/* If mprotect region spans beyond the end of the vmarea then it
* spans 2 or more vmareas with dissimilar protection (xref
* PR 410921) or has unallocated regions in between (PR 413109).
*/
DOCHECK(1, dcontext->mprot_multi_areas = len > size ? true : false;);
}
new_memprot = osprot_to_memprot(prot) |
/* mprotect won't change meta flags */
(old_memprot & MEMPROT_META_FLAGS);
res = app_memory_protection_change(dcontext, addr, len, new_memprot, &new_memprot,
NULL, false /*!image*/);
if (res != DO_APP_MEM_PROT_CHANGE) {
if (res == FAIL_APP_MEM_PROT_CHANGE) {
ASSERT_NOT_IMPLEMENTED(false); /* return code? */
} else {
ASSERT_NOT_IMPLEMENTED(res != SUBSET_APP_MEM_PROT_CHANGE);
ASSERT_NOT_REACHED();
}
execute_syscall = false;
} else {
/* FIXME Store state for undo if the syscall fails. */
IF_NO_MEMQUERY(memcache_update_locked(addr, addr + len, new_memprot,
-1 /*type unchanged*/, exists));
}
break;
}
#ifdef ANDROID
case SYS_prctl:
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
dcontext->sys_param2 = sys_param(dcontext, 2);
dcontext->sys_param3 = sys_param(dcontext, 3);
dcontext->sys_param4 = sys_param(dcontext, 4);
break;
#endif
#ifdef LINUX
case SYS_brk: {
if (DYNAMO_OPTION(emulate_brk)) {
/* i#1004: emulate brk via a separate mmap */
byte *new_val = (byte *)sys_param(dcontext, 0);
byte *res = emulate_app_brk(dcontext, new_val);
execute_syscall = false;
/* SYS_brk returns old brk on failure */
set_success_return_val(dcontext, (reg_t)res);
} else {
/* i#91/PR 396352: need to watch SYS_brk to maintain all_memory_areas.
* We store the old break in the param1 slot.
*/
DODEBUG(dcontext->sys_param0 = (reg_t)sys_param(dcontext, 0););
dcontext->sys_param1 = dynamorio_syscall(SYS_brk, 1, 0);
}
break;
}
# ifdef SYS_uselib
case SYS_uselib: {
/* Used to get the kernel to load a share library (legacy system call).
* Was primarily used when statically linking to dynamically loaded shared
* libraries that were loaded at known locations. Shouldn't be used by
* applications using the dynamic loader (ld) which is currently the only
* way we can inject so we don't expect to see this. PR 307621. */
ASSERT_NOT_IMPLEMENTED(false);
break;
}
# endif
#endif
/****************************************************************************/
/* SPAWNING */
#ifdef LINUX
case SYS_clone3:
case SYS_clone: execute_syscall = handle_clone_pre(dcontext); break;
#elif defined(MACOS)
case SYS_bsdthread_create: {
/* XXX i#1403: we need earlier injection to intercept
* bsdthread_register in order to capture workqueue threads.
* For now we settle for intercepting bsd threads at the user thread func.
* We miss a little user-mode code but this is enough to get started.
*/
app_pc func = (app_pc)sys_param(dcontext, 0);
void *func_arg = (void *)sys_param(dcontext, 1);
void *clone_rec;
LOG(THREAD, LOG_SYSCALLS, 1,
"bsdthread_create: thread func " PFX ", arg " PFX "\n", func, func_arg);
handle_clone(dcontext, CLONE_THREAD | CLONE_VM | CLONE_SIGHAND | SIGCHLD);
clone_rec = create_clone_record(dcontext, NULL, func, func_arg);
dcontext->sys_param0 = (reg_t)func;
dcontext->sys_param1 = (reg_t)func_arg;
*sys_param_addr(dcontext, 0) = (reg_t)new_bsdthread_intercept;
*sys_param_addr(dcontext, 1) = (reg_t)clone_rec;
os_new_thread_pre();
break;
}
case SYS_posix_spawn: {
/* FIXME i#1644: monitor this call which can be fork or exec */
ASSERT_NOT_IMPLEMENTED(false);
break;
}
#endif
#ifdef SYS_vfork
case SYS_vfork: {
/* treat as if sys_clone with flags just as sys_vfork does */
/* in /usr/src/linux/arch/i386/kernel/process.c */
uint flags = CLONE_VFORK | CLONE_VM | SIGCHLD;
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: vfork\n");
handle_clone(dcontext, flags);
cleanup_after_vfork_execve(dcontext);
/* save for post_system_call, treated as if SYS_clone */
dcontext->sys_param0 = (reg_t)flags;
/* vfork has the same needs as clone. Pass info via a clone_record_t
* structure to child. See SYS_clone for info about i#149/PR 403015.
*/
IF_LINUX(ASSERT(is_thread_create_syscall(dcontext, NULL)));
dcontext->sys_param1 = mc->xsp; /* for restoring in parent */
# ifdef MACOS
create_clone_record(dcontext, (reg_t *)&mc->xsp, NULL, NULL);
# else
create_clone_record(dcontext, (reg_t *)&mc->xsp /*child uses parent sp*/, NULL,
NULL);
# endif
os_clone_pre(dcontext);
os_new_thread_pre();
break;
}
#endif
#ifdef SYS_fork
case SYS_fork: {
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: fork\n");
os_fork_pre(dcontext);
break;
}
#endif
case SYS_execve: {
int ret = handle_execve(dcontext);
if (ret != 0) {
execute_syscall = false;
set_failure_return_val(dcontext, ret);
}
break;
}
/****************************************************************************/
/* SIGNALS */
case IF_MACOS_ELSE(SYS_sigaction, SYS_rt_sigaction): { /* 174 */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage long
sys_rt_sigaction(int sig, const struct sigaction *act,
struct sigaction *oact, size_t sigsetsize)
*/
int sig = (int)sys_param(dcontext, 0);
const kernel_sigaction_t *act =
(const kernel_sigaction_t *)sys_param(dcontext, 1);
prev_sigaction_t *oact = (prev_sigaction_t *)sys_param(dcontext, 2);
size_t sigsetsize = (size_t)
/* On Mac there is no size arg (but it doesn't use old sigaction, so
* closer to rt_ than non-rt_ below).
*/
IF_MACOS_ELSE(sizeof(kernel_sigset_t), sys_param(dcontext, 3));
uint res;
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: %ssigaction %d " PFX " " PFX " %d\n",
IF_MACOS_ELSE("", "rt_"), sig, act, oact, sigsetsize);
/* post_syscall does some work as well */
dcontext->sys_param0 = (reg_t)sig;
dcontext->sys_param1 = (reg_t)act;
dcontext->sys_param2 = (reg_t)oact;
dcontext->sys_param3 = (reg_t)sigsetsize;
execute_syscall = handle_sigaction(dcontext, sig, act, oact, sigsetsize, &res);
if (!execute_syscall) {
LOG(THREAD, LOG_SYSCALLS, 2, "sigaction emulation => %d\n", -res);
if (res == 0)
set_success_return_val(dcontext, 0);
else
set_failure_return_val(dcontext, res);
}
break;
}
#if defined(LINUX) && !defined(X64)
case SYS_sigaction: { /* 67 */
/* sys_sigaction(int sig, const struct old_sigaction *act,
* struct old_sigaction *oact)
*/
int sig = (int)sys_param(dcontext, 0);
const old_sigaction_t *act = (const old_sigaction_t *)sys_param(dcontext, 1);
old_sigaction_t *oact = (old_sigaction_t *)sys_param(dcontext, 2);
uint res;
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: sigaction %d " PFX " " PFX "\n", sig, act,
oact);
dcontext->sys_param0 = (reg_t)sig;
dcontext->sys_param1 = (reg_t)act;
dcontext->sys_param2 = (reg_t)oact;
execute_syscall = handle_old_sigaction(dcontext, sig, act, oact, &res);
if (!execute_syscall) {
LOG(THREAD, LOG_SYSCALLS, 2, "sigaction emulation => %d\n", -res);
if (res == 0)
set_success_return_val(dcontext, 0);
else
set_failure_return_val(dcontext, res);
}
break;
}
#endif
#if defined(LINUX) && !defined(X64)
case SYS_sigreturn: { /* 119 */
/* in /usr/src/linux/arch/i386/kernel/signal.c:
asmlinkage int sys_sigreturn(unsigned long __unused)
*/
execute_syscall = handle_sigreturn(dcontext, false);
/* app will not expect syscall to return, so when handle_sigreturn
* returns false it always redirects the context, and thus no
* need to set return val here.
*/
break;
}
#endif
#ifdef LINUX
case SYS_rt_sigreturn: { /* 173 */
/* in /usr/src/linux/arch/i386/kernel/signal.c:
asmlinkage int sys_rt_sigreturn(unsigned long __unused)
*/
execute_syscall = handle_sigreturn(dcontext, true);
/* see comment for SYS_sigreturn on return val */
break;
}
#endif
#ifdef MACOS
case SYS_sigreturn: {
/* int sigreturn(struct ucontext *uctx, int infostyle) */
execute_syscall = handle_sigreturn(dcontext, (void *)sys_param(dcontext, 0),
(int)sys_param(dcontext, 1));
/* see comment for SYS_sigreturn on return val */
break;
}
#endif
case SYS_sigaltstack: { /* 186 */
/* in /usr/src/linux/arch/i386/kernel/signal.c:
asmlinkage int
sys_sigaltstack(const stack_t *uss, stack_t *uoss)
*/
const stack_t *uss = (const stack_t *)sys_param(dcontext, 0);
stack_t *uoss = (stack_t *)sys_param(dcontext, 1);
uint res;
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: sigaltstack " PFX " " PFX "\n", uss, uoss);
execute_syscall =
handle_sigaltstack(dcontext, uss, uoss, get_mcontext(dcontext)->xsp, &res);
if (!execute_syscall) {
LOG(THREAD, LOG_SYSCALLS, 2, "sigaltstack emulation => %d\n", -res);
if (res == 0)
set_success_return_val(dcontext, res);
else
set_failure_return_val(dcontext, res);
}
break;
}
case IF_MACOS_ELSE(SYS_sigprocmask, SYS_rt_sigprocmask): { /* 175 */
/* TODO i#5256: Fx this path and enable linux.sigaction on MacOS. */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage long
sys_rt_sigprocmask(int how, sigset_t *set, sigset_t *oset,
size_t sigsetsize)
*/
/* we also need access to the params in post_system_call */
uint error_code = 0;
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
dcontext->sys_param2 = sys_param(dcontext, 2);
/* SYS_sigprocmask on MacOS does not have a size arg. So we use the
* kernel_sigset_t size instead.
*/
size_t sigsetsize =
(size_t)IF_MACOS_ELSE(sizeof(kernel_sigset_t), sys_param(dcontext, 3));
dcontext->sys_param3 = (reg_t)sigsetsize;
execute_syscall = handle_sigprocmask(dcontext, (int)sys_param(dcontext, 0),
(kernel_sigset_t *)sys_param(dcontext, 1),
(kernel_sigset_t *)sys_param(dcontext, 2),
sigsetsize, &error_code);
if (!execute_syscall) {
if (error_code == 0)
set_success_return_val(dcontext, 0);
else
set_failure_return_val(dcontext, error_code);
}
break;
}
#ifdef MACOS
case SYS_sigsuspend_nocancel:
#endif
case IF_MACOS_ELSE(SYS_sigsuspend, SYS_rt_sigsuspend): { /* 179 */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage int
sys_rt_sigsuspend(sigset_t *unewset, size_t sigsetsize)
*/
handle_sigsuspend(dcontext, (kernel_sigset_t *)sys_param(dcontext, 0),
(size_t)sys_param(dcontext, 1));
break;
}
#ifdef LINUX
# ifdef SYS_signalfd
case SYS_signalfd: /* 282/321 */
# endif
case SYS_signalfd4: { /* 289 */
/* int signalfd (int fd, const sigset_t *mask, size_t sizemask) */
/* int signalfd4(int fd, const sigset_t *mask, size_t sizemask, int flags) */
ptr_int_t new_result;
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
dcontext->sys_param2 = sys_param(dcontext, 2);
# ifdef SYS_signalfd
if (dcontext->sys_num == SYS_signalfd)
dcontext->sys_param3 = 0;
else
# endif
dcontext->sys_param3 = sys_param(dcontext, 3);
new_result = handle_pre_signalfd(
dcontext, (int)dcontext->sys_param0, (kernel_sigset_t *)dcontext->sys_param1,
(size_t)dcontext->sys_param2, (int)dcontext->sys_param3);
execute_syscall = false;
/* since non-Mac, we can use this even if the call failed */
set_success_return_val(dcontext, new_result);
break;
}
#endif
case SYS_kill: { /* 37 */
/* in /usr/src/linux/kernel/signal.c:
* asmlinkage long sys_kill(int pid, int sig)
*/
pid_t pid = (pid_t)sys_param(dcontext, 0);
uint sig = (uint)sys_param(dcontext, 1);
LOG(GLOBAL, LOG_TOP | LOG_SYSCALLS, 2,
"thread " TIDFMT " sending signal %d to pid " PIDFMT "\n",
d_r_get_thread_id(), sig, pid);
/* We check whether targeting this process or this process group */
if (pid == get_process_id() || pid == 0 || pid == -get_process_group_id()) {
handle_self_signal(dcontext, sig);
}
break;
}
#if defined(SYS_tkill)
case SYS_tkill: { /* 238 */
/* in /usr/src/linux/kernel/signal.c:
* asmlinkage long sys_tkill(int pid, int sig)
*/
pid_t tid = (pid_t)sys_param(dcontext, 0);
uint sig = (uint)sys_param(dcontext, 1);
LOG(GLOBAL, LOG_TOP | LOG_SYSCALLS, 2,
"thread " TIDFMT " sending signal %d to tid %d\n", d_r_get_thread_id(), sig,
tid);
if (tid == d_r_get_thread_id()) {
handle_self_signal(dcontext, sig);
}
break;
}
#endif
#if defined(SYS_tgkill)
case SYS_tgkill: { /* 270 */
/* in /usr/src/linux/kernel/signal.c:
* asmlinkage long sys_tgkill(int tgid, int pid, int sig)
*/
pid_t tgid = (pid_t)sys_param(dcontext, 0);
pid_t tid = (pid_t)sys_param(dcontext, 1);
uint sig = (uint)sys_param(dcontext, 2);
LOG(GLOBAL, LOG_TOP | LOG_SYSCALLS, 2,
"thread " TIDFMT " sending signal %d to tid %d tgid %d\n",
d_r_get_thread_id(), sig, tid, tgid);
/* some kernels support -1 values:
+ tgkill(-1, tid, sig) == tkill(tid, sig)
* tgkill(tgid, -1, sig) == kill(tgid, sig)
* the 2nd was proposed but is not in 2.6.20 so I'm ignoring it, since
* I don't want to kill the thread when the signal is never sent!
* FIXME: the 1st is in my tkill manpage, but not my 2.6.20 kernel sources!
*/
if ((tgid == -1 || tgid == get_process_id()) && tid == d_r_get_thread_id()) {
handle_self_signal(dcontext, sig);
}
break;
}
#endif
case SYS_setitimer: /* 104 */
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
dcontext->sys_param2 = sys_param(dcontext, 2);
handle_pre_setitimer(dcontext, (int)sys_param(dcontext, 0),
(const struct itimerval *)sys_param(dcontext, 1),
(struct itimerval *)sys_param(dcontext, 2));
break;
case SYS_getitimer: /* 105 */
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
break;
#if defined(LINUX) && defined(X86)
case SYS_alarm: /* 27 on x86 and 37 on x64 */
dcontext->sys_param0 = sys_param(dcontext, 0);
handle_pre_alarm(dcontext, (unsigned int)dcontext->sys_param0);
break;
#endif
#if 0
# ifndef X64
case SYS_signal: { /* 48 */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage unsigned long
sys_signal(int sig, __sighandler_t handler)
*/
break;
}
case SYS_sigsuspend: { /* 72 */
/* in /usr/src/linux/arch/i386/kernel/signal.c:
asmlinkage int
sys_sigsuspend(int history0, int history1, old_sigset_t mask)
*/
break;
}
case SYS_sigprocmask: { /* 126 */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage long
sys_sigprocmask(int how, old_sigset_t *set, old_sigset_t *oset)
*/
break;
}
# endif
#else
/* until we've implemented them, keep down here to get warning: */
# if defined(LINUX) && !defined(X64)
# ifndef ARM
case SYS_signal:
# endif
case SYS_sigsuspend:
case SYS_sigprocmask:
# endif
#endif
#if defined(LINUX) && !defined(X64)
case SYS_sigpending: /* 73 */
# ifndef ARM
case SYS_sgetmask: /* 68 */
case SYS_ssetmask: /* 69 */
# endif
#endif
#ifdef LINUX
# ifdef SYS_rt_sigtimedwait_time64
case SYS_rt_sigtimedwait_time64: /* 421 */
# endif
case SYS_rt_sigtimedwait: /* 177 */
case SYS_rt_sigqueueinfo: /* 178 */
#endif
case IF_MACOS_ELSE(SYS_sigpending, SYS_rt_sigpending): { /* 176 */
/* FIXME i#92: handle all of these syscalls! */
LOG(THREAD, LOG_ASYNCH | LOG_SYSCALLS, 1,
"WARNING: unhandled signal system call %d\n", dcontext->sys_num);
SYSLOG_INTERNAL_WARNING_ONCE("unhandled signal system call %d",
dcontext->sys_num);
break;
}
#ifdef LINUX
# ifdef SYS_ppoll_time64
case SYS_ppoll_time64:
# endif
case SYS_ppoll: {
kernel_sigset_t *sigmask = (kernel_sigset_t *)sys_param(dcontext, 3);
dcontext->sys_param3 = (reg_t)sigmask;
if (sigmask == NULL)
break;
size_t sizemask = (size_t)sys_param(dcontext, 4);
/* The original app's sigmask parameter is now NULL effectively making the syscall
* a non p* version, and the mask's semantics are emulated by DR instead.
*/
set_syscall_param(dcontext, 3, (reg_t)NULL);
bool sig_pending = false;
if (!handle_pre_extended_syscall_sigmasks(dcontext, sigmask, sizemask,
&sig_pending)) {
/* In old kernels with sizeof(kernel_sigset_t) != sizemask, we're forcing
* failure. We're already violating app transparency in other places in DR.
*/
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
}
if (sig_pending) {
/* If there had been pending signals, we revert re-writing the app's
* parameter, but we leave the modified signal mask.
*/
set_syscall_param(dcontext, 3, dcontext->sys_param3);
set_failure_return_val(dcontext, EINTR);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
}
break;
}
# ifdef SYS_pselect6_time64
case SYS_pselect6_time64:
# endif
case SYS_pselect6: {
typedef struct {
kernel_sigset_t *sigmask;
size_t sizemask;
} data_t;
dcontext->sys_param3 = sys_param(dcontext, 5);
data_t *data_param = (data_t *)dcontext->sys_param3;
data_t data;
if (data_param == NULL) {
/* The kernel does not consider a NULL 6th+7th-args struct to be an error but
* just a NULL sigmask.
*/
dcontext->sys_param4 = (reg_t)NULL;
break;
}
/* Refer to comments in SYS_ppoll above. Taking extra steps here due to struct
* argument in pselect6.
*/
if (!d_r_safe_read(data_param, sizeof(data), &data)) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EFAULT to app for pselect6\n");
set_failure_return_val(dcontext, EFAULT);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
break;
}
dcontext->sys_param4 = (reg_t)data.sigmask;
if (data.sigmask == NULL)
break;
kernel_sigset_t *nullsigmaskptr = NULL;
if (!safe_write_ex((void *)&data_param->sigmask, sizeof(data_param->sigmask),
&nullsigmaskptr, NULL)) {
set_failure_return_val(dcontext, EFAULT);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
break;
}
bool sig_pending = false;
if (!handle_pre_extended_syscall_sigmasks(dcontext, data.sigmask, data.sizemask,
&sig_pending)) {
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
}
if (sig_pending) {
if (!safe_write_ex((void *)&data_param->sigmask, sizeof(data_param->sigmask),
&dcontext->sys_param4, NULL)) {
set_failure_return_val(dcontext, EFAULT);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
break;
}
set_failure_return_val(dcontext, EINTR);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
}
break;
}
case SYS_epoll_pwait: {
kernel_sigset_t *sigmask = (kernel_sigset_t *)sys_param(dcontext, 4);
dcontext->sys_param4 = (reg_t)sigmask;
if (sigmask == NULL)
break;
size_t sizemask = (size_t)sys_param(dcontext, 5);
/* Refer to comments in SYS_ppoll above. */
set_syscall_param(dcontext, 4, (reg_t)NULL);
bool sig_pending = false;
if (!handle_pre_extended_syscall_sigmasks(dcontext, sigmask, sizemask,
&sig_pending)) {
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
}
if (sig_pending) {
set_syscall_param(dcontext, 4, dcontext->sys_param4);
set_failure_return_val(dcontext, EINTR);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
}
break;
}
#endif
/****************************************************************************/
/* FILES */
/* prevent app from closing our files or opening a new file in our fd space.
* it's not worth monitoring all syscalls that take in fds from affecting ours.
*/
#ifdef MACOS
case SYS_close_nocancel:
#endif
#ifdef SYS_close_range
case SYS_close_range: {
/* client.file_io indeed tests this for all arch, but it hasn't yet been
* run on an AArchXX machine that has close_range available.
*/
IF_AARCHXX(ASSERT_NOT_TESTED());
uint first_fd = sys_param(dcontext, 0), last_fd = sys_param(dcontext, 1);
uint flags = sys_param(dcontext, 2);
bool is_cloexec = TEST(CLOSE_RANGE_CLOEXEC, flags);
if (is_cloexec) {
/* client.file_io has a test for CLOSE_RANGE_CLOEXEC, but it hasn't been
* verified on a system with kernel version >= 5.11 yet.
*/
ASSERT_NOT_TESTED();
}
/* We do not let the app execute their own close_range ever. Instead we
* make multiple close_range syscalls ourselves, one for each contiguous
* sub-range of non-DR-private fds in [first, last].
*/
execute_syscall = false;
if (first_fd > last_fd) {
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
break;
}
uint cur_range_first_fd, cur_range_last_fd;
bool cur_range_valid = false;
int ret = 0;
for (int i = first_fd; i <= last_fd; i++) {
/* Do not allow any changes to DR-owned FDs. */
if ((is_cloexec && fd_is_dr_owned(i)) ||
(!is_cloexec && !handle_close_range_pre(dcontext, i))) {
SYSLOG_INTERNAL_WARNING_ONCE("app trying to close private fd(s)");
if (cur_range_valid) {
cur_range_valid = false;
ret = dynamorio_syscall(SYS_close_range, 3, cur_range_first_fd,
cur_range_last_fd, flags);
if (ret != 0)
break;
}
} else {
# ifdef LINUX
if (!is_cloexec) {
signal_handle_close(dcontext, i);
}
# endif
if (cur_range_valid) {
ASSERT(cur_range_last_fd == i - 1);
cur_range_last_fd = i;
} else {
cur_range_first_fd = i;
cur_range_last_fd = i;
cur_range_valid = true;
}
}
}
if (cur_range_valid) {
ret = dynamorio_syscall(SYS_close_range, 3, cur_range_first_fd,
cur_range_last_fd, flags);
}
if (ret != 0) {
set_failure_return_val(dcontext, ret);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else {
set_success_return_val(dcontext, 0);
}
break;
}
#endif
case SYS_close: {
execute_syscall = handle_close_pre(dcontext);
#ifdef LINUX
if (execute_syscall)
signal_handle_close(dcontext, (file_t)sys_param(dcontext, 0));
#endif
break;
}
#if defined(SYS_dup2) || defined(SYS_dup3)
# ifdef SYS_dup3
case SYS_dup3:
# endif
# ifdef SYS_dup2
case SYS_dup2:
# endif
{
file_t newfd = (file_t)sys_param(dcontext, 1);
if (fd_is_dr_owned(newfd) || fd_is_in_private_range(newfd)) {
SYSLOG_INTERNAL_WARNING_ONCE("app trying to dup-close DR file(s)");
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"WARNING: app trying to dup2/dup3 to %d. Disallowing.\n", newfd);
if (DYNAMO_OPTION(fail_on_stolen_fds)) {
set_failure_return_val(dcontext, EBADF);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else
set_success_return_val(dcontext, 0);
execute_syscall = false;
}
break;
}
#endif
#ifdef MACOS
case SYS_fcntl_nocancel:
#endif
case SYS_fcntl: {
int cmd = (int)sys_param(dcontext, 1);
long arg = (long)sys_param(dcontext, 2);
/* we only check for asking for min in private space: not min below
* but actual will be above (see notes in os_file_init())
*/
if ((cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC) && fd_is_in_private_range(arg)) {
SYSLOG_INTERNAL_WARNING_ONCE("app trying to open private fd(s)");
LOG(THREAD, LOG_TOP | LOG_SYSCALLS, 1,
"WARNING: app trying to dup to >= %d. Disallowing.\n", arg);
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
} else {
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = cmd;
}
break;
}
#if defined(X64) || !defined(ARM) || defined(MACOS)
case SYS_getrlimit:
#endif
#if defined(LINUX) && !defined(X64)
case SYS_ugetrlimit:
#endif
/* save for post */
dcontext->sys_param0 = sys_param(dcontext, 0); /* resource */
dcontext->sys_param1 = sys_param(dcontext, 1); /* rlimit */
break;
case SYS_setrlimit: {
int resource = (int)sys_param(dcontext, 0);
if (resource == RLIMIT_NOFILE && DYNAMO_OPTION(steal_fds) > 0) {
#if !defined(ARM) && !defined(X64) && !defined(MACOS)
struct compat_rlimit rlim;
#else
struct rlimit rlim;
#endif
if (!d_r_safe_read((void *)sys_param(dcontext, 1), sizeof(rlim), &rlim)) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EFAULT to app for prlimit64\n");
set_failure_return_val(dcontext, EFAULT);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else if (rlim.rlim_cur > rlim.rlim_max) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EINVAL for prlimit64\n");
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else if (rlim.rlim_max <= min_dr_fd &&
/* Can't raise hard unless have CAP_SYS_RESOURCE capability.
* XXX i#2980: should query for that capability.
*/
rlim.rlim_max <= app_rlimit_nofile.rlim_max) {
/* if the new rlimit is lower, pretend succeed */
app_rlimit_nofile.rlim_cur = rlim.rlim_cur;
app_rlimit_nofile.rlim_max = rlim.rlim_max;
set_success_return_val(dcontext, 0);
} else {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EPERM to app for setrlimit\n");
/* don't let app raise limits as that would mess up our fd space */
set_failure_return_val(dcontext, EPERM);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
}
execute_syscall = false;
}
break;
}
#ifdef LINUX
case SYS_prlimit64:
/* save for post */
dcontext->sys_param0 = sys_param(dcontext, 0); /* pid */
dcontext->sys_param1 = sys_param(dcontext, 1); /* resource */
dcontext->sys_param2 = sys_param(dcontext, 2); /* new rlimit */
dcontext->sys_param3 = sys_param(dcontext, 3); /* old rlimit */
if (/* XXX: how do we handle the case of setting rlimit.nofile on another
* process that is running with DynamoRIO?
*/
/* XXX: CLONE_FILES allows different processes to share the same file
* descriptor table, and different threads of the same process have
* separate file descriptor tables. POSIX specifies that rlimits are
* per-process, not per-thread, and Linux follows suit, so the threads
* with different descriptors will not matter, and the pids sharing
* descriptors turns into the hard-to-solve IPC problem.
*/
(dcontext->sys_param0 == 0 || dcontext->sys_param0 == get_process_id()) &&
dcontext->sys_param1 == RLIMIT_NOFILE &&
dcontext->sys_param2 != (reg_t)NULL && DYNAMO_OPTION(steal_fds) > 0) {
rlimit64_t rlim;
if (!d_r_safe_read((void *)(dcontext->sys_param2), sizeof(rlim), &rlim)) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EFAULT to app for prlimit64\n");
set_failure_return_val(dcontext, EFAULT);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else {
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: prlimit64 soft=" INT64_FORMAT_STRING
" hard=" INT64_FORMAT_STRING " vs DR %d\n",
rlim.rlim_cur, rlim.rlim_max, min_dr_fd);
if (rlim.rlim_cur > rlim.rlim_max) {
LOG(THREAD, LOG_SYSCALLS, 2, "\treturning EINVAL for prlimit64\n");
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
} else if (rlim.rlim_max <= min_dr_fd &&
/* Can't raise hard unless have CAP_SYS_RESOURCE capability.
* XXX i#2980: should query for that capability.
*/
rlim.rlim_max <= app_rlimit_nofile.rlim_max) {
/* if the new rlimit is lower, pretend succeed */
app_rlimit_nofile.rlim_cur = rlim.rlim_cur;
app_rlimit_nofile.rlim_max = rlim.rlim_max;
set_success_return_val(dcontext, 0);
/* set old rlimit if necessary */
if (dcontext->sys_param3 != (reg_t)NULL) {
safe_write_ex((void *)(dcontext->sys_param3), sizeof(rlim),
&app_rlimit_nofile, NULL);
}
} else {
/* don't let app raise limits as that would mess up our fd space */
LOG(THREAD, LOG_SYSCALLS, 2,
"\treturning EPERM to app for prlimit64\n");
set_failure_return_val(dcontext, EPERM);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
}
}
execute_syscall = false;
}
break;
#endif
#ifdef LINUX
# ifdef SYS_readlink
case SYS_readlink:
# endif
case SYS_readlinkat:
if (DYNAMO_OPTION(early_inject)) {
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
dcontext->sys_param2 = sys_param(dcontext, 2);
if (dcontext->sys_num == SYS_readlinkat)
dcontext->sys_param3 = sys_param(dcontext, 3);
}
break;
/* i#107 syscalls that might change/query app's segment */
# if defined(X86) && defined(X64)
case SYS_arch_prctl: {
/* we handle arch_prctl in post_syscall */
dcontext->sys_param0 = sys_param(dcontext, 0);
dcontext->sys_param1 = sys_param(dcontext, 1);
break;
}
# endif
# ifdef X86
case SYS_set_thread_area: {
our_modify_ldt_t desc;
if (INTERNAL_OPTION(mangle_app_seg) &&
d_r_safe_read((void *)sys_param(dcontext, 0), sizeof(desc), &desc)) {
if (os_set_app_thread_area(dcontext, &desc) &&
safe_write_ex((void *)sys_param(dcontext, 0), sizeof(desc), &desc,
NULL)) {
/* check if the range is unlimited */
ASSERT_CURIOSITY(desc.limit == 0xfffff);
execute_syscall = false;
set_success_return_val(dcontext, 0);
}
}
break;
}
case SYS_get_thread_area: {
our_modify_ldt_t desc;
if (INTERNAL_OPTION(mangle_app_seg) &&
d_r_safe_read((const void *)sys_param(dcontext, 0), sizeof(desc), &desc)) {
if (os_get_app_thread_area(dcontext, &desc) &&
safe_write_ex((void *)sys_param(dcontext, 0), sizeof(desc), &desc,
NULL)) {
execute_syscall = false;
set_success_return_val(dcontext, 0);
}
}
break;
}
# endif /* X86 */
# ifdef ARM
case SYS_set_tls: {
LOG(THREAD, LOG_VMAREAS | LOG_SYSCALLS, 2, "syscall: set_tls " PFX "\n",
sys_param(dcontext, 0));
if (os_set_app_tls_base(dcontext, TLS_REG_LIB, (void *)sys_param(dcontext, 0))) {
execute_syscall = false;
set_success_return_val(dcontext, 0);
} else {
ASSERT_NOT_REACHED();
}
break;
}
case SYS_cacheflush: {
/* We assume we don't want to change the executable_areas list or change
* the selfmod status of this region: else we should call something
* that invokes handle_modified_code() in a way that handles a bigger
* region than a single write.
*/
app_pc start = (app_pc)sys_param(dcontext, 0);
app_pc end = (app_pc)sys_param(dcontext, 1);
LOG(THREAD, LOG_VMAREAS | LOG_SYSCALLS, 2,
"syscall: cacheflush " PFX "-" PFX "\n", start, end);
flush_fragments_from_region(dcontext, start, end - start,
/* An unlink flush should be fine: the app must
* use synch to ensure other threads see the
* new code.
*/
false /*don't force synchall*/,
NULL /*flush_completion_callback*/,
NULL /*user_data*/);
break;
}
# endif /* ARM */
#elif defined(MACOS)
/* FIXME i#58: handle i386_{get,set}_ldt and thread_fast_set_cthread_self64 */
#endif
#ifdef DEBUG
# ifdef MACOS
case SYS_open_nocancel:
# endif
# ifdef SYS_open
case SYS_open: {
dcontext->sys_param0 = sys_param(dcontext, 0);
break;
}
# endif
#endif
#ifdef SYS_openat2
case SYS_openat2:
#endif
case SYS_openat: {
/* XXX: For completeness we might want to replace paths for SYS_open and
* possibly others, but SYS_openat is all we need on modern systems so we
* limit syscall overhead to this single point for now.
*/
dcontext->sys_param0 = 0;
dcontext->sys_param1 = sys_param(dcontext, 1);
const char *path = (const char *)dcontext->sys_param1;
if (!IS_STRING_OPTION_EMPTY(xarch_root) && !os_file_exists(path, false)) {
char *buf = heap_alloc(dcontext, MAXIMUM_PATH HEAPACCT(ACCT_OTHER));
string_option_read_lock();
snprintf(buf, MAXIMUM_PATH, "%s/%s", DYNAMO_OPTION(xarch_root), path);
buf[MAXIMUM_PATH - 1] = '\0';
string_option_read_unlock();
if (os_file_exists(buf, false)) {
LOG(THREAD, LOG_SYSCALLS, 2, "SYS_openat: replacing |%s| with |%s|\n",
path, buf);
set_syscall_param(dcontext, 1, (reg_t)buf);
/* Save for freeing in post. */
dcontext->sys_param0 = (reg_t)buf;
} else
heap_free(dcontext, buf, MAXIMUM_PATH HEAPACCT(ACCT_OTHER));
}
break;
}
#ifdef LINUX
case SYS_rseq:
LOG(THREAD, LOG_VMAREAS | LOG_SYSCALLS, 2, "syscall: rseq " PFX " %d %d %d\n",
sys_param(dcontext, 0), sys_param(dcontext, 1), sys_param(dcontext, 2),
sys_param(dcontext, 3));
if (DYNAMO_OPTION(disable_rseq)) {
set_failure_return_val(dcontext, ENOSYS);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
execute_syscall = false;
} else {
dcontext->sys_param0 = sys_param(dcontext, 0);
}
break;
#endif
default: {
#ifdef VMX86_SERVER
if (is_vmkuw_sysnum(dcontext->sys_num)) {
execute_syscall = vmkuw_pre_system_call(dcontext);
break;
}
#endif
break;
}
} /* end switch */
dcontext->whereami = old_whereami;
return execute_syscall;
}
void
all_memory_areas_lock(void)
{
IF_NO_MEMQUERY(memcache_lock());
}
void
all_memory_areas_unlock(void)
{
IF_NO_MEMQUERY(memcache_unlock());
}
void
update_all_memory_areas(app_pc start, app_pc end, uint prot, int type)
{
IF_NO_MEMQUERY(memcache_update(start, end, prot, type));
}
bool
remove_from_all_memory_areas(app_pc start, app_pc end)
{
IF_NO_MEMQUERY(return memcache_remove(start, end));
return true;
}
/* We consider a module load to happen at the first mmap, so we check on later
* overmaps to ensure things look consistent. */
static bool
mmap_check_for_module_overlap(app_pc base, size_t size, bool readable, uint64 inode,
bool at_map)
{
module_area_t *ma;
os_get_module_info_lock();
ma = module_pc_lookup(base);
if (ma != NULL) {
/* FIXME - how can we distinguish between the loader mapping the segments
* over the initial map from someone just mapping over part of a module? If
* is the latter case need to adjust the view size or remove from module list. */
LOG(GLOBAL, LOG_VMAREAS, 2,
"%s mmap overlapping module area : \n"
"\tmap : base=" PFX " base+size=" PFX " inode=" UINT64_FORMAT_STRING "\n"
"\tmod : start=" PFX " end=" PFX " inode=" UINT64_FORMAT_STRING "\n",
at_map ? "new" : "existing", base, base + size, inode, ma->start, ma->end,
ma->names.inode);
ASSERT_CURIOSITY(base >= ma->start);
if (at_map) {
ASSERT_CURIOSITY(base + size <= ma->end);
} else {
/* FIXME - I'm having problems with this check for existing maps. I
* haven't been able to get gdb to break in early enough to really get a good
* look at the early loader behavior. Two issues: One case is with our .so
* for which the anonymous .bss mapping is one page larger than expected
* (which might be some loader bug in the size calculation? or something? if
* so should see it trigger the at_map curiosity on some dll and can address
* then) and the other is that for a few executables the .bss mapping is much
* larger (~0x20000 larger) then expected when running under DR (but not
* running natively where it is instead the expected size). Both could just
* be the loader merging adjacent identically protected regions though I
* can't explain the discrepancy between DR and native given that our vmmheap
* is elsewhere in the address space (so who and how allocated that adjacent
* memory). I've yet to see any issue with dynamically loaded modules so
* it's probably the loader merging regions. Still worth investigating. */
ASSERT_CURIOSITY(inode == 0 /*see above comment*/ ||
module_contains_addr(ma, base + size - 1));
}
/* Handle cases like transparent huge pages where there are anon regions on top
* of the file mapping (i#2566).
*/
if (ma->names.inode == 0)
ma->names.inode = inode;
ASSERT_CURIOSITY(ma->names.inode == inode || inode == 0 /* for .bss */);
DOCHECK(1, {
if (readable && module_is_header(base, size)) {
/* Case 8879: For really small modules, to save disk space, the same
* disk page could hold both RO and .data, occupying just 1 page of
* disk space, e.g. /usr/lib/httpd/modules/mod_auth_anon.so. When
* such a module is mapped in, the os maps the same disk page twice,
* one readonly and one copy-on-write (see pg. 96, Sec 4.4 from
* Linkers and Loaders by John R. Levine). It also possible for
* such small modules to have multiple LOAD data segments. Since all
* these segments are mapped from a single disk page they will all have an
* elf_header satisfying the check above. So, if the new mmap overlaps an
* elf_area and it is also a header, then make sure the offsets (from the
* beginning of the backing file) of all the segments up to the currect
* one are within the page size. Note, if it is a header of a different
* module, then we'll not have an overlap, so we will not hit this case.
*/
bool cur_seg_found = false;
int seg_id = 0;
while (seg_id < ma->os_data.num_segments &&
ma->os_data.segments[seg_id].start <= base) {
cur_seg_found = ma->os_data.segments[seg_id].start == base;
ASSERT_CURIOSITY(
ma->os_data.segments[seg_id].offset <
PAGE_SIZE
/* On Mac we walk the dyld module list before the
* address space, so we often hit modules we already
* know about. */
IF_MACOS(|| !dynamo_initialized && ma->start == base));
++seg_id;
}
ASSERT_CURIOSITY(cur_seg_found);
}
});
}
os_get_module_info_unlock();
#ifdef ANDROID
/* i#1860: we need to keep looking for the segment with .dynamic as Android's
* loader does not map the whole file up front.
*/
if (ma != NULL && at_map && readable)
os_module_update_dynamic_info(base, size, at_map);
#endif
return ma != NULL;
}
static void
os_add_new_app_module(dcontext_t *dcontext, bool at_map, app_pc base, size_t size,
uint memprot)
{
memquery_iter_t iter;
bool found_map = false;
uint64 inode = 0;
const char *filename = "";
size_t mod_size = size;
if (!at_map) {
/* the size is the first seg size, get the whole module size instead */
app_pc first_seg_base = NULL;
app_pc first_seg_end = NULL;
app_pc last_seg_end = NULL;
if (module_walk_program_headers(base, size, at_map, false, &first_seg_base,
&first_seg_end, &last_seg_end, NULL, NULL)) {
ASSERT_CURIOSITY(size ==
(ALIGN_FORWARD(first_seg_end, PAGE_SIZE) -
(ptr_uint_t)first_seg_base) ||
base == vdso_page_start || base == vsyscall_page_start);
mod_size =
ALIGN_FORWARD(last_seg_end, PAGE_SIZE) - (ptr_uint_t)first_seg_base;
}
}
LOG(THREAD, LOG_SYSCALLS | LOG_VMAREAS, 2, "dlopen " PFX "-" PFX "%s\n", base,
base + mod_size, TEST(MEMPROT_EXEC, memprot) ? " +x" : "");
/* Mapping in a new module. From what we've observed of the loader's
* behavior, it first maps the file in with size equal to the final
* memory image size (I'm not sure how it gets that size without reading
* in the elf header and then walking through all the program headers to
* get the largest virtual offset). This is necessary to reserve all the
* space that will be needed. It then walks through the program headers
* mapping over the the previously mapped space with the appropriate
* permissions and offsets. Note that the .bss portion is mapped over
* as anonymous. It may also, depending on the program headers, make some
* areas read-only after fixing up their relocations etc. NOTE - at
* no point are the section headers guaranteed to be mapped in so we can't
* reliably walk sections (only segments) without looking to disk.
*/
/* FIXME - when should we add the module to our list? At the first map
* seems to be the best choice as we know the bounds and it's difficult to
* tell when the loader is finished. The downside is that at the initial map
* the memory layout isn't finalized (memory beyond the first segment will
* be shifted for page alignment reasons), so we have to be careful and
* make adjustments to read anything beyond the first segment until the
* loader finishes. This goes for the client too as it gets notified when we
* add to the list. FIXME we could try to track the expected segment overmaps
* and only notify the client after the last one (though that's still before
* linking and relocation, but that's true on Windows too). */
/* Get filename & inode for the list. */
memquery_iterator_start(&iter, base, true /* plan to alloc a module_area_t */);
while (memquery_iterator_next(&iter)) {
if (iter.vm_start == base) {
ASSERT_CURIOSITY(iter.inode != 0 || base == vdso_page_start ||
base == vsyscall_page_start);
ASSERT_CURIOSITY(iter.offset == 0); /* first map shouldn't have offset */
/* XREF 307599 on rounding module end to the next PAGE boundary */
ASSERT_CURIOSITY(
(iter.vm_end - iter.vm_start == ALIGN_FORWARD(size, PAGE_SIZE)));
inode = iter.inode;
filename = dr_strdup(iter.comment HEAPACCT(ACCT_OTHER));
found_map = true;
break;
}
}
memquery_iterator_stop(&iter);
#ifdef HAVE_MEMINFO
/* barring weird races we should find this map except */
ASSERT_CURIOSITY(found_map);
#else /* HAVE_MEMINFO */
/* Without /proc/maps or other memory querying interface available at
* library map time, there is no way to find out the name of the file
* that was mapped, thus its inode isn't available either.
*
* Just module_list_add with no filename will still result in
* library name being extracted from the .dynamic section and added
* to the module list. However, this name may not always exist, thus
* we might have a library with no file name available at all!
*
* Note: visor implements vsi mem maps that give file info, but, no
* path, should be ok. xref PR 401580.
*
* Once PR 235433 is implemented in visor then fix memquery_iterator*() to
* use vsi to find out page protection info, file name & inode.
*/
#endif /* HAVE_MEMINFO */
/* XREF 307599 on rounding module end to the next PAGE boundary */
if (found_map) {
module_list_add(base, ALIGN_FORWARD(mod_size, PAGE_SIZE), at_map, filename,
inode);
dr_strfree(filename HEAPACCT(ACCT_OTHER));
}
}
void
os_check_new_app_module(dcontext_t *dcontext, app_pc pc)
{
module_area_t *ma;
os_get_module_info_lock();
ma = module_pc_lookup(pc);
/* ma might be NULL due to dynamic generated code or custom loaded modules */
if (ma == NULL) {
dr_mem_info_t info;
/* i#1760: an app module loaded by custom loader (e.g., bionic libc)
* might not be detected by DynamoRIO in process_mmap.
*/
if (query_memory_ex_from_os(pc, &info) && info.type == DR_MEMTYPE_IMAGE) {
/* add the missing module */
os_get_module_info_unlock();
os_add_new_app_module(get_thread_private_dcontext(), false /*!at_map*/,
info.base_pc, info.size, info.prot);
os_get_module_info_lock();
}
}
os_get_module_info_unlock();
}
/* All processing for mmap and mmap2. */
static void
process_mmap(dcontext_t *dcontext, app_pc base, size_t size, uint prot,
uint flags _IF_DEBUG(const char *map_type))
{
bool image = false;
uint memprot = osprot_to_memprot(prot);
#ifdef ANDROID
/* i#1861: avoid merging file-backed w/ anon regions */
if (!TEST(MAP_ANONYMOUS, flags))
memprot |= MEMPROT_HAS_COMMENT;
#endif
LOG(THREAD, LOG_SYSCALLS, 4, "process_mmap(" PFX "," PFX ",0x%x,%s,%s)\n", base, size,
flags, memprot_string(memprot), map_type);
/* Notes on how ELF SOs are mapped in.
*
* o The initial mmap for an ELF file specifies enough space for
* all segments (and their constituent sections) in the file.
* The protection bits for that section are used for the entire
* region, and subsequent mmaps for subsequent segments within
* the region modify their portion's protection bits as needed.
* So if the prot bits for the first segment are +x, the entire
* region is +x. ** Note that our primary concern is adjusting
* exec areas to reflect the prot bits of subsequent
* segments. ** The region is added to the all-memory areas
* and also to exec areas (as determined by app_memory_allocation()).
*
* o Any subsequent segment sub-mappings specify their own protection
* bits and therefore are added to the exec areas via normal
* processing. They are also "naturally" added to the all-mems list.
* We do a little extra processing when mapping into a previously
* mapped region and the prot bits mismatch; if the new mapping is
* not +x, flushing needs to occur.
*/
/* process_mmap can be called with PROT_NONE, so we need to check if we
* can read the memory to see if it is a elf_header
*/
/* XXX: get inode for check */
if (TEST(MAP_ANONYMOUS, flags)) {
/* not an ELF mmap */
LOG(THREAD, LOG_SYSCALLS, 4, "mmap " PFX ": anon\n", base);
} else if (mmap_check_for_module_overlap(base, size, TEST(MEMPROT_READ, memprot), 0,
true)) {
/* FIXME - how can we distinguish between the loader mapping the segments
* over the initial map from someone just mapping over part of a module? If
* is the latter case need to adjust the view size or remove from module list. */
image = true;
DODEBUG({ map_type = "ELF SO"; });
LOG(THREAD, LOG_SYSCALLS, 4, "mmap " PFX ": overlaps image\n", base);
} else if (TEST(MEMPROT_READ, memprot) &&
/* i#727: We can still get SIGBUS on mmap'ed files that can't be
* read, so pass size=0 to use a safe_read.
*/
module_is_header(base, 0)) {
#ifdef ANDROID
/* The Android loader's initial all-segment-covering mmap is anonymous */
dr_mem_info_t info;
if (query_memory_ex_from_os((byte *)ALIGN_FORWARD(base + size, PAGE_SIZE),
&info) &&
info.prot == MEMPROT_NONE && info.type == DR_MEMTYPE_DATA) {
LOG(THREAD, LOG_SYSCALLS, 4, "mmap " PFX ": Android elf\n", base);
image = true;
DODEBUG({ map_type = "ELF SO"; });
os_add_new_app_module(dcontext, true /*at_map*/, base,
/* pass segment size, not whole module size */
size, memprot);
} else
#endif
if (module_is_partial_map(base, size, memprot)) {
/* i#1240: App might read first page of ELF header using mmap, which
* might accidentally be treated as a module load. Heuristically
* distinguish this by saying that if this is the first mmap for an ELF
* (i.e., it doesn't overlap with a previous map), and if it's small,
* then don't treat it as a module load.
*/
LOG(THREAD, LOG_SYSCALLS, 4, "mmap " PFX ": partial\n", base);
} else {
LOG(THREAD, LOG_SYSCALLS, 4, "mmap " PFX ": elf header\n", base);
image = true;
DODEBUG({ map_type = "ELF SO"; });
os_add_new_app_module(dcontext, true /*at_map*/, base, size, memprot);
}
}
LOG(THREAD, LOG_SYSCALLS, 4, "\t try app_mem_alloc\n");
IF_NO_MEMQUERY(memcache_handle_mmap(dcontext, base, size, memprot, image));
if (app_memory_allocation(dcontext, base, size, memprot, image _IF_DEBUG(map_type)))
STATS_INC(num_app_code_modules);
LOG(THREAD, LOG_SYSCALLS, 4, "\t app_mem_alloc -- DONE\n");
}
#ifdef LINUX
/* Call right after the system call.
* i#173: old_prot and old_type should be from before the system call
*/
static bool
handle_app_mremap(dcontext_t *dcontext, byte *base, size_t size, byte *old_base,
size_t old_size, uint old_prot, uint old_type)
{
if (!mmap_syscall_succeeded(base))
return false;
if (base != old_base || size < old_size) { /* take action only if
* there was a change */
DEBUG_DECLARE(bool ok;)
/* fragments were shifted...don't try to fix them, just flush */
app_memory_deallocation(dcontext, (app_pc)old_base, old_size,
false /* don't own thread_initexit_lock */,
false /* not image, FIXME: somewhat arbitrary */);
DOCHECK(1, {
/* we don't expect to see remappings of modules */
os_get_module_info_lock();
ASSERT_CURIOSITY(!module_overlaps(base, size));
os_get_module_info_unlock();
});
/* Verify that the current prot on the new region (according to
* the os) is the same as what the prot used to be for the old
* region.
*/
DOCHECK(1, {
uint memprot;
ok = get_memory_info_from_os(base, NULL, NULL, &memprot);
/* allow maps to have +x,
* +x may be caused by READ_IMPLIES_EXEC set in personality flag (i#262)
*/
ASSERT(ok &&
(memprot == old_prot || (memprot & (~MEMPROT_EXEC)) == old_prot));
});
app_memory_allocation(dcontext, base, size, old_prot,
old_type == DR_MEMTYPE_IMAGE _IF_DEBUG("mremap"));
IF_NO_MEMQUERY(memcache_handle_mremap(dcontext, base, size, old_base, old_size,
old_prot, old_type));
}
return true;
}
static void
handle_app_brk(dcontext_t *dcontext, byte *lowest_brk /*if known*/, byte *old_brk,
byte *new_brk)
{
/* i#851: the brk might not be page aligned */
old_brk = (app_pc)ALIGN_FORWARD(old_brk, PAGE_SIZE);
new_brk = (app_pc)ALIGN_FORWARD(new_brk, PAGE_SIZE);
if (new_brk < old_brk) {
/* Usually the heap is writable, so we don't really need to call
* this here: but seems safest to do so, esp if someone made part of
* the heap read-only and then put code there.
*/
app_memory_deallocation(dcontext, new_brk, old_brk - new_brk,
false /* don't own thread_initexit_lock */,
false /* not image */);
} else if (new_brk > old_brk) {
/* No need to call app_memory_allocation() as doesn't interact
* w/ security policies.
*/
}
IF_NO_MEMQUERY(memcache_handle_app_brk(lowest_brk, old_brk, new_brk));
}
#endif
/* This routine is *not* called is pre_system_call() returns false to skip
* the syscall.
*/
/* XXX: split out specific handlers into separate routines
*/
void
post_system_call(dcontext_t *dcontext)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
/* registers have been clobbered, so sysnum is kept in dcontext */
int sysnum = dcontext->sys_num;
/* We expect most syscall failures to return < 0, so >= 0 is success.
* Some syscall return addresses that have the sign bit set and so
* appear to be failures but are not. They are handled on a
* case-by-case basis in the switch statement below.
*/
ptr_int_t result = (ptr_int_t)MCXT_SYSCALL_RES(mc); /* signed */
bool success = syscall_successful(mc, sysnum);
app_pc base;
size_t size;
uint prot;
dr_where_am_i_t old_whereami;
DEBUG_DECLARE(bool ok;)
RSTATS_INC(post_syscall);
old_whereami = dcontext->whereami;
dcontext->whereami = DR_WHERE_SYSCALL_HANDLER;
#if defined(LINUX) && defined(X86)
/* PR 313715: restore xbp since for some vsyscall sequences that use
* the syscall instruction its value is needed:
* 0xffffe400 <__kernel_vsyscall+0>: push %ebp
* 0xffffe401 <__kernel_vsyscall+1>: mov %ecx,%ebp
* 0xffffe403 <__kernel_vsyscall+3>: syscall
* 0xffffe405 <__kernel_vsyscall+5>: mov $0x2b,%ecx
* 0xffffe40a <__kernel_vsyscall+10>: movl %ecx,%ss
* 0xffffe40c <__kernel_vsyscall+12>: mov %ebp,%ecx
* 0xffffe40e <__kernel_vsyscall+14>: pop %ebp
* 0xffffe40f <__kernel_vsyscall+15>: ret
*/
if (should_syscall_method_be_sysenter() && !dcontext->sys_was_int) {
mc->xbp = dcontext->sys_xbp;
}
#endif
/* handle fork, try to do it early before too much logging occurs */
if (false
#ifdef SYS_fork
|| sysnum ==
SYS_fork
#endif
IF_LINUX(||
(sysnum == SYS_clone && !TEST(CLONE_VM, dcontext->sys_param0)) ||
(sysnum == SYS_clone3 &&
!TEST(CLONE_VM, get_stored_clone3_flags(dcontext))))) {
if (result == 0) {
/* we're the child */
thread_id_t child = get_sys_thread_id();
#ifdef DEBUG
thread_id_t parent = get_parent_id();
SYSLOG_INTERNAL_INFO("-- parent %d forked child %d --", parent, child);
#endif
/* first, fix TLS of dcontext */
ASSERT(parent != 0);
/* change parent pid to our pid */
replace_thread_id(dcontext->owning_thread, child);
dcontext->owning_thread = child;
dcontext->owning_process = get_process_id();
/* now let dynamo initialize new shared memory, logfiles, etc.
* need access to static vars in dynamo.c, that's why we don't do it. */
/* FIXME - xref PR 246902 - d_r_dispatch runs a lot of code before
* getting to post_system_call() is any of that going to be messed up
* by waiting till here to fixup the child logfolder/file and tid?
*/
dynamorio_fork_init(dcontext);
LOG(THREAD, LOG_SYSCALLS, 1,
"after fork-like syscall: parent is %d, child is %d\n", parent, child);
} else {
/* we're the parent */
os_fork_post(dcontext, true /*parent*/);
}
}
LOG(THREAD, LOG_SYSCALLS, 2, "post syscall: sysnum=" PFX ", result=" PFX " (%d)\n",
sysnum, MCXT_SYSCALL_RES(mc), (int)MCXT_SYSCALL_RES(mc));
switch (sysnum) {
/****************************************************************************/
/* MEMORY REGIONS */
#ifdef DEBUG
# ifdef MACOS
case SYS_open_nocancel:
# endif
# ifdef SYS_open
case SYS_open: {
if (success) {
/* useful for figuring out what module was loaded that then triggers
* module.c elf curiosities
*/
LOG(THREAD, LOG_SYSCALLS, 2, "SYS_open %s => %d\n", dcontext->sys_param0,
(int)result);
}
break;
}
# endif
#endif
#if defined(LINUX) && !defined(X64) && !defined(ARM)
case SYS_mmap:
#endif
case IF_MACOS_ELSE(SYS_mmap, IF_X64_ELSE(SYS_mmap, SYS_mmap2)): {
uint flags;
DEBUG_DECLARE(const char *map_type;)
RSTATS_INC(num_app_mmaps);
base = (app_pc)MCXT_SYSCALL_RES(mc); /* For mmap, it's NOT arg->addr! */
/* mmap isn't simply a user-space wrapper for mmap2. It's called
* directly when dynamically loading an SO, i.e., dlopen(). */
#ifdef LINUX /* MacOS success is in CF */
success = mmap_syscall_succeeded((app_pc)result);
/* The syscall either failed OR the retcode is less than the
* largest uint value of any errno and the addr returned is
* page-aligned.
*/
ASSERT_CURIOSITY(
!success ||
((app_pc)result < (app_pc)(ptr_int_t)-0x1000 && ALIGNED(base, PAGE_SIZE)));
#else
ASSERT_CURIOSITY(!success || ALIGNED(base, PAGE_SIZE));
#endif
if (!success)
goto exit_post_system_call;
#if defined(LINUX) && !defined(X64) && !defined(ARM)
if (sysnum == SYS_mmap) {
/* The syscall succeeded so the read of 'arg' should be
* safe. */
mmap_arg_struct_t *arg = (mmap_arg_struct_t *)dcontext->sys_param0;
size = (size_t)arg->len;
prot = (uint)arg->prot;
flags = (uint)arg->flags;
DEBUG_DECLARE(map_type = "mmap";)
} else {
#endif
size = (size_t)dcontext->sys_param1;
prot = (uint)dcontext->sys_param2;
flags = (uint)dcontext->sys_param3;
DEBUG_DECLARE(map_type = IF_X64_ELSE("mmap2", "mmap");)
#if defined(LINUX) && !defined(X64) && !defined(ARM)
}
#endif
process_mmap(dcontext, base, size, prot, flags _IF_DEBUG(map_type));
break;
}
case SYS_munmap: {
app_pc addr = (app_pc)dcontext->sys_param0;
size_t len = (size_t)dcontext->sys_param1;
/* We assumed in pre_system_call() that the unmap would succeed
* and flushed fragments and removed the region from exec areas.
* If the unmap failed, we re-add the region to exec areas.
* For zero-length unmaps we don't need to re-add anything,
* and we hit an assert in vmareas.c if we try (i#4031).
*
* The same logic can be used on Windows (but isn't yet).
*/
/* FIXME There are shortcomings to the approach. If another thread
* executes in the region after our pre_system_call processing
* but before the re-add below, it will get a security violation.
* That's less than ideal but at least isn't a security hole.
* The overall shortcoming is that we lose the state from our
* stateful security policies -- future exec list, tables used
* for RCT (.C/.E/.F) -- which can't be easily restored. Also,
* the re-add could add a region that wasn't on the exec list
* previously.
*
* See case 7559 for a better approach.
*/
if (!success && len != 0) {
dr_mem_info_t info;
/* must go to os to get real memory since we already removed */
DEBUG_DECLARE(ok =)
query_memory_ex_from_os(addr, &info);
ASSERT(ok);
app_memory_allocation(dcontext, addr, len, info.prot,
info.type ==
DR_MEMTYPE_IMAGE _IF_DEBUG("failed munmap"));
IF_NO_MEMQUERY(
memcache_update_locked((app_pc)ALIGN_BACKWARD(addr, PAGE_SIZE),
(app_pc)ALIGN_FORWARD(addr + len, PAGE_SIZE),
info.prot, info.type, false /*add back*/));
}
break;
}
#ifdef LINUX
case SYS_mremap: {
app_pc old_base = (app_pc)dcontext->sys_param0;
size_t old_size = (size_t)dcontext->sys_param1;
base = (app_pc)MCXT_SYSCALL_RES(mc);
size = (size_t)dcontext->sys_param2;
/* even if no shift, count as munmap plus mmap */
RSTATS_INC(num_app_munmaps);
RSTATS_INC(num_app_mmaps);
success =
handle_app_mremap(dcontext, base, size, old_base, old_size,
/* i#173: use memory prot and type
* obtained from pre_system_call
*/
(uint)dcontext->sys_param3, (uint)dcontext->sys_param4);
/* The syscall either failed OR the retcode is less than the
* largest uint value of any errno and the addr returned is
* is page-aligned.
*/
ASSERT_CURIOSITY(
!success ||
((app_pc)result < (app_pc)(ptr_int_t)-0x1000 && ALIGNED(base, PAGE_SIZE)));
if (!success)
goto exit_post_system_call;
break;
}
#endif
case SYS_mprotect: {
base = (app_pc)dcontext->sys_param0;
size = dcontext->sys_param1;
prot = dcontext->sys_param2;
#ifdef VMX86_SERVER
/* PR 475111: workaround for PR 107872 */
if (os_in_vmkernel_userworld() && result == -EBUSY && prot == PROT_NONE) {
result = mprotect_syscall(base, size, PROT_READ);
/* since non-Mac, we can use this even if the call failed */
set_success_return_val(dcontext, result);
success = (result >= 0);
LOG(THREAD, LOG_VMAREAS, 1,
"re-doing mprotect -EBUSY for " PFX "-" PFX " => %d\n", base, base + size,
(int)result);
SYSLOG_INTERNAL_WARNING_ONCE("re-doing mprotect for PR 475111, PR 107872");
}
#endif
/* FIXME i#143: we need to tweak the returned oldprot for
* writable areas we've made read-only
*/
if (!success) {
uint memprot = 0;
/* Revert the prot bits if needed. */
if (!get_memory_info_from_os(base, NULL, NULL, &memprot))
memprot = PROT_NONE;
LOG(THREAD, LOG_SYSCALLS, 3,
"syscall: mprotect failed: " PFX "-" PFX " prot->%d\n", base, base + size,
osprot_to_memprot(prot));
LOG(THREAD, LOG_SYSCALLS, 3, "\told prot->%d\n", memprot);
if (prot != memprot_to_osprot(memprot)) {
/* We're trying to reverse the prot change, assuming that
* this action doesn't have any unexpected side effects
* when doing so (such as not reversing some bit of internal
* state).
*/
uint new_memprot;
DEBUG_DECLARE(uint res =)
app_memory_protection_change(dcontext, base, size,
osprot_to_memprot(prot), &new_memprot, NULL,
false /*!image*/);
ASSERT_NOT_IMPLEMENTED(res != SUBSET_APP_MEM_PROT_CHANGE);
ASSERT(res == DO_APP_MEM_PROT_CHANGE ||
res == PRETEND_APP_MEM_PROT_CHANGE);
/* PR 410921 - Revert the changes to all-mems list.
* FIXME: This fix assumes the whole region had the prot &
* type, which is true in the cases we have seen so far, but
* theoretically may not be true. If it isn't true, multiple
* memory areas with different types/protections might have
* been changed in pre_system_call(), so will have to keep a
* list of all vmareas changed. This might be expensive for
* each mprotect syscall to guard against a rare theoretical bug.
*/
ASSERT_CURIOSITY(!dcontext->mprot_multi_areas);
IF_NO_MEMQUERY(memcache_update_locked(
base, base + size, memprot, -1 /*type unchanged*/, true /*exists*/));
}
}
break;
}
#ifdef ANDROID
case SYS_prctl: {
int code = (int)dcontext->sys_param0;
int subcode = (ulong)dcontext->sys_param1;
if (success && code == PR_SET_VMA && subcode == PR_SET_VMA_ANON_NAME) {
byte *addr = (byte *)dcontext->sys_param2;
size_t len = (size_t)dcontext->sys_param3;
IF_DEBUG(const char *comment = (const char *)dcontext->sys_param4;)
uint memprot = 0;
if (!get_memory_info_from_os(addr, NULL, NULL, &memprot))
memprot = MEMPROT_NONE;
/* We're post-syscall so from_os should match the prctl */
ASSERT((comment == NULL && !TEST(MEMPROT_HAS_COMMENT, memprot)) ||
(comment != NULL && TEST(MEMPROT_HAS_COMMENT, memprot)));
LOG(THREAD, LOG_SYSCALLS, 2,
"syscall: prctl PR_SET_VMA_ANON_NAME base=" PFX " size=" PFX
" comment=%s\n",
addr, len, comment == NULL ? "<null>" : comment);
IF_NO_MEMQUERY(memcache_update_locked(
addr, addr + len, memprot, -1 /*type unchanged*/, true /*exists*/));
}
break;
}
#endif
#ifdef LINUX
case SYS_brk: {
/* i#91/PR 396352: need to watch SYS_brk to maintain all_memory_areas.
* This code should work regardless of whether syscall failed
* (if it failed, the old break will be returned). We stored
* the old break in sys_param1 in pre-syscall.
*/
app_pc old_brk = (app_pc)dcontext->sys_param1;
app_pc new_brk = (app_pc)result;
DEBUG_DECLARE(app_pc req_brk = (app_pc)dcontext->sys_param0;);
ASSERT(!DYNAMO_OPTION(emulate_brk)); /* shouldn't get here */
# ifdef DEBUG
if (DYNAMO_OPTION(early_inject) &&
req_brk != NULL /* Ignore calls that don't increase brk. */) {
DO_ONCE({
ASSERT_CURIOSITY(new_brk > old_brk &&
"i#1004: first brk() "
"allocation failed with -early_inject");
});
}
# endif
handle_app_brk(dcontext, NULL, old_brk, new_brk);
break;
}
#endif
/****************************************************************************/
/* SPAWNING -- fork mostly handled above */
#ifdef LINUX
case SYS_clone3:
case SYS_clone: {
/* in /usr/src/linux/arch/i386/kernel/process.c */
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: clone returned " PFX "\n",
MCXT_SYSCALL_RES(mc));
/* TODO i#5221: Handle clone3 returning errors other than ENOSYS. */
/* We switch the lib tls segment back to dr's privlib segment.
* Please refer to comment on os_switch_lib_tls.
* It is only called in parent thread.
* The child thread's tls setup is done in os_tls_app_seg_init.
*/
if (was_thread_create_syscall(dcontext)) {
if (INTERNAL_OPTION(private_loader))
os_switch_lib_tls(dcontext, false /*to dr*/);
/* i#2089: we already restored the DR tls in os_clone_post() */
if (sysnum == SYS_clone3) {
/* Free DR's copy of clone_args and restore the pointer to the
* app's copy in the SYSCALL_PARAM_CLONE3_CLONE_ARGS reg.
* sys_param1 contains the pointer to DR's clone_args, and
* sys_param0 contains the pointer to the app's original
* clone_args.
*/
# ifdef X86
ASSERT(sys_param(dcontext, SYSCALL_PARAM_CLONE3_CLONE_ARGS) ==
dcontext->sys_param1);
set_syscall_param(dcontext, SYSCALL_PARAM_CLONE3_CLONE_ARGS,
dcontext->sys_param0);
# else
/* On AArchXX r0 is used to pass the first arg to the syscall as well as
* to hold its return value. As the clone_args pointer isn't available
* post-syscall natively anyway, there's no need to restore here.
*/
# endif
uint app_clone_args_size = (uint)dcontext->sys_param2;
heap_free(dcontext, (clone3_syscall_args_t *)dcontext->sys_param1,
app_clone_args_size HEAPACCT(ACCT_OTHER));
} else if (sysnum == SYS_clone) {
set_syscall_param(dcontext, SYSCALL_PARAM_CLONE_STACK,
dcontext->sys_param1);
}
}
break;
}
#elif defined(MACOS) && !defined(X64)
case SYS_bsdthread_create: {
/* restore stack values we clobbered */
ASSERT(*sys_param_addr(dcontext, 0) == (reg_t)new_bsdthread_intercept);
*sys_param_addr(dcontext, 0) = dcontext->sys_param0;
*sys_param_addr(dcontext, 1) = dcontext->sys_param1;
break;
}
#endif
#ifdef SYS_fork
case SYS_fork: {
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: fork returned " PFX "\n",
MCXT_SYSCALL_RES(mc));
break;
}
#endif
#ifdef SYS_vfork
case SYS_vfork: {
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: vfork returned " PFX "\n",
MCXT_SYSCALL_RES(mc));
IF_LINUX(ASSERT(was_thread_create_syscall(dcontext)));
/* restore xsp in parent */
LOG(THREAD, LOG_SYSCALLS, 2, "vfork: restoring xsp from " PFX " to " PFX "\n",
mc->xsp, dcontext->sys_param1);
mc->xsp = dcontext->sys_param1;
if (MCXT_SYSCALL_RES(mc) != 0) {
/* We switch the lib tls segment back to dr's segment.
* Please refer to comment on os_switch_lib_tls.
* It is only called in parent thread.
* The child thread's tls setup is done in os_tls_app_seg_init.
*/
if (INTERNAL_OPTION(private_loader)) {
os_switch_lib_tls(dcontext, false /*to dr*/);
}
/* i#2089: we already restored the DR tls in os_clone_post() */
}
break;
}
#endif
case SYS_execve: {
/* if we get here it means execve failed (doesn't return on success) */
success = false;
mark_thread_execve(dcontext->thread_record, false);
ASSERT(result < 0);
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: execve failed\n");
handle_execve_post(dcontext);
/* Don't 'break' as we have an ASSERT(success) just below
* the switch(). */
goto exit_post_system_call;
break; /* unnecessary but good form so keep it */
}
/****************************************************************************/
/* SIGNALS */
case IF_MACOS_ELSE(SYS_sigaction, SYS_rt_sigaction): { /* 174 */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage long
sys_rt_sigaction(int sig, const struct sigaction *act,
struct sigaction *oact, size_t sigsetsize)
*/
/* FIXME i#148: Handle syscall failure. */
int sig = (int)dcontext->sys_param0;
const kernel_sigaction_t *act = (const kernel_sigaction_t *)dcontext->sys_param1;
prev_sigaction_t *oact = (prev_sigaction_t *)dcontext->sys_param2;
size_t sigsetsize = (size_t)dcontext->sys_param3;
uint res;
res = handle_post_sigaction(dcontext, success, sig, act, oact, sigsetsize);
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: %ssigaction => %d\n",
IF_MACOS_ELSE("", "rt_"), -res);
if (res != 0)
set_failure_return_val(dcontext, res);
if (!success || res != 0)
goto exit_post_system_call;
break;
}
#if defined(LINUX) && !defined(X64)
case SYS_sigaction: { /* 67 */
int sig = (int)dcontext->sys_param0;
const old_sigaction_t *act = (const old_sigaction_t *)dcontext->sys_param1;
old_sigaction_t *oact = (old_sigaction_t *)dcontext->sys_param2;
uint res = handle_post_old_sigaction(dcontext, success, sig, act, oact);
LOG(THREAD, LOG_SYSCALLS, 2, "syscall: sigaction => %d\n", -res);
if (res != 0)
set_failure_return_val(dcontext, res);
if (!success || res != 0)
goto exit_post_system_call;
break;
}
#endif
case IF_MACOS_ELSE(SYS_sigprocmask, SYS_rt_sigprocmask): { /* 175 */
/* in /usr/src/linux/kernel/signal.c:
asmlinkage long
sys_rt_sigprocmask(int how, sigset_t *set, sigset_t *oset,
size_t sigsetsize)
*/
/* FIXME i#148: Handle syscall failure. */
handle_post_sigprocmask(
dcontext, (int)dcontext->sys_param0, (kernel_sigset_t *)dcontext->sys_param1,
(kernel_sigset_t *)dcontext->sys_param2, (size_t)dcontext->sys_param3);
break;
}
#if defined(LINUX) && !defined(X64)
case SYS_sigreturn: /* 119 */
#endif
case IF_MACOS_ELSE(SYS_sigreturn, SYS_rt_sigreturn): /* 173 */
/* there is no return value: it's just the value of eax, so avoid
* assert below
*/
success = true;
break;
case SYS_setitimer: /* 104 */
handle_post_setitimer(dcontext, success, (int)dcontext->sys_param0,
(const struct itimerval *)dcontext->sys_param1,
(struct itimerval *)dcontext->sys_param2);
break;
case SYS_getitimer: /* 105 */
handle_post_getitimer(dcontext, success, (int)dcontext->sys_param0,
(struct itimerval *)dcontext->sys_param1);
break;
#if defined(LINUX) && defined(X86)
case SYS_alarm: /* 27 on x86 and 37 on x64 */
handle_post_alarm(dcontext, success, (unsigned int)dcontext->sys_param0);
break;
#endif
#if defined(LINUX) && defined(X86) && defined(X64)
case SYS_arch_prctl: {
if (success && INTERNAL_OPTION(mangle_app_seg)) {
tls_handle_post_arch_prctl(dcontext, dcontext->sys_param0,
dcontext->sys_param1);
}
break;
}
#endif
#ifdef LINUX
# ifdef SYS_ppoll_time64
case SYS_ppoll_time64:
# endif
case SYS_ppoll: {
if (dcontext->sys_param3 == (reg_t)NULL)
break;
handle_post_extended_syscall_sigmasks(dcontext, success);
set_syscall_param(dcontext, 3, dcontext->sys_param3);
break;
}
# ifdef SYS_pselect6_time64
case SYS_pselect6_time64:
# endif
case SYS_pselect6: {
if (dcontext->sys_param4 == (reg_t)NULL)
break;
typedef struct {
kernel_sigset_t *sigmask;
size_t sizemask;
} data_t;
data_t *data_param = (data_t *)dcontext->sys_param3;
handle_post_extended_syscall_sigmasks(dcontext, success);
if (!safe_write_ex((void *)&data_param->sigmask, sizeof(data_param->sigmask),
&dcontext->sys_param4, NULL)) {
LOG(THREAD, LOG_SYSCALLS, 2, "\tEFAULT for pselect6 post syscall\n");
}
break;
}
case SYS_epoll_pwait: {
if (dcontext->sys_param4 == (reg_t)NULL)
break;
handle_post_extended_syscall_sigmasks(dcontext, success);
set_syscall_param(dcontext, 4, dcontext->sys_param4);
break;
}
#endif
/****************************************************************************/
/* FILES */
#ifdef SYS_dup2
case SYS_dup2: IF_LINUX(case SYS_dup3:) {
# ifdef LINUX
if (success) {
signal_handle_dup(dcontext, (file_t)sys_param(dcontext, 1),
(file_t)result);
}
# endif
break;
}
#endif
#ifdef MACOS
case SYS_fcntl_nocancel:
#endif
case SYS_fcntl: {
#ifdef LINUX /* Linux-only since only for signalfd */
if (success) {
file_t fd = (long)dcontext->sys_param0;
int cmd = (int)dcontext->sys_param1;
if ((cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC))
signal_handle_dup(dcontext, fd, (file_t)result);
}
break;
#endif
}
case IF_MACOS_ELSE(SYS_getrlimit, IF_X64_ELSE(SYS_getrlimit, SYS_ugetrlimit)): {
int resource = dcontext->sys_param0;
if (success && resource == RLIMIT_NOFILE) {
/* we stole some space: hide it from app */
struct rlimit *rlim = (struct rlimit *)dcontext->sys_param1;
safe_write_ex(&rlim->rlim_cur, sizeof(rlim->rlim_cur),
&app_rlimit_nofile.rlim_cur, NULL);
safe_write_ex(&rlim->rlim_max, sizeof(rlim->rlim_max),
&app_rlimit_nofile.rlim_max, NULL);
}
break;
}
#if !defined(ARM) && !defined(X64) && !defined(MACOS)
/* Old struct w/ smaller fields */
case SYS_getrlimit: {
int resource = dcontext->sys_param0;
if (success && resource == RLIMIT_NOFILE) {
struct compat_rlimit *rlim = (struct compat_rlimit *)dcontext->sys_param1;
safe_write_ex(&rlim->rlim_cur, sizeof(rlim->rlim_cur),
&app_rlimit_nofile.rlim_cur, NULL);
safe_write_ex(&rlim->rlim_max, sizeof(rlim->rlim_max),
&app_rlimit_nofile.rlim_max, NULL);
}
break;
}
#endif
#ifdef LINUX
case SYS_prlimit64: {
int resource = dcontext->sys_param1;
rlimit64_t *rlim = (rlimit64_t *)dcontext->sys_param3;
if (success && resource == RLIMIT_NOFILE && rlim != NULL &&
/* XXX: xref pid discussion in pre_system_call SYS_prlimit64 */
(dcontext->sys_param0 == 0 || dcontext->sys_param0 == get_process_id())) {
safe_write_ex(rlim, sizeof(*rlim), &app_rlimit_nofile, NULL);
}
break;
}
#endif
#ifdef LINUX
# ifdef SYS_readlink
case SYS_readlink:
# endif
case SYS_readlinkat:
if (success && DYNAMO_OPTION(early_inject)) {
bool is_at = (sysnum == SYS_readlinkat);
/* i#907: /proc/self/exe is a symlink to libdynamorio.so. We need
* to fix it up if the app queries. Any thread id can be passed to
* /proc/%d/exe, so we have to check. We could instead look for
* libdynamorio.so in the result but we've tweaked our injector
* in the past to exec different binaries so this seems more robust.
*/
if (symlink_is_self_exe((const char *)(is_at ? dcontext->sys_param1
: dcontext->sys_param0))) {
char *tgt = (char *)(is_at ? dcontext->sys_param2 : dcontext->sys_param1);
size_t tgt_sz =
(size_t)(is_at ? dcontext->sys_param3 : dcontext->sys_param2);
int len = snprintf(tgt, tgt_sz, "%s", get_application_name());
if (len > 0)
set_success_return_val(dcontext, len);
else {
set_failure_return_val(dcontext, EINVAL);
DODEBUG({ dcontext->expect_last_syscall_to_fail = true; });
}
}
}
break;
# ifdef SYS_openat2
case SYS_openat2:
# endif
case SYS_openat:
if (dcontext->sys_param0 != 0) {
heap_free(dcontext, (void *)dcontext->sys_param0,
MAXIMUM_PATH HEAPACCT(ACCT_OTHER));
}
break;
case SYS_rseq:
/* Lazy rseq handling. */
if (success) {
rseq_process_syscall(dcontext);
rseq_locate_rseq_regions();
}
break;
#endif
default:
#ifdef VMX86_SERVER
if (is_vmkuw_sysnum(sysnum)) {
vmkuw_post_system_call(dcontext);
break;
}
#endif
break;
} /* switch */
DODEBUG({
if (ignorable_system_call_normalized(sysnum)) {
STATS_INC(post_syscall_ignorable);
} else {
/* Many syscalls can fail though they aren't ignored. However, they
* shouldn't happen without us knowing about them. See PR 402769
* for SYS_close case.
*/
if (!(success || sysnum == SYS_close ||
IF_MACOS(sysnum == SYS_close_nocancel ||)
dcontext->expect_last_syscall_to_fail)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"Unexpected failure of non-ignorable syscall %d\n", sysnum);
}
}
});
exit_post_system_call:
/* The instrument_post_syscall should be called after DR finishes all
* its operations, since DR needs to know the real syscall results,
* and any changes made by the client are simply to fool the app.
* Also, dr_syscall_invoke_another() needs to set eax, which shouldn't
* affect the result of the 1st syscall. Xref i#1.
*/
/* after restore of xbp so client sees it as though was sysenter */
instrument_post_syscall(dcontext, sysnum);
dcontext->whereami = old_whereami;
}
#ifdef LINUX
# ifdef STATIC_LIBRARY
/* Static libraries may optionally define two linker variables
* (dynamorio_so_start and dynamorio_so_end) to help mitigate
* edge cases in detecting DR's library bounds. They are optional.
*
* If not specified, the variables' location will default to
* weak_dynamorio_so_bounds_filler and they will not be used.
* Note that referencing the value of these symbols will crash:
* always use the address only.
*/
extern int dynamorio_so_start WEAK
__attribute__((alias("weak_dynamorio_so_bounds_filler")));
extern int dynamorio_so_end WEAK
__attribute__((alias("weak_dynamorio_so_bounds_filler")));
static int weak_dynamorio_so_bounds_filler;
# else /* !STATIC_LIBRARY */
/* For non-static linux we always get our bounds from linker-provided symbols.
* Note that referencing the value of these symbols will crash: always use the
* address only.
*/
extern int dynamorio_so_start, dynamorio_so_end;
# endif /* STATIC_LIBRARY */
#endif /* LINUX */
/* get_dynamo_library_bounds initializes dynamorio library bounds, using a
* release-time assert if there is a problem doing so. It does not use any
* heap, and we assume it is called prior to find_executable_vm_areas in a
* single thread.
*/
static void
get_dynamo_library_bounds(void)
{
/* Note that we're not counting DYNAMORIO_PRELOAD_NAME as a DR area, to match
* Windows, so we should unload it like we do there. The other reason not to
* count it is so is_in_dynamo_dll() can be the only exception to the
* never-execute-from-DR-areas list rule
*/
int res;
app_pc check_start, check_end;
char *libdir;
const char *dynamorio_libname = NULL;
bool do_memquery = true;
#ifdef STATIC_LIBRARY
# ifdef LINUX
/* For static+linux, we might have linker vars to help us and we definitely
* know our "library name" since we are in the app. When we have both we
* don't need to do a memquery.
*/
if (&dynamorio_so_start != &weak_dynamorio_so_bounds_filler &&
&dynamorio_so_end != &weak_dynamorio_so_bounds_filler) {
do_memquery = false;
dynamo_dll_start = (app_pc)&dynamorio_so_start;
dynamo_dll_end = (app_pc)ALIGN_FORWARD(&dynamorio_so_end, PAGE_SIZE);
LOG(GLOBAL, LOG_VMAREAS, 2,
"Using dynamorio_so_start and dynamorio_so_end for library bounds"
"\n");
const char *dr_path = get_application_name();
strncpy(dynamorio_library_filepath, dr_path,
BUFFER_SIZE_ELEMENTS(dynamorio_library_filepath));
NULL_TERMINATE_BUFFER(dynamorio_library_filepath);
const char *slash = strrchr(dr_path, '/');
ASSERT(slash != NULL);
/* Include the slash in the library path */
size_t copy_chars = 1 + slash - dr_path;
ASSERT(copy_chars < BUFFER_SIZE_ELEMENTS(dynamorio_library_path));
strncpy(dynamorio_library_path, dr_path, copy_chars);
dynamorio_library_path[copy_chars] = '\0';
}
# endif
if (do_memquery) {
/* No linker vars, so we need to find bound using an internal PC */
check_start = (app_pc)&get_dynamo_library_bounds;
}
#else /* !STATIC_LIBRARY */
# ifdef LINUX
/* PR 361594: we get our bounds from linker-provided symbols.
* Note that referencing the value of these symbols will crash:
* always use the address only.
*/
extern int dynamorio_so_start, dynamorio_so_end;
dynamo_dll_start = (app_pc)&dynamorio_so_start;
dynamo_dll_end = (app_pc)ALIGN_FORWARD(&dynamorio_so_end, PAGE_SIZE);
# elif defined(MACOS)
dynamo_dll_start = module_dynamorio_lib_base();
# endif
check_start = dynamo_dll_start;
#endif /* STATIC_LIBRARY */
if (do_memquery) {
static char dynamorio_libname_buf[MAXIMUM_PATH];
res = memquery_library_bounds(
NULL, &check_start, &check_end, dynamorio_library_path,
BUFFER_SIZE_ELEMENTS(dynamorio_library_path), dynamorio_libname_buf,
BUFFER_SIZE_ELEMENTS(dynamorio_libname_buf));
ASSERT(res > 0);
#ifndef STATIC_LIBRARY
dynamorio_libname = IF_UNIT_TEST_ELSE(UNIT_TEST_EXE_NAME, dynamorio_libname_buf);
#endif /* STATIC_LIBRARY */
snprintf(dynamorio_library_filepath,
BUFFER_SIZE_ELEMENTS(dynamorio_library_filepath), "%s%s",
dynamorio_library_path, dynamorio_libname);
NULL_TERMINATE_BUFFER(dynamorio_library_filepath);
#if !defined(STATIC_LIBRARY) && defined(LINUX)
ASSERT(check_start == dynamo_dll_start && check_end == dynamo_dll_end);
#elif defined(MACOS)
ASSERT(check_start == dynamo_dll_start);
dynamo_dll_end = check_end;
#else
dynamo_dll_start = check_start;
dynamo_dll_end = check_end;
#endif
}
LOG(GLOBAL, LOG_VMAREAS, 1, PRODUCT_NAME " library path: %s\n",
dynamorio_library_path);
LOG(GLOBAL, LOG_VMAREAS, 1, PRODUCT_NAME " library file path: %s\n",
dynamorio_library_filepath);
LOG(GLOBAL, LOG_VMAREAS, 1, "DR library bounds: " PFX " to " PFX "\n",
dynamo_dll_start, dynamo_dll_end);
/* Issue 20: we need the path to the alt arch */
strncpy(dynamorio_alt_arch_path, dynamorio_library_path,
BUFFER_SIZE_ELEMENTS(dynamorio_alt_arch_path));
/* Assumption: libdir name is not repeated elsewhere in path */
libdir = strstr(dynamorio_alt_arch_path, IF_X64_ELSE(DR_LIBDIR_X64, DR_LIBDIR_X86));
if (libdir != NULL) {
const char *newdir = IF_X64_ELSE(DR_LIBDIR_X86, DR_LIBDIR_X64);
/* do NOT place the NULL */
strncpy(libdir, newdir, strlen(newdir));
} else {
SYSLOG_INTERNAL_WARNING("unable to determine lib path for cross-arch execve");
}
NULL_TERMINATE_BUFFER(dynamorio_alt_arch_path);
LOG(GLOBAL, LOG_VMAREAS, 1, PRODUCT_NAME " alt arch path: %s\n",
dynamorio_alt_arch_path);
snprintf(dynamorio_alt_arch_filepath,
BUFFER_SIZE_ELEMENTS(dynamorio_alt_arch_filepath), "%s%s",
dynamorio_alt_arch_path, dynamorio_libname);
NULL_TERMINATE_BUFFER(dynamorio_alt_arch_filepath);
if (dynamo_dll_start == NULL || dynamo_dll_end == NULL) {
REPORT_FATAL_ERROR_AND_EXIT(FAILED_TO_FIND_DR_BOUNDS, 2, get_application_name(),
get_application_pid());
}
}
/* get full path to our own library, (cached), used for forking and message file name */
char *
get_dynamorio_library_path(void)
{
if (!dynamorio_library_filepath[0]) { /* not cached */
get_dynamo_library_bounds();
}
return dynamorio_library_filepath;
}
#ifdef LINUX
/* Get full path+name of executable file from /proc/self/exe. Returns an empty
* string on error.
* FIXME i#47: This will return DR's path when using early injection.
*/
static char *
read_proc_self_exe(bool ignore_cache)
{
static char exepath[MAXIMUM_PATH];
static bool tried = false;
# ifdef MACOS
ASSERT_NOT_IMPLEMENTED(false);
# endif
if (!tried || ignore_cache) {
tried = true;
/* assume we have /proc/self/exe symlink: could add HAVE_PROC_EXE
* but we have no alternative solution except assuming the first
* /proc/self/maps entry is the executable
*/
ssize_t res;
DEBUG_DECLARE(int len =)
snprintf(exepath, BUFFER_SIZE_ELEMENTS(exepath), "/proc/%d/exe",
get_process_id());
ASSERT(len > 0);
NULL_TERMINATE_BUFFER(exepath);
/* i#960: readlink does not null terminate, so we do it. */
# ifdef SYS_readlink
res = dynamorio_syscall(SYS_readlink, 3, exepath, exepath,
BUFFER_SIZE_ELEMENTS(exepath) - 1);
# else
res = dynamorio_syscall(SYS_readlinkat, 4, AT_FDCWD, exepath, exepath,
BUFFER_SIZE_ELEMENTS(exepath) - 1);
# endif
ASSERT(res < BUFFER_SIZE_ELEMENTS(exepath));
exepath[MAX(res, 0)] = '\0';
NULL_TERMINATE_BUFFER(exepath);
}
return exepath;
}
#endif /* LINUX */
app_pc
get_application_base(void)
{
if (executable_start == NULL) {
#if defined(STATIC_LIBRARY)
/* When compiled statically, the app and the DR's "library" are the same. */
executable_start = get_dynamorio_dll_start();
executable_end = get_dynamorio_dll_end();
#elif defined(HAVE_MEMINFO)
/* Haven't done find_executable_vm_areas() yet so walk maps ourselves */
const char *name = get_application_name();
if (name != NULL && name[0] != '\0') {
DEBUG_DECLARE(int count =)
memquery_library_bounds(name, &executable_start, &executable_end, NULL, 0,
NULL, 0);
ASSERT(count > 0 && executable_start != NULL);
}
#else
/* We have to fail. Should we dl_iterate this early? */
#endif
}
return executable_start;
}
app_pc
get_application_end(void)
{
if (executable_end == NULL)
get_application_base();
return executable_end;
}
app_pc
get_image_entry()
{
static app_pc image_entry_point = NULL;
if (image_entry_point == NULL && executable_start != NULL) {
module_area_t *ma;
os_get_module_info_lock();
ma = module_pc_lookup(executable_start);
ASSERT(ma != NULL);
if (ma != NULL) {
ASSERT(executable_start == ma->start);
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
image_entry_point = ma->entry_point;
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
}
os_get_module_info_unlock();
}
return image_entry_point;
}
#ifdef DEBUG
void
mem_stats_snapshot()
{
/* FIXME: NYI */
}
#endif
bool
is_in_dynamo_dll(app_pc pc)
{
ASSERT(dynamo_dll_start != NULL);
#ifdef VMX86_SERVER
/* We want to consider vmklib as part of the DR lib for allowing
* execution (_init calls os_in_vmkernel_classic()) and for
* reporting crashes as our fault
*/
if (vmk_in_vmklib(pc))
return true;
#endif
return (pc >= dynamo_dll_start && pc < dynamo_dll_end);
}
app_pc
get_dynamorio_dll_start()
{
if (dynamo_dll_start == NULL)
get_dynamo_library_bounds();
ASSERT(dynamo_dll_start != NULL);
return dynamo_dll_start;
}
app_pc
get_dynamorio_dll_end()
{
if (dynamo_dll_end == NULL)
get_dynamo_library_bounds();
ASSERT(dynamo_dll_end != NULL);
return dynamo_dll_end;
}
app_pc
get_dynamorio_dll_preferred_base()
{
/* on Linux there is no preferred base if we're PIC,
* therefore is always equal to dynamo_dll_start */
return get_dynamorio_dll_start();
}
static void
found_vsyscall_page(memquery_iter_t *iter _IF_DEBUG(OUT const char **map_type))
{
#ifndef X64
/* We assume no vsyscall page for x64; thus, checking the
* hardcoded address shouldn't have any false positives.
*/
ASSERT(iter->vm_end - iter->vm_start == PAGE_SIZE ||
/* i#1583: recent kernels have 2-page vdso */
iter->vm_end - iter->vm_start == 2 * PAGE_SIZE);
ASSERT(!dynamo_initialized); /* .data should be +w */
/* we're not considering as "image" even if part of ld.so (xref i#89) and
* thus we aren't adjusting our code origins policies to remove the
* vsyscall page exemption.
*/
DODEBUG({ *map_type = "VDSO"; });
/* On re-attach, the vdso can be split into two entries (from DR's hook),
* so take just the first one as the start (xref i#2157).
*/
if (vdso_page_start == NULL) {
vdso_page_start = iter->vm_start;
vdso_size = iter->vm_end - iter->vm_start;
}
/* The vsyscall page can be on the 2nd page inside the vdso, but until we
* see a syscall we don't know and we point it at the vdso start.
*/
if (vsyscall_page_start == NULL)
vsyscall_page_start = iter->vm_start;
LOG(GLOBAL, LOG_VMAREAS, 1, "found vdso/vsyscall pages @ " PFX " %s\n",
vsyscall_page_start, iter->comment);
#else
/* i#172
* fix bugs for OS where vdso page is set unreadable as below
* ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vdso]
* but it is readable indeed.
*/
/* i#430
* fix bugs for OS where vdso page is set unreadable as below
* ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vsyscall]
* but it is readable indeed.
*/
if (!TESTALL((PROT_READ | PROT_EXEC), iter->prot))
iter->prot |= (PROT_READ | PROT_EXEC);
/* i#1908: vdso and vsyscall pages are now split */
if (strncmp(iter->comment, VSYSCALL_PAGE_MAPS_NAME,
strlen(VSYSCALL_PAGE_MAPS_NAME)) == 0)
vdso_page_start = iter->vm_start;
else if (strncmp(iter->comment, VSYSCALL_REGION_MAPS_NAME,
strlen(VSYSCALL_REGION_MAPS_NAME)) == 0)
vsyscall_page_start = iter->vm_start;
#endif
}
#ifndef HAVE_MEMINFO_QUERY
static void
add_to_memcache(byte *region_start, byte *region_end, void *user_data)
{
memcache_update_locked(region_start, region_end, MEMPROT_NONE, DR_MEMTYPE_DATA,
false /*!exists*/);
}
#endif
int
os_walk_address_space(memquery_iter_t *iter, bool add_modules)
{
int count = 0;
#ifdef MACOS
app_pc shared_start, shared_end;
bool have_shared = module_dyld_shared_region(&shared_start, &shared_end);
#endif
#ifdef RETURN_AFTER_CALL
dcontext_t *dcontext = get_thread_private_dcontext();
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
#endif
#ifndef HAVE_MEMINFO_QUERY
/* We avoid tracking the innards of vmheap for all_memory_areas by
* adding a single no-access region for the whole vmheap.
* Queries from heap routines use _from_os.
* Queries in check_thread_vm_area are fine getting "noaccess": wants
* any DR memory not on exec areas list to be noaccess.
* Queries from clients: should be ok to hide innards. Marking noaccess
* should be safer than marking free, as unruly client might try to mmap
* something in the free space: better to have it think it's reserved but
* not yet used memory. FIXME: we're not marking beyond-vmheap DR regions
* as noaccess!
*/
iterate_vmm_regions(add_to_memcache, NULL);
#endif
#ifndef HAVE_MEMINFO
count = find_vm_areas_via_probe();
#else
while (memquery_iterator_next(iter)) {
bool image = false;
size_t size = iter->vm_end - iter->vm_start;
/* i#479, hide private module and match Windows's behavior */
bool skip = dynamo_vm_area_overlap(iter->vm_start, iter->vm_end) &&
!is_in_dynamo_dll(iter->vm_start) /* our own text section is ok */
/* client lib text section is ok (xref i#487) */
&& !is_in_client_lib(iter->vm_start);
DEBUG_DECLARE(const char *map_type = "Private");
/* we can't really tell what's a stack and what's not, but we rely on
* our passing NULL preventing rwx regions from being added to executable
* or future list, even w/ -executable_if_alloc
*/
LOG(GLOBAL, LOG_VMAREAS, 2, "start=" PFX " end=" PFX " prot=%x comment=%s\n",
iter->vm_start, iter->vm_end, iter->prot, iter->comment);
/* Issue 89: the vdso might be loaded inside ld.so as below,
* which causes ASSERT_CURIOSITY in mmap_check_for_module_overlap fail.
* b7fa3000-b7fbd000 r-xp 00000000 08:01 108679 /lib/ld-2.8.90.so
* b7fbd000-b7fbe000 r-xp b7fbd000 00:00 0 [vdso]
* b7fbe000-b7fbf000 r--p 0001a000 08:01 108679 /lib/ld-2.8.90.so
* b7fbf000-b7fc0000 rw-p 0001b000 08:01 108679 /lib/ld-2.8.90.so
* So we always first check if it is a vdso page before calling
* mmap_check_for_module_overlap.
* Update: with i#160/PR 562667 handling non-contiguous modules like
* ld.so we now gracefully handle other objects like vdso in gaps in
* module, but it's simpler to leave this ordering here.
*/
if (skip) {
/* i#479, hide private module and match Windows's behavior */
LOG(GLOBAL, LOG_VMAREAS, 2, PFX "-" PFX " skipping: internal DR region\n",
iter->vm_start, iter->vm_end);
# ifdef MACOS
} else if (have_shared && iter->vm_start >= shared_start &&
iter->vm_start < shared_end) {
/* Skip modules we happen to find inside the dyld shared cache,
* as we'll fail to identify the library. We add them
* in module_walk_dyld_list instead.
*/
image = true;
# endif
} else if (strncmp(iter->comment, VSYSCALL_PAGE_MAPS_NAME,
strlen(VSYSCALL_PAGE_MAPS_NAME)) == 0 ||
IF_X64_ELSE(strncmp(iter->comment, VSYSCALL_REGION_MAPS_NAME,
strlen(VSYSCALL_REGION_MAPS_NAME)) == 0,
/* Older kernels do not label it as "[vdso]", but it is
* hardcoded there.
*/
/* 32-bit */
iter->vm_start == VSYSCALL_PAGE_START_HARDCODED)) {
if (add_modules) {
found_vsyscall_page(iter _IF_DEBUG(&map_type));
/* We'd like to add vsyscall to the module list too but when it's
* separate from vdso it has no ELF header which is too complex
* to force into the module list.
*/
if (module_is_header(iter->vm_start, iter->vm_end - iter->vm_start)) {
module_list_add(iter->vm_start, iter->vm_end - iter->vm_start, false,
iter->comment, iter->inode);
}
}
} else if (add_modules &&
mmap_check_for_module_overlap(iter->vm_start, size,
TEST(MEMPROT_READ, iter->prot),
iter->inode, false)) {
/* we already added the whole image region when we hit the first map for it */
image = true;
DODEBUG({ map_type = "ELF SO"; });
} else if (TEST(MEMPROT_READ, iter->prot) &&
module_is_header(iter->vm_start, size)) {
size_t image_size = size;
app_pc mod_base, mod_first_end, mod_max_end;
char *exec_match;
bool found_exec = false;
image = true;
DODEBUG({ map_type = "ELF SO"; });
LOG(GLOBAL, LOG_VMAREAS, 2,
"Found already mapped module first segment :\n"
"\t" PFX "-" PFX "%s inode=" UINT64_FORMAT_STRING " name=%s\n",
iter->vm_start, iter->vm_end, TEST(MEMPROT_EXEC, iter->prot) ? " +x" : "",
iter->inode, iter->comment);
# ifdef LINUX
/* Mapped images should have inodes, except for cases where an anon
* map is placed on top (i#2566)
*/
ASSERT_CURIOSITY(iter->inode != 0 || iter->comment[0] == '\0');
# endif
ASSERT_CURIOSITY(iter->offset == 0); /* first map shouldn't have offset */
/* Get size by walking the program headers. This includes .bss. */
if (module_walk_program_headers(iter->vm_start, size, false,
true, /* i#1589: ld.so relocated .dynamic */
&mod_base, &mod_first_end, &mod_max_end, NULL,
NULL)) {
image_size = mod_max_end - mod_base;
} else {
ASSERT_NOT_REACHED();
}
LOG(GLOBAL, LOG_VMAREAS, 2,
"Found already mapped module total module :\n"
"\t" PFX "-" PFX " inode=" UINT64_FORMAT_STRING " name=%s\n",
iter->vm_start, iter->vm_start + image_size, iter->inode, iter->comment);
if (add_modules) {
const char *modpath = iter->comment;
/* look for executable */
# ifdef LINUX
exec_match = get_application_name();
if (exec_match != NULL && exec_match[0] != '\0')
found_exec = (strcmp(iter->comment, exec_match) == 0);
/* Handle an anon region for the header (i#2566) */
if (!found_exec && executable_start != NULL &&
executable_start == iter->vm_start) {
found_exec = true;
/* The maps file's first entry may not have the path, in the
* presence of mremapping for hugepages (i#2566; i#3387) (this
* could happen for libraries too, but we don't have alternatives
* there). Or, it may have an incorrect path. Prefer the path
* we recorded in early injection or obtained from
* /proc/self/exe.
*/
modpath = get_application_name();
}
# else
/* We don't have a nice normalized name: it can have ./ or ../ inside
* it. But, we can distinguish an exe from a lib here, even for PIE,
* so we go with that plus a basename comparison.
*/
exec_match = (char *)get_application_short_name();
if (module_is_executable(iter->vm_start) && exec_match != NULL &&
exec_match[0] != '\0') {
const char *iter_basename = strrchr(iter->comment, '/');
if (iter_basename == NULL)
iter_basename = iter->comment;
else
iter_basename++;
found_exec = (strcmp(iter_basename, exec_match) == 0);
}
# endif
if (found_exec) {
if (executable_start == NULL)
executable_start = iter->vm_start;
else
ASSERT(iter->vm_start == executable_start);
LOG(GLOBAL, LOG_VMAREAS, 2,
"Found executable %s @" PFX "-" PFX " %s\n",
get_application_name(), iter->vm_start,
iter->vm_start + image_size, iter->comment);
}
/* We don't yet know whether contiguous so we have to settle for the
* first segment's size. We'll update it in module_list_add().
*/
module_list_add(iter->vm_start, mod_first_end - mod_base, false, modpath,
iter->inode);
# ifdef MACOS
/* look for dyld */
if (strcmp(iter->comment, "/usr/lib/dyld") == 0)
module_walk_dyld_list(iter->vm_start);
# endif
}
} else if (iter->inode != 0) {
DODEBUG({ map_type = "Mapped File"; });
}
/* add all regions (incl. dynamo_areas and stack) to all_memory_areas */
# ifndef HAVE_MEMINFO_QUERY
/* Don't add if we're using one single vmheap entry. */
if (!is_vmm_reserved_address(iter->vm_start, iter->vm_end - iter->vm_start, NULL,
NULL)) {
LOG(GLOBAL, LOG_VMAREAS, 4,
"os_walk_address_space: adding: " PFX "-" PFX " prot=%d\n",
iter->vm_start, iter->vm_end, iter->prot);
memcache_update_locked(iter->vm_start, iter->vm_end, iter->prot,
image ? DR_MEMTYPE_IMAGE : DR_MEMTYPE_DATA,
false /*!exists*/);
}
# endif
/* FIXME: best if we could pass every region to vmareas, but
* it has no way of determining if this is a stack b/c we don't have
* a dcontext at this point -- so we just don't pass the stack
*/
if (!skip /* i#479, hide private module and match Windows's behavior */ &&
add_modules &&
app_memory_allocation(NULL, iter->vm_start, (iter->vm_end - iter->vm_start),
iter->prot, image _IF_DEBUG(map_type))) {
count++;
}
}
#endif /* !HAVE_MEMINFO */
#ifndef HAVE_MEMINFO_QUERY
DOLOG(4, LOG_VMAREAS, memcache_print(GLOBAL, "init: all memory areas:\n"););
#endif
#ifdef RETURN_AFTER_CALL
/* Find the bottom of the stack of the initial (native) entry */
ostd->stack_bottom_pc = find_stack_bottom();
LOG(THREAD, LOG_ALL, 1, "Stack bottom pc = " PFX "\n", ostd->stack_bottom_pc);
#endif
/* now that we've walked memory print all modules */
LOG(GLOBAL, LOG_VMAREAS, 2, "Module list after memory walk\n");
DOLOG(1, LOG_VMAREAS, {
if (add_modules)
print_modules(GLOBAL, DUMP_NOT_XML);
});
return count;
}
/* assumed to be called after find_dynamo_library_vm_areas() */
int
find_executable_vm_areas(void)
{
int count;
memquery_iter_t iter;
memquery_iterator_start(&iter, NULL, true /*may alloc*/);
count = os_walk_address_space(&iter, true);
memquery_iterator_stop(&iter);
STATS_ADD(num_app_code_modules, count);
/* now that we have the modules set up, query libc */
get_libc_errno_location(true /*force init*/);
return count;
}
/* initializes dynamorio library bounds.
* does not use any heap.
* assumed to be called prior to find_executable_vm_areas.
*/
int
find_dynamo_library_vm_areas(void)
{
#ifndef STATIC_LIBRARY
/* We didn't add inside get_dynamo_library_bounds b/c it was called pre-alloc.
* We don't bother to break down the sub-regions.
* Assumption: we don't need to have the protection flags for DR sub-regions.
* For static library builds, DR's code is in the exe and isn't considered
* to be a DR area.
*/
add_dynamo_vm_area(get_dynamorio_dll_start(), get_dynamorio_dll_end(),
MEMPROT_READ | MEMPROT_WRITE | MEMPROT_EXEC,
true /* from image */ _IF_DEBUG(dynamorio_library_filepath));
#endif
#ifdef VMX86_SERVER
if (os_in_vmkernel_userworld())
vmk_add_vmklib_to_dynamo_areas();
#endif
return 1;
}
bool
get_stack_bounds(dcontext_t *dcontext, byte **base, byte **top)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
if (ostd->stack_base == NULL) {
/* initialize on-demand since don't have app esp handy in os_thread_init()
* FIXME: the comment here -- ignoring it for now, if hit cases confirming
* it the right thing will be to merge adjacent rwx regions and assume
* their union is the stack -- otherwise have to have special stack init
* routine called from x86.asm new_thread_dynamo_start and internal_dynamo_start,
* and the latter is not a do-once...
*/
size_t size = 0;
bool ok;
/* store stack info at thread startup, since stack can get fragmented in
* /proc/self/maps w/ later mprotects and it can be hard to piece together later
*/
if (IF_MEMQUERY_ELSE(false, DYNAMO_OPTION(use_all_memory_areas))) {
ok = get_memory_info((app_pc)get_mcontext(dcontext)->xsp, &ostd->stack_base,
&size, NULL);
} else {
ok = get_memory_info_from_os((app_pc)get_mcontext(dcontext)->xsp,
&ostd->stack_base, &size, NULL);
}
if (!ok) {
/* This can happen with dr_prepopulate_cache() before we start running
* the app.
*/
ASSERT(!dynamo_started);
return false;
}
ostd->stack_top = ostd->stack_base + size;
LOG(THREAD, LOG_THREADS, 1, "App stack is " PFX "-" PFX "\n", ostd->stack_base,
ostd->stack_top);
}
if (base != NULL)
*base = ostd->stack_base;
if (top != NULL)
*top = ostd->stack_top;
return true;
}
#ifdef RETURN_AFTER_CALL
initial_call_stack_status_t
at_initial_stack_bottom(dcontext_t *dcontext, app_pc target_pc)
{
/* We can't rely exclusively on finding the true stack bottom
* b/c we can't always walk the call stack (PR 608990) so we
* use the image entry as our primary trigger
*/
if (executable_start != NULL /*defensive*/ && reached_image_entry_yet()) {
return INITIAL_STACK_EMPTY;
} else {
/* If our stack walk ends early we could have false positives, but
* that's better than false negatives if we miss the image entry
* or we were unable to find the executable_start
*/
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
if (target_pc == ostd->stack_bottom_pc) {
return INITIAL_STACK_BOTTOM_REACHED;
} else {
return INITIAL_STACK_BOTTOM_NOT_REACHED;
}
}
}
#endif /* RETURN_AFTER_CALL */
/* Uses our cached data structures (if in use, else raw query) to retrieve memory info */
bool
query_memory_ex(const byte *pc, OUT dr_mem_info_t *out_info)
{
#ifdef HAVE_MEMINFO_QUERY
return query_memory_ex_from_os(pc, out_info);
#else
return memcache_query_memory(pc, out_info);
#endif
}
bool
query_memory_cur_base(const byte *pc, OUT dr_mem_info_t *info)
{
return query_memory_ex(pc, info);
}
/* Use our cached data structures (if in use, else raw query) to retrieve memory info */
bool
get_memory_info(const byte *pc, byte **base_pc, size_t *size,
uint *prot /* OUT optional, returns MEMPROT_* value */)
{
dr_mem_info_t info;
if (is_vmm_reserved_address((byte *)pc, 1, NULL, NULL)) {
if (!query_memory_ex_from_os(pc, &info) || info.type == DR_MEMTYPE_FREE)
return false;
} else {
if (!query_memory_ex(pc, &info) || info.type == DR_MEMTYPE_FREE)
return false;
}
if (base_pc != NULL)
*base_pc = info.base_pc;
if (size != NULL)
*size = info.size;
if (prot != NULL)
*prot = info.prot;
return true;
}
/* We assume that this routine might be called instead of query_memory_ex()
* b/c the caller is in a fragile location and cannot acquire locks, so
* we try to do the same here.
*/
bool
query_memory_ex_from_os(const byte *pc, OUT dr_mem_info_t *info)
{
bool have_type = false;
bool res = memquery_from_os(pc, info, &have_type);
if (!res) {
/* No other failure types for now */
info->type = DR_MEMTYPE_ERROR;
} else if (res && !have_type) {
/* We pass 0 instead of info->size b/c even if marked as +r we can still
* get SIGBUS if beyond end of mmapped file: not uncommon if querying
* in middle of library load before .bss fully set up (PR 528744).
* However, if there is no fault handler, is_elf_so_header's safe_read will
* recurse to here, so in that case we use info->size but we assume
* it's only at init or exit and so not in the middle of a load
* and less likely to be querying a random mmapped file.
* The cleaner fix is to allow safe_read to work w/o a dcontext or
* fault handling: i#350/PR 529066.
*/
if (TEST(MEMPROT_READ, info->prot) &&
module_is_header(info->base_pc, fault_handling_initialized ? 0 : info->size))
info->type = DR_MEMTYPE_IMAGE;
else {
/* FIXME: won't quite match find_executable_vm_areas marking as
* image: can be doubly-mapped so; don't want to count vdso; etc.
*/
info->type = DR_MEMTYPE_DATA;
}
}
return res;
}
bool
get_memory_info_from_os(const byte *pc, byte **base_pc, size_t *size,
uint *prot /* OUT optional, returns MEMPROT_* value */)
{
dr_mem_info_t info;
if (!query_memory_ex_from_os(pc, &info) || info.type == DR_MEMTYPE_FREE)
return false;
if (base_pc != NULL)
*base_pc = info.base_pc;
if (size != NULL)
*size = info.size;
if (prot != NULL)
*prot = info.prot;
return true;
}
/* in utils.c, exported only for our hack! */
extern void
deadlock_avoidance_unlock(mutex_t *lock, bool ownable);
void
mutex_wait_contended_lock(mutex_t *lock, priv_mcontext_t *mc)
{
dcontext_t *dcontext = get_thread_private_dcontext();
bool set_client_safe_for_synch =
((dcontext != NULL) && IS_CLIENT_THREAD(dcontext) &&
((mutex_t *)dcontext->client_data->client_grab_mutex == lock));
if (mc != NULL) {
ASSERT(dcontext != NULL);
/* set_safe_for_sync can't be true at the same time as passing
* an mcontext to return into: nothing would be able to reset the
* client_thread_safe_for_sync flag.
*/
ASSERT(!set_client_safe_for_synch);
*get_mcontext(dcontext) = *mc;
}
/* i#96/PR 295561: use futex(2) if available */
if (ksynch_kernel_support()) {
/* Try to get the lock. If already held, it's fine to store any value
* > LOCK_SET_STATE (we don't rely on paired incs/decs) so that
* the next unlocker will call mutex_notify_released_lock().
*/
ptr_int_t res;
#ifndef LINUX /* we actually don't use this for Linux: see below */
KSYNCH_TYPE *event = mutex_get_contended_event(lock);
ASSERT(event != NULL && ksynch_var_initialized(event));
#endif
while (atomic_exchange_int(&lock->lock_requests, LOCK_CONTENDED_STATE) !=
LOCK_FREE_STATE) {
if (set_client_safe_for_synch)
dcontext->client_data->client_thread_safe_for_synch = true;
if (mc != NULL)
set_synch_state(dcontext, THREAD_SYNCH_VALID_MCONTEXT);
/* Unfortunately the synch semantics are different for Linux vs Mac.
* We have to use lock_requests as the futex to avoid waiting if
* lock_requests changes, while on Mac the underlying synch prevents
* a wait there.
*/
#ifdef LINUX
/* We'll abort the wait if lock_requests has changed at all.
* We can't have a series of changes that result in no apparent
* change w/o someone acquiring the lock, b/c
* mutex_notify_released_lock() sets lock_requests to LOCK_FREE_STATE.
*/
res = ksynch_wait(&lock->lock_requests, LOCK_CONTENDED_STATE, 0);
#else
res = ksynch_wait(event, 0, 0);
#endif
if (res != 0 && res != -EWOULDBLOCK)
os_thread_yield();
if (set_client_safe_for_synch)
dcontext->client_data->client_thread_safe_for_synch = false;
if (mc != NULL)
set_synch_state(dcontext, THREAD_SYNCH_NONE);
/* we don't care whether properly woken (res==0), var mismatch
* (res==-EWOULDBLOCK), or error: regardless, someone else
* could have acquired the lock, so we try again
*/
}
} else {
/* we now have to undo our earlier request */
atomic_dec_and_test(&lock->lock_requests);
while (!d_r_mutex_trylock(lock)) {
if (set_client_safe_for_synch)
dcontext->client_data->client_thread_safe_for_synch = true;
if (mc != NULL)
set_synch_state(dcontext, THREAD_SYNCH_VALID_MCONTEXT);
os_thread_yield();
if (set_client_safe_for_synch)
dcontext->client_data->client_thread_safe_for_synch = false;
if (mc != NULL)
set_synch_state(dcontext, THREAD_SYNCH_NONE);
}
#ifdef DEADLOCK_AVOIDANCE
/* HACK: trylock's success causes it to do DEADLOCK_AVOIDANCE_LOCK, so to
* avoid two in a row (causes assertion on owner) we unlock here
* In the future we will remove the trylock here and this will go away.
*/
deadlock_avoidance_unlock(lock, true);
#endif
}
return;
}
void
mutex_notify_released_lock(mutex_t *lock)
{
/* i#96/PR 295561: use futex(2) if available. */
if (ksynch_kernel_support()) {
/* Set to LOCK_FREE_STATE to avoid concurrent lock attempts from
* resulting in a futex_wait value match w/o anyone owning the lock
*/
lock->lock_requests = LOCK_FREE_STATE;
/* No reason to wake multiple threads: just one */
#ifdef LINUX
ksynch_wake(&lock->lock_requests);
#else
ksynch_wake(&lock->contended_event);
#endif
} /* else nothing to do */
}
/* read_write_lock_t implementation doesn't expect the contention path
helpers to guarantee the lock is held (unlike mutexes) so simple
yields are still acceptable.
*/
void
rwlock_wait_contended_writer(read_write_lock_t *rwlock)
{
os_thread_yield();
}
void
rwlock_notify_writer(read_write_lock_t *rwlock)
{
/* nothing to do here */
}
void
rwlock_wait_contended_reader(read_write_lock_t *rwlock)
{
os_thread_yield();
}
void
rwlock_notify_readers(read_write_lock_t *rwlock)
{
/* nothing to do here */
}
/***************************************************************************/
/* events are un-signaled when successfully waited upon. */
typedef struct linux_event_t {
/* Any function that sets this flag must also notify possibly waiting
* thread(s). See i#96/PR 295561.
*/
KSYNCH_TYPE signaled;
mutex_t lock;
bool broadcast;
} linux_event_t;
/* FIXME: this routine will need to have a macro wrapper to let us
* assign different ranks to all events for DEADLOCK_AVOIDANCE.
* Currently a single rank seems to work.
*/
event_t
create_event(void)
{
event_t e = (event_t)global_heap_alloc(sizeof(linux_event_t) HEAPACCT(ACCT_OTHER));
ksynch_init_var(&e->signaled);
ASSIGN_INIT_LOCK_FREE(e->lock, event_lock); /* FIXME: pass the event name here */
e->broadcast = false;
return e;
}
event_t
create_broadcast_event(void)
{
event_t e = create_event();
e->broadcast = true;
return e;
}
void
destroy_event(event_t e)
{
DELETE_LOCK(e->lock);
ksynch_free_var(&e->signaled);
global_heap_free(e, sizeof(linux_event_t) HEAPACCT(ACCT_OTHER));
}
void
signal_event(event_t e)
{
d_r_mutex_lock(&e->lock);
ksynch_set_value(&e->signaled, 1);
if (e->broadcast)
ksynch_wake_all(&e->signaled);
else
ksynch_wake(&e->signaled);
LOG(THREAD_GET, LOG_THREADS, 3, "thread " TIDFMT " signalling event " PFX "\n",
d_r_get_thread_id(), e);
d_r_mutex_unlock(&e->lock);
}
void
reset_event(event_t e)
{
d_r_mutex_lock(&e->lock);
ksynch_set_value(&e->signaled, 0);
LOG(THREAD_GET, LOG_THREADS, 3, "thread " TIDFMT " resetting event " PFX "\n",
d_r_get_thread_id(), e);
d_r_mutex_unlock(&e->lock);
}
bool
wait_for_event(event_t e, int timeout_ms)
{
#ifdef DEBUG
dcontext_t *dcontext = get_thread_private_dcontext();
#endif
uint64 start_time, cur_time;
if (timeout_ms > 0)
start_time = query_time_millis();
/* Use a user-space event on Linux, a kernel event on Windows. */
LOG(THREAD, LOG_THREADS, 3, "thread " TIDFMT " waiting for event " PFX "\n",
d_r_get_thread_id(), e);
do {
if (ksynch_get_value(&e->signaled) == 1) {
d_r_mutex_lock(&e->lock);
if (ksynch_get_value(&e->signaled) == 0) {
/* some other thread beat us to it */
LOG(THREAD, LOG_THREADS, 3,
"thread " TIDFMT " was beaten to event " PFX "\n",
d_r_get_thread_id(), e);
d_r_mutex_unlock(&e->lock);
} else {
if (!e->broadcast) {
/* reset the event */
ksynch_set_value(&e->signaled, 0);
}
d_r_mutex_unlock(&e->lock);
LOG(THREAD, LOG_THREADS, 3,
"thread " TIDFMT " finished waiting for event " PFX "\n",
d_r_get_thread_id(), e);
return true;
}
} else {
/* Waits only if the signaled flag is not set as 1. Return value
* doesn't matter because the flag will be re-checked.
*/
ksynch_wait(&e->signaled, 0, timeout_ms);
}
if (ksynch_get_value(&e->signaled) == 0) {
/* If it still has to wait, give up the cpu. */
os_thread_yield();
}
if (timeout_ms > 0)
cur_time = query_time_millis();
} while (timeout_ms <= 0 || cur_time - start_time < timeout_ms);
return false;
}
/***************************************************************************
* DIRECTORY ITERATOR
*/
/* These structs are written to the buf that we pass to getdents. We can
* iterate them by adding d_reclen to the current buffer offset and interpreting
* that as the next entry.
*/
struct linux_dirent {
#ifdef SYS_getdents
/* Adapted from struct old_linux_dirent in linux/fs/readdir.c: */
unsigned long d_ino;
unsigned long d_off;
unsigned short d_reclen;
char d_name[];
#else
/* Adapted from struct linux_dirent64 in linux/include/linux/dirent.h: */
uint64 d_ino;
int64 d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[];
#endif
};
#define CURRENT_DIRENT(iter) ((struct linux_dirent *)(&iter->buf[iter->off]))
static void
os_dir_iterator_start(dir_iterator_t *iter, file_t fd)
{
iter->fd = fd;
iter->off = 0;
iter->end = 0;
}
static bool
os_dir_iterator_next(dir_iterator_t *iter)
{
#ifdef MACOS
/* We can use SYS_getdirentries, but do we even need a dir iterator?
* On Linux it's only used to enumerate /proc/pid/task.
*/
ASSERT_NOT_IMPLEMENTED(false);
return false;
#else
if (iter->off < iter->end) {
/* Have existing dents, get the next offset. */
iter->off += CURRENT_DIRENT(iter)->d_reclen;
ASSERT(iter->off <= iter->end);
}
if (iter->off == iter->end) {
/* Do a getdents syscall. Unlike when reading a file, the kernel will
* not read a partial linux_dirent struct, so we don't need to shift the
* left over bytes to the buffer start. See the getdents manpage for
* the example code that this is based on.
*/
iter->off = 0;
# ifdef SYS_getdents
iter->end =
dynamorio_syscall(SYS_getdents, 3, iter->fd, iter->buf, sizeof(iter->buf));
# else
iter->end =
dynamorio_syscall(SYS_getdents64, 3, iter->fd, iter->buf, sizeof(iter->buf));
# endif
ASSERT(iter->end <= sizeof(iter->buf));
if (iter->end <= 0) { /* No more dents, or error. */
iter->name = NULL;
if (iter->end < 0) {
LOG(GLOBAL, LOG_SYSCALLS, 1, "getdents syscall failed with errno %d\n",
-iter->end);
}
return false;
}
}
iter->name = CURRENT_DIRENT(iter)->d_name;
return true;
#endif
}
/***************************************************************************
* THREAD TAKEOVER
*/
/* Record used to synchronize thread takeover. */
typedef struct _takeover_record_t {
thread_id_t tid;
event_t event;
} takeover_record_t;
/* When attempting thread takeover, we store an array of thread id and event
* pairs here. Each thread we signal is supposed to enter DR control and signal
* this event after it has added itself to all_threads.
*
* XXX: What we really want is to be able to use SYS_rt_tgsigqueueinfo (Linux >=
* 2.6.31) to pass the event_t to each thread directly, rather than using this
* side data structure.
*/
static takeover_record_t *thread_takeover_records;
static uint num_thread_takeover_records;
/* This is the dcontext of the thread that initiated the takeover. We read the
* owning_thread and signal_field threads from it in the signaled threads to
* set up siginfo sharing.
*/
static dcontext_t *takeover_dcontext;
/* Lists active threads in the process.
* XXX: The /proc man page says /proc/pid/task is only available if the main
* thread is still alive, but experiments on 2.6.38 show otherwise.
*/
static thread_id_t *
os_list_threads(dcontext_t *dcontext, uint *num_threads_out)
{
dir_iterator_t iter;
file_t task_dir;
uint tids_alloced = 10;
uint num_threads = 0;
thread_id_t *new_tids;
thread_id_t *tids;
ASSERT(num_threads_out != NULL);
#ifdef MACOS
/* XXX i#58: NYI.
* We may want SYS_proc_info with PROC_INFO_PID_INFO and PROC_PIDLISTTHREADS,
* or is that just BSD threads and instead we want process_set_tasks()
* and task_info() as in 7.3.1.3 in Singh's OSX book?
*/
*num_threads_out = 0;
return NULL;
#endif
tids =
HEAP_ARRAY_ALLOC(dcontext, thread_id_t, tids_alloced, ACCT_THREAD_MGT, PROTECTED);
task_dir = os_open_directory("/proc/self/task", OS_OPEN_READ);
ASSERT(task_dir != INVALID_FILE);
os_dir_iterator_start(&iter, task_dir);
while (os_dir_iterator_next(&iter)) {
thread_id_t tid;
DEBUG_DECLARE(int r;)
if (strcmp(iter.name, ".") == 0 || strcmp(iter.name, "..") == 0)
continue;
IF_DEBUG(r =)
sscanf(iter.name, "%u", &tid);
ASSERT_MESSAGE(CHKLVL_ASSERTS, "failed to parse /proc/pid/task entry", r == 1);
if (tid <= 0)
continue;
if (num_threads == tids_alloced) {
/* realloc, essentially. Less expensive than counting first. */
new_tids = HEAP_ARRAY_ALLOC(dcontext, thread_id_t, tids_alloced * 2,
ACCT_THREAD_MGT, PROTECTED);
memcpy(new_tids, tids, sizeof(thread_id_t) * tids_alloced);
HEAP_ARRAY_FREE(dcontext, tids, thread_id_t, tids_alloced, ACCT_THREAD_MGT,
PROTECTED);
tids = new_tids;
tids_alloced *= 2;
}
tids[num_threads++] = tid;
}
ASSERT(iter.end == 0); /* No reading errors. */
os_close(task_dir);
/* realloc back down to num_threads for caller simplicity. */
new_tids =
HEAP_ARRAY_ALLOC(dcontext, thread_id_t, num_threads, ACCT_THREAD_MGT, PROTECTED);
memcpy(new_tids, tids, sizeof(thread_id_t) * num_threads);
HEAP_ARRAY_FREE(dcontext, tids, thread_id_t, tids_alloced, ACCT_THREAD_MGT,
PROTECTED);
tids = new_tids;
*num_threads_out = num_threads;
return tids;
}
/* List the /proc/self/task directory and add all unknown thread ids to the
* all_threads hashtable in dynamo.c. Returns true if we found any unknown
* threads and false otherwise. We assume that since we don't know about them
* they are not under DR and have no dcontexts.
*/
bool
os_take_over_all_unknown_threads(dcontext_t *dcontext)
{
uint i;
uint num_threads;
thread_id_t *tids;
uint threads_to_signal = 0, threads_timed_out = 0;
/* We do not want to re-takeover a thread that's in between notifying us on
* the last call to this routine and getting onto the all_threads list as
* we'll self-interpret our own code leading to a lot of problems.
* XXX: should we use an event to avoid this inefficient loop? We expect
* this to only happen in rare cases during attach when threads are in flux.
*/
while (uninit_thread_count > 0) /* relying on volatile */
os_thread_yield();
/* This can only happen if we had already taken over a thread, because there is
* full synchronization at detach. The same thread may now already be on its way
* to exit, and its thread record might be gone already and make it look like a
* new native thread below. If we rely on the thread to self-detect that it was
* interrupted at a DR address we may run into a deadlock (i#2694). In order to
* avoid this, we wait here. This is expected to be uncommon, and can only happen
* with very short-lived threads.
* XXX: if this loop turns out to be too inefficient, we could support detecting
* the lock function's address bounds along w/ is_dynamo_address.
*/
while (exiting_thread_count > 0)
os_thread_yield();
d_r_mutex_lock(&thread_initexit_lock);
CLIENT_ASSERT(thread_takeover_records == NULL,
"Only one thread should attempt app take over!");
#ifdef LINUX
/* Check this thread for rseq in between setup and start. */
if (rseq_is_registered_for_current_thread())
rseq_locate_rseq_regions();
#endif
/* Find tids for which we have no thread record, meaning they are not under
* our control. Shift them to the beginning of the tids array.
*/
tids = os_list_threads(dcontext, &num_threads);
if (tids == NULL) {
d_r_mutex_unlock(&thread_initexit_lock);
return false; /* have to assume no unknown */
}
for (i = 0; i < num_threads; i++) {
thread_record_t *tr = thread_lookup(tids[i]);
if (tr == NULL ||
/* Re-takeover known threads that are currently native as well.
* XXX i#95: we need a synchall-style loop for known threads as
* they can be in DR for syscall hook handling.
* Update: we now remove the hook for start/stop: but native_exec
* or other individual threads going native could still hit this.
*/
(is_thread_currently_native(tr) && !IS_CLIENT_THREAD(tr->dcontext)))
tids[threads_to_signal++] = tids[i];
}
LOG(GLOBAL, LOG_THREADS, 1, "TAKEOVER: %d threads to take over\n", threads_to_signal);
if (threads_to_signal > 0) {
takeover_record_t *records;
/* Assuming pthreads, prepare signal_field for sharing. */
handle_clone(dcontext, PTHREAD_CLONE_FLAGS);
/* Create records with events for all the threads we want to signal. */
LOG(GLOBAL, LOG_THREADS, 1, "TAKEOVER: publishing takeover records\n");
records = HEAP_ARRAY_ALLOC(dcontext, takeover_record_t, threads_to_signal,
ACCT_THREAD_MGT, PROTECTED);
for (i = 0; i < threads_to_signal; i++) {
LOG(GLOBAL, LOG_THREADS, 1, "TAKEOVER: will signal thread " TIDFMT "\n",
tids[i]);
records[i].tid = tids[i];
records[i].event = create_event();
}
/* Publish the records and the initial take over dcontext. */
thread_takeover_records = records;
num_thread_takeover_records = threads_to_signal;
takeover_dcontext = dcontext;
/* Signal the other threads. */
for (i = 0; i < threads_to_signal; i++) {
thread_signal(get_process_id(), records[i].tid, SUSPEND_SIGNAL);
}
d_r_mutex_unlock(&thread_initexit_lock);
/* Wait for all the threads we signaled. */
ASSERT_OWN_NO_LOCKS();
for (i = 0; i < threads_to_signal; i++) {
static const int progress_period = 50;
if (i % progress_period == 0) {
char buf[16];
/* +1 to include the attach request thread to match the final msg. */
snprintf(buf, BUFFER_SIZE_ELEMENTS(buf), "%d/%d", i + 1,
threads_to_signal + 1);
NULL_TERMINATE_BUFFER(buf);
SYSLOG(SYSLOG_VERBOSE, INFO_ATTACHED, 3, buf, get_application_name(),
get_application_pid());
}
/* We split the wait up so that we'll break early on an exited thread. */
static const int wait_ms = 25;
int max_attempts =
/* Integer division rounding down is fine since we always wait 25ms. */
DYNAMO_OPTION(takeover_timeout_ms) / wait_ms;
int attempts = 0;
while (!wait_for_event(records[i].event, wait_ms)) {
/* The thread may have exited (i#2601). We assume no tid re-use. */
char task[64];
snprintf(task, BUFFER_SIZE_ELEMENTS(task), "/proc/self/task/%d", tids[i]);
NULL_TERMINATE_BUFFER(task);
if (!os_file_exists(task, false /*!is dir*/)) {
SYSLOG_INTERNAL_WARNING_ONCE("thread exited while attaching");
break;
}
if (++attempts > max_attempts) {
if (DYNAMO_OPTION(unsafe_ignore_takeover_timeout)) {
SYSLOG(
SYSLOG_VERBOSE, THREAD_TAKEOVER_TIMED_OUT, 3,
get_application_name(), get_application_pid(),
"Continuing since -unsafe_ignore_takeover_timeout is set.");
++threads_timed_out;
} else {
SYSLOG(
SYSLOG_VERBOSE, THREAD_TAKEOVER_TIMED_OUT, 3,
get_application_name(), get_application_pid(),
"Aborting. Use -unsafe_ignore_takeover_timeout to ignore.");
REPORT_FATAL_ERROR_AND_EXIT(FAILED_TO_TAKE_OVER_THREADS, 2,
get_application_name(),
get_application_pid());
}
break;
}
/* Else try again. */
}
}
/* Now that we've taken over the other threads, we can safely free the
* records and reset the shared globals.
*/
d_r_mutex_lock(&thread_initexit_lock);
LOG(GLOBAL, LOG_THREADS, 1,
"TAKEOVER: takeover complete, unpublishing records\n");
thread_takeover_records = NULL;
num_thread_takeover_records = 0;
takeover_dcontext = NULL;
for (i = 0; i < threads_to_signal; i++) {
destroy_event(records[i].event);
}
HEAP_ARRAY_FREE(dcontext, records, takeover_record_t, threads_to_signal,
ACCT_THREAD_MGT, PROTECTED);
}
d_r_mutex_unlock(&thread_initexit_lock);
HEAP_ARRAY_FREE(dcontext, tids, thread_id_t, num_threads, ACCT_THREAD_MGT, PROTECTED);
ASSERT(threads_to_signal >= threads_timed_out);
return (threads_to_signal - threads_timed_out) > 0;
}
bool
os_thread_re_take_over(void)
{
#ifdef X86
/* i#2089: is_thread_initialized() will fail for a currently-native app.
* We bypass the magic field checks here of is_thread_tls_initialized().
* XXX: should this be inside is_thread_initialized()? But that may mislead
* other callers: the caller has to restore the TLs. Some old code also
* used get_thread_private_dcontext() being NULL to indicate an unknown thread:
* that should also call here.
*/
if (!is_thread_initialized() && is_thread_tls_allocated()) {
/* It's safe to call thread_lookup() for ourself. */
thread_record_t *tr = thread_lookup(get_sys_thread_id());
if (tr != NULL) {
ASSERT(is_thread_currently_native(tr));
LOG(GLOBAL, LOG_THREADS, 1, "\tretakeover for cur-native thread " TIDFMT "\n",
get_sys_thread_id());
LOG(tr->dcontext->logfile, LOG_THREADS, 1,
"\nretakeover for cur-native thread " TIDFMT "\n", get_sys_thread_id());
os_swap_dr_tls(tr->dcontext, false /*to dr*/);
ASSERT(is_thread_initialized());
return true;
}
}
#endif
return false;
}
static void
os_thread_signal_taken_over(void)
{
thread_id_t mytid;
event_t event = NULL;
uint i;
/* Wake up the thread that initiated the take over. */
mytid = d_r_get_thread_id();
ASSERT(thread_takeover_records != NULL);
for (i = 0; i < num_thread_takeover_records; i++) {
if (thread_takeover_records[i].tid == mytid) {
event = thread_takeover_records[i].event;
break;
}
}
ASSERT_MESSAGE(CHKLVL_ASSERTS, "mytid not present in takeover records!",
event != NULL);
signal_event(event);
}
/* Takes over the current thread from the signal handler. We notify the thread
* that signaled us by signalling our event in thread_takeover_records.
* If it returns, it returns false, and the thread should be let go.
*/
bool
os_thread_take_over(priv_mcontext_t *mc, kernel_sigset_t *sigset)
{
dcontext_t *dcontext;
priv_mcontext_t *dc_mc;
LOG(GLOBAL, LOG_THREADS, 1, "TAKEOVER: received signal in thread " TIDFMT "\n",
get_sys_thread_id());
/* Do standard DR thread initialization. Mirrors code in
* create_clone_record and new_thread_setup, except we're not putting a
* clone record on the dstack.
*/
os_thread_re_take_over();
if (!is_thread_initialized()) {
/* If this is a thread on its way to init, don't self-interp (i#2688). */
if (is_dynamo_address(mc->pc)) {
os_thread_signal_taken_over();
return false;
}
dcontext = init_thread_with_shared_siginfo(mc, takeover_dcontext);
ASSERT(dcontext != NULL);
} else {
/* Re-takeover a thread that we let go native */
dcontext = get_thread_private_dcontext();
ASSERT(dcontext != NULL);
}
signal_set_mask(dcontext, sigset);
signal_swap_mask(dcontext, true /*to app*/);
dynamo_thread_under_dynamo(dcontext);
dc_mc = get_mcontext(dcontext);
*dc_mc = *mc;
dcontext->whereami = DR_WHERE_APP;
dcontext->next_tag = mc->pc;
os_thread_signal_taken_over();
DOLOG(2, LOG_TOP, {
byte *cur_esp;
GET_STACK_PTR(cur_esp);
LOG(THREAD, LOG_TOP, 2,
"%s: next_tag=" PFX ", cur xsp=" PFX ", mc->xsp=" PFX "\n", __FUNCTION__,
dcontext->next_tag, cur_esp, mc->xsp);
});
#ifdef LINUX
/* See whether we should initiate lazy rseq handling, and avoid treating
* regions as rseq when the rseq syscall is never set up.
*/
if (rseq_is_registered_for_current_thread()) {
rseq_locate_rseq_regions();
rseq_thread_attach(dcontext);
}
#endif
/* Start interpreting from the signal context. */
call_switch_stack(dcontext, dcontext->dstack, (void (*)(void *))d_r_dispatch,
NULL /*not on d_r_initstack*/, false /*shouldn't return*/);
ASSERT_NOT_REACHED();
return true; /* make compiler happy */
}
bool
os_thread_take_over_suspended_native(dcontext_t *dcontext)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
if (!is_thread_currently_native(dcontext->thread_record) ||
ksynch_get_value(&ostd->suspended) < 0)
return false;
/* Thread is sitting in suspend signal loop so we just set a flag
* for when it resumes:
*/
/* XXX: there's no event for a client to trigger this on so not yet
* tested. i#721 may help.
*/
ASSERT_NOT_TESTED();
ostd->retakeover = true;
return true;
}
/* Called for os-specific takeover of a secondary thread from the one
* that called dr_app_setup().
*/
dcontext_t *
os_thread_take_over_secondary(priv_mcontext_t *mc)
{
thread_record_t **list;
int num_threads;
int i;
dcontext_t *dcontext;
/* We want to share with the thread that called dr_app_setup. */
d_r_mutex_lock(&thread_initexit_lock);
get_list_of_threads(&list, &num_threads);
ASSERT(num_threads >= 1);
for (i = 0; i < num_threads; i++) {
/* Find a thread that's already set up */
if (is_thread_signal_info_initialized(list[i]->dcontext))
break;
}
ASSERT(i < num_threads);
ASSERT(list[i]->id != get_sys_thread_id());
/* Assuming pthreads, prepare signal_field for sharing. */
handle_clone(list[i]->dcontext, PTHREAD_CLONE_FLAGS);
dcontext = init_thread_with_shared_siginfo(mc, list[i]->dcontext);
d_r_mutex_unlock(&thread_initexit_lock);
global_heap_free(list,
num_threads * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT));
return dcontext;
}
/***************************************************************************/
uint
os_random_seed(void)
{
uint seed;
/* reading from /dev/urandom for a non-blocking random */
int urand = os_open("/dev/urandom", OS_OPEN_READ);
DEBUG_DECLARE(int read =) os_read(urand, &seed, sizeof(seed));
ASSERT(read == sizeof(seed));
os_close(urand);
return seed;
}
#ifdef RCT_IND_BRANCH
/* Analyze a range in a possibly new module
* return false if not a code section in a module
* otherwise returns true and adds all valid targets for rct_ind_branch_check
*/
bool
rct_analyze_module_at_violation(dcontext_t *dcontext, app_pc target_pc)
{
/* FIXME: note that this will NOT find the data section corresponding to the given PC
* we don't yet have a corresponding get_allocation_size or an ELF header walk routine
* on linux
*/
app_pc code_start;
size_t code_size;
uint prot;
if (!get_memory_info(target_pc, &code_start, &code_size, &prot))
return false;
/* TODO: in almost all cases expect the region at module_base+module_size to be
* the corresponding data section.
* Writable yet initialized data indeed needs to be processed.
*/
if (code_size > 0) {
app_pc code_end = code_start + code_size;
app_pc data_start;
size_t data_size;
ASSERT(TESTALL(MEMPROT_READ | MEMPROT_EXEC, prot)); /* code */
if (!get_memory_info(code_end, &data_start, &data_size, &prot))
return false;
ASSERT(data_start == code_end);
ASSERT(TESTALL(MEMPROT_READ | MEMPROT_WRITE, prot)); /* data */
app_pc text_start = code_start;
app_pc text_end = data_start + data_size;
/* TODO: performance: do this only in case relocation info is not present */
DEBUG_DECLARE(uint found =)
find_address_references(dcontext, text_start, text_end, code_start, code_end);
LOG(GLOBAL, LOG_RCT, 2, PFX "-" PFX " : %d ind targets of %d code size",
text_start, text_end, found, code_size);
return true;
}
return false;
}
# ifdef X64
bool
rct_add_rip_rel_addr(dcontext_t *dcontext, app_pc tgt _IF_DEBUG(app_pc src))
{
/* FIXME PR 276762: not implemented */
return false;
}
# endif
#endif /* RCT_IND_BRANCH */
#ifdef HOT_PATCHING_INTERFACE
void *
get_drmarker_hotp_policy_status_table()
{
ASSERT_NOT_IMPLEMENTED(false);
return NULL;
}
void
set_drmarker_hotp_policy_status_table(void *new_table)
{
ASSERT_NOT_IMPLEMENTED(false);
}
byte *
hook_text(byte *hook_code_buf, const app_pc image_addr, intercept_function_t hook_func,
const void *callee_arg, const after_intercept_action_t action_after,
const bool abort_if_hooked, const bool ignore_cti, byte **app_code_copy_p,
byte **alt_exit_tgt_p)
{
ASSERT_NOT_IMPLEMENTED(false);
return NULL;
}
void
unhook_text(byte *hook_code_buf, app_pc image_addr)
{
ASSERT_NOT_IMPLEMENTED(false);
}
void
insert_jmp_at_tramp_entry(dcontext_t *dcontext, byte *trampoline, byte *target)
{
ASSERT_NOT_IMPLEMENTED(false);
}
#endif /* HOT_PATCHING_INTERFACE */
bool
aslr_is_possible_attack(app_pc target)
{
/* FIXME: ASLR not implemented */
return false;
}
app_pc
aslr_possible_preferred_address(app_pc target_addr)
{
/* FIXME: ASLR not implemented */
return NULL;
}
void
take_over_primary_thread()
{
/* nothing to do here */
}
bool
os_current_user_directory(char *directory_prefix /* INOUT */, uint directory_len,
bool create)
{
/* XXX: could share some of this code w/ corresponding windows routine */
uid_t uid = dynamorio_syscall(SYS_getuid, 0);
char *directory = directory_prefix;
char *dirend = directory_prefix + strlen(directory_prefix);
snprintf(dirend, directory_len - (dirend - directory_prefix), "%cdpc-%d", DIRSEP,
uid);
directory_prefix[directory_len - 1] = '\0';
if (!os_file_exists(directory, true /*is dir*/) && create) {
/* XXX: we should ensure we do not follow symlinks */
/* XXX: should add support for CREATE_DIR_FORCE_OWNER */
if (!os_create_dir(directory, CREATE_DIR_REQUIRE_NEW)) {
LOG(GLOBAL, LOG_CACHE, 2, "\terror creating per-user dir %s\n", directory);
return false;
} else {
LOG(GLOBAL, LOG_CACHE, 2, "\tcreated per-user dir %s\n", directory);
}
}
return true;
}
bool
os_validate_user_owned(file_t file_or_directory_handle)
{
/* note on Linux this scheme should never be used */
ASSERT(false && "chown Alice evilfile");
return false;
}
bool
os_check_option_compatibility(void)
{
/* no options are Linux OS version dependent */
return false;
}
#ifdef X86_32
/* Emulate uint64 modulo and division by uint32 on ia32.
* XXX: Does *not* handle 64-bit divisors!
*/
static uint64
uint64_divmod(uint64 dividend, uint64 divisor64, uint32 *remainder)
{
/* Assumes little endian, which x86 is. */
union {
uint64 v64;
struct {
uint32 lo;
uint32 hi;
};
} res;
uint32 upper;
uint32 divisor = (uint32)divisor64;
/* Our uses don't use large divisors. */
ASSERT(divisor64 <= UINT_MAX && "divisor is larger than uint32 can hold");
/* Divide out the high bits first. */
res.v64 = dividend;
upper = res.hi;
res.hi = upper / divisor;
upper %= divisor;
/* Use the unsigned div instruction, which uses EDX:EAX to form a 64-bit
* dividend. We only get a 32-bit quotient out, which is why we divide out
* the high bits first. The quotient will fit in EAX.
*
* DIV r/m32 F7 /6 Unsigned divide EDX:EAX by r/m32, with result stored
* in EAX <- Quotient, EDX <- Remainder.
* inputs:
* EAX = res.lo
* EDX = upper
* rm = divisor
* outputs:
* res.lo = EAX
* *remainder = EDX
* The outputs precede the inputs in gcc inline asm syntax, and so to put
* inputs in EAX and EDX we use "0" and "1".
*/
asm("divl %2"
: "=a"(res.lo), "=d"(*remainder)
: "rm"(divisor), "0"(res.lo), "1"(upper));
return res.v64;
}
/* Match libgcc's prototype. */
uint64
__udivdi3(uint64 dividend, uint64 divisor)
{
uint32 remainder;
return uint64_divmod(dividend, divisor, &remainder);
}
/* Match libgcc's prototype. */
uint64
__umoddi3(uint64 dividend, uint64 divisor)
{
uint32 remainder;
uint64_divmod(dividend, divisor, &remainder);
return (uint64)remainder;
}
/* Same thing for signed. */
static int64
int64_divmod(int64 dividend, int64 divisor64, int *remainder)
{
union {
int64 v64;
struct {
int lo;
int hi;
};
} res;
int upper;
int divisor = (int)divisor64;
/* Our uses don't use large divisors. */
ASSERT(divisor64 <= INT_MAX && divisor64 >= INT_MIN && "divisor too large for int");
/* Divide out the high bits first. */
res.v64 = dividend;
upper = res.hi;
res.hi = upper / divisor;
upper %= divisor;
/* Like above but with the signed div instruction, which does a signed divide
* on edx:eax by r/m32 => quotient in eax, remainder in edx.
*/
asm("idivl %2"
: "=a"(res.lo), "=d"(*remainder)
: "rm"(divisor), "0"(res.lo), "1"(upper));
return res.v64;
}
/* Match libgcc's prototype. */
int64
__divdi3(int64 dividend, int64 divisor)
{
int remainder;
return int64_divmod(dividend, divisor, &remainder);
}
/* __moddi3 is coming from third_party/libgcc for x86 as well as arm. */
#elif defined(ARM)
/* i#1566: for ARM, __aeabi versions are used instead of udivdi3 and umoddi3.
* We link with __aeabi routines from libgcc via third_party/libgcc.
*/
#endif /* X86_32 */
/****************************************************************************
* Tests
*/
#if defined(STANDALONE_UNIT_TEST)
void
test_uint64_divmod(void)
{
# ifdef X86_32
uint64 quotient;
uint32 remainder;
/* Simple division below 2^32. */
quotient = uint64_divmod(9, 3, &remainder);
EXPECT(quotient == 3, true);
EXPECT(remainder == 0, true);
quotient = uint64_divmod(10, 3, &remainder);
EXPECT(quotient == 3, true);
EXPECT(remainder == 1, true);
/* Division when upper bits are less than the divisor. */
quotient = uint64_divmod(45ULL << 31, 1U << 31, &remainder);
EXPECT(quotient == 45, true);
EXPECT(remainder == 0, true);
/* Division when upper bits are greater than the divisor. */
quotient = uint64_divmod(45ULL << 32, 15, &remainder);
EXPECT(quotient == 3ULL << 32, true);
EXPECT(remainder == 0, true);
quotient = uint64_divmod((45ULL << 32) + 13, 15, &remainder);
EXPECT(quotient == 3ULL << 32, true);
EXPECT(remainder == 13, true);
/* Try calling the intrinsics. Don't divide by powers of two, gcc will
* lower that to a shift.
*/
quotient = (45ULL << 32);
quotient /= 15;
EXPECT(quotient == (3ULL << 32), true);
quotient = (45ULL << 32) + 13;
remainder = quotient % 15;
EXPECT(remainder == 13, true);
# endif /* X86_32 */
}
void
unit_test_os(void)
{
test_uint64_divmod();
}
#endif /* STANDALONE_UNIT_TEST */
| 1 | 25,793 | Convention is to use TEST | DynamoRIO-dynamorio | c |
@@ -38,9 +38,9 @@ class TemporalMemoryCompatibilityTest(unittest.TestCase):
"""
- @unittest.skip("There are slight differences between implementations that"
- "prevent this from passing still. See "
- "https://github.com/numenta/nupic/issues/2980")
+ # @unittest.skip("There are slight differences between implementations that"
+ # "prevent this from passing still. See "
+ # "https://github.com/numenta/nupic/issues/2980")
def testTMPyCpp(self):
"""
Test compatibility between C++ and Python TM implementation. | 1 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2016, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import json
import unittest
import numpy
from nupic.regions.TPRegion import TPRegion
from network_creation_common import createAndRunNetwork
class TemporalMemoryCompatibilityTest(unittest.TestCase):
"""Temporal Memory compatability tests between different implementations.
TODO: Test with predictedSegmentDecrement set to non-zero. See
https://github.com/numenta/nupic/issues/2999
"""
@unittest.skip("There are slight differences between implementations that"
"prevent this from passing still. See "
"https://github.com/numenta/nupic/issues/2980")
def testTMPyCpp(self):
"""
Test compatibility between C++ and Python TM implementation.
"""
results1 = createAndRunNetwork(TPRegion,
"bottomUpOut",
checkpointMidway=False,
temporalImp="tm_cpp")
results2 = createAndRunNetwork(TPRegion,
"bottomUpOut",
checkpointMidway=False,
temporalImp="tm_py")
self.compareArrayResults(results1, results2)
def compareArrayResults(self, results1, results2):
self.assertEqual(len(results1), len(results2))
for i in xrange(len(results1)):
result1 = list(results1[i].nonzero()[0])
result2 = list(results2[i].nonzero()[0])
self.assertEqual(result1, result2,
"Row {0} not equal: {1} vs. {2}".format(i, result1, result2))
if __name__ == "__main__":
unittest.main()
| 1 | 21,224 | Just in case: remember to remove this. | numenta-nupic | py |
@@ -61,7 +61,7 @@ public class EIP1559 {
final BigInteger target = BigInteger.valueOf(targetGasUsed);
final BigInteger denominator = BigInteger.valueOf(feeMarket.getBasefeeMaxChangeDenominator());
feeDelta = pBaseFee.multiply(gDelta).divide(target).divide(denominator).longValue();
- baseFee = parentBaseFee - feeDelta;
+ baseFee = max(parentBaseFee - feeDelta, 0);
}
LOG.trace(
"block #{} parentBaseFee: {} parentGasUsed: {} parentGasTarget: {} baseFee: {}", | 1 | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.core.fees;
import static java.lang.Math.max;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import java.math.BigInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class EIP1559 {
private static final Logger LOG = LogManager.getLogger();
private final long initialForkBlknum;
private final FeeMarket feeMarket = FeeMarket.eip1559();
public EIP1559(final long forkBlockNumber) {
initialForkBlknum = forkBlockNumber;
}
public long computeBaseFee(
final long blockNumber,
final long parentBaseFee,
final long parentBlockGasUsed,
final long targetGasUsed) {
if (isForkBlock(blockNumber)) {
return getFeeMarket().getInitialBasefee();
}
long gasDelta, feeDelta, baseFee;
if (parentBlockGasUsed == targetGasUsed) {
return parentBaseFee;
} else if (parentBlockGasUsed > targetGasUsed) {
gasDelta = parentBlockGasUsed - targetGasUsed;
final BigInteger pBaseFee = BigInteger.valueOf(parentBaseFee);
final BigInteger gDelta = BigInteger.valueOf(gasDelta);
final BigInteger target = BigInteger.valueOf(targetGasUsed);
final BigInteger denominator = BigInteger.valueOf(feeMarket.getBasefeeMaxChangeDenominator());
feeDelta = max(pBaseFee.multiply(gDelta).divide(target).divide(denominator).longValue(), 1);
baseFee = parentBaseFee + feeDelta;
} else {
gasDelta = targetGasUsed - parentBlockGasUsed;
final BigInteger pBaseFee = BigInteger.valueOf(parentBaseFee);
final BigInteger gDelta = BigInteger.valueOf(gasDelta);
final BigInteger target = BigInteger.valueOf(targetGasUsed);
final BigInteger denominator = BigInteger.valueOf(feeMarket.getBasefeeMaxChangeDenominator());
feeDelta = pBaseFee.multiply(gDelta).divide(target).divide(denominator).longValue();
baseFee = parentBaseFee - feeDelta;
}
LOG.trace(
"block #{} parentBaseFee: {} parentGasUsed: {} parentGasTarget: {} baseFee: {}",
blockNumber,
parentBaseFee,
parentBlockGasUsed,
targetGasUsed,
baseFee);
return baseFee;
}
public boolean isValidBaseFee(final long parentBaseFee, final long baseFee) {
return Math.abs(baseFee - parentBaseFee)
<= Math.max(1, parentBaseFee / feeMarket.getBasefeeMaxChangeDenominator());
}
public boolean isEIP1559(final long blockNumber) {
return blockNumber >= initialForkBlknum;
}
public boolean isForkBlock(final long blockNumber) {
return initialForkBlknum == blockNumber;
}
public long getForkBlock() {
return initialForkBlknum;
}
public long targetGasUsed(final BlockHeader header) {
return header.getGasLimit() / getFeeMarket().getSlackCoefficient();
}
public FeeMarket getFeeMarket() {
return feeMarket;
}
}
| 1 | 25,507 | I am not certain if this should be 0 or 7 here. I think a basefee under 7 is pathological | hyperledger-besu | java |
@@ -20,6 +20,12 @@ vm[] = {
.0002908882086657216,
.0000048481368110953599
};
+/* byte sequence for Degree Sign U+00B0 in UTF-8. */
+ static constexpr char
+DEG_SIGN1 = '\xc2';
+ static constexpr char
+DEG_SIGN2 = '\xb0';
+
double
dmstor(const char *is, char **rs) {
return dmstor_ctx( pj_get_default_ctx(), is, rs ); | 1 | /* Convert DMS string to radians */
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "proj.h"
#include "proj_internal.h"
static double proj_strtod(char *nptr, char **endptr);
/* following should be sufficient for all but the ridiculous */
#define MAX_WORK 64
static const char
*sym = "NnEeSsWw";
static const double
vm[] = {
DEG_TO_RAD,
.0002908882086657216,
.0000048481368110953599
};
double
dmstor(const char *is, char **rs) {
return dmstor_ctx( pj_get_default_ctx(), is, rs );
}
double
dmstor_ctx(PJ_CONTEXT *ctx, const char *is, char **rs) {
int n, nl;
char *s, work[MAX_WORK];
const char* p;
double v, tv;
if (rs)
*rs = (char *)is;
/* copy sting into work space */
while (isspace(*is)) ++is;
n = MAX_WORK;
s = work;
p = (char *)is;
while (isgraph(*p) && --n)
*s++ = *p++;
*s = '\0';
/* it is possible that a really odd input (like lots of leading
zeros) could be truncated in copying into work. But ... */
int sign = *(s = work);
if (sign == '+' || sign == '-') s++;
else sign = '+';
v = 0.;
for (nl = 0 ; nl < 3 ; nl = n + 1 ) {
if (!(isdigit(*s) || *s == '.')) break;
if ((tv = proj_strtod(s, &s)) == HUGE_VAL)
return tv;
switch (*s) {
case 'D': case 'd':
n = 0; break;
case '\'':
n = 1; break;
case '"':
n = 2; break;
case 'r': case 'R':
if (nl) {
proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE );
return HUGE_VAL;
}
++s;
v = tv;
goto skip;
default:
v += tv * vm[nl];
skip: n = 4;
continue;
}
if (n < nl) {
proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE );
return HUGE_VAL;
}
v += tv * vm[n];
++s;
}
/* postfix sign */
if (*s && (p = strchr(sym, *s))) {
sign = (p - sym) >= 4 ? '-' : '+';
++s;
}
if (sign == '-')
v = -v;
if (rs) /* return point of next char after valid string */
*rs = (char *)is + (s - work);
return v;
}
static double
proj_strtod(char *nptr, char **endptr)
{
char c, *cp = nptr;
double result;
/*
* Scan for characters which cause problems with VC++ strtod()
*/
while ((c = *cp) != '\0') {
if (c == 'd' || c == 'D') {
/*
* Found one, so NUL it out, call strtod(),
* then restore it and return
*/
*cp = '\0';
result = strtod(nptr, endptr);
*cp = c;
return result;
}
++cp;
}
/* no offending characters, just handle normally */
return pj_strtod(nptr, endptr);
}
| 1 | 12,684 | it would be better to move the declaration of the variable with its initialization at line 68 | OSGeo-PROJ | cpp |
@@ -12,6 +12,7 @@
defined in: Hall and Kier JCICS _35_ 1039-1045 (1995) Table 1
"""
+import sys
from rdkit import Chem
_rawD = [ | 1 | # $Id$
#
# Copyright (C) 2002-2006 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" contains SMARTS definitions and calculators for EState atom types
defined in: Hall and Kier JCICS _35_ 1039-1045 (1995) Table 1
"""
from rdkit import Chem
_rawD = [
('sLi', '[LiD1]-*'),
('ssBe', '[BeD2](-*)-*'),
('ssssBe', '[BeD4](-*)(-*)(-*)-*'),
('ssBH', '[BD2H](-*)-*'),
('sssB', '[BD3](-*)(-*)-*'),
('ssssB', '[BD4](-*)(-*)(-*)-*'),
('sCH3', '[CD1H3]-*'),
('dCH2', '[CD1H2]=*'),
('ssCH2', '[CD2H2](-*)-*'),
('tCH', '[CD1H]#*'),
('dsCH', '[CD2H](=*)-*'),
('aaCH', '[C,c;D2H](:*):*'),
('sssCH', '[CD3H](-*)(-*)-*'),
('ddC', '[CD2H0](=*)=*'),
('tsC', '[CD2H0](#*)-*'),
('dssC', '[CD3H0](=*)(-*)-*'),
('aasC', '[C,c;D3H0](:*)(:*)-*'),
('aaaC', '[C,c;D3H0](:*)(:*):*'),
('ssssC', '[CD4H0](-*)(-*)(-*)-*'),
('sNH3', '[ND1H3]-*'),
('sNH2', '[ND1H2]-*'),
('ssNH2', '[ND2H2](-*)-*'),
('dNH', '[ND1H]=*'),
('ssNH', '[ND2H](-*)-*'),
('aaNH', '[N,nD2H](:*):*'),
('tN', '[ND1H0]#*'),
('sssNH', '[ND3H](-*)(-*)-*'),
('dsN', '[ND2H0](=*)-*'),
('aaN', '[N,nD2H0](:*):*'),
('sssN', '[ND3H0](-*)(-*)-*'),
('ddsN', '[ND3H0](~[OD1H0])(~[OD1H0])-,:*'), # mod
('aasN', '[N,nD3H0](:*)(:*)-,:*'), # mod
('ssssN', '[ND4H0](-*)(-*)(-*)-*'),
('sOH', '[OD1H]-*'),
('dO', '[OD1H0]=*'),
('ssO', '[OD2H0](-*)-*'),
('aaO', '[O,oD2H0](:*):*'),
('sF', '[FD1]-*'),
('sSiH3', '[SiD1H3]-*'),
('ssSiH2', '[SiD2H2](-*)-*'),
('sssSiH', '[SiD3H1](-*)(-*)-*'),
('ssssSi', '[SiD4H0](-*)(-*)(-*)-*'),
('sPH2', '[PD1H2]-*'),
('ssPH', '[PD2H1](-*)-*'),
('sssP', '[PD3H0](-*)(-*)-*'),
('dsssP', '[PD4H0](=*)(-*)(-*)-*'),
('sssssP', '[PD5H0](-*)(-*)(-*)(-*)-*'),
('sSH', '[SD1H1]-*'),
('dS', '[SD1H0]=*'),
('ssS', '[SD2H0](-*)-*'),
('aaS', '[S,sD2H0](:*):*'),
('dssS', '[SD3H0](=*)(-*)-*'),
('ddssS', '[SD4H0](~[OD1H0])(~[OD1H0])(-*)-*'), # mod
('sCl', '[ClD1]-*'),
('sGeH3', '[GeD1H3](-*)'),
('ssGeH2', '[GeD2H2](-*)-*'),
('sssGeH', '[GeD3H1](-*)(-*)-*'),
('ssssGe', '[GeD4H0](-*)(-*)(-*)-*'),
('sAsH2', '[AsD1H2]-*'),
('ssAsH', '[AsD2H1](-*)-*'),
('sssAs', '[AsD3H0](-*)(-*)-*'),
('sssdAs', '[AsD4H0](=*)(-*)(-*)-*'),
('sssssAs', '[AsD5H0](-*)(-*)(-*)(-*)-*'),
('sSeH', '[SeD1H1]-*'),
('dSe', '[SeD1H0]=*'),
('ssSe', '[SeD2H0](-*)-*'),
('aaSe', '[SeD2H0](:*):*'),
('dssSe', '[SeD3H0](=*)(-*)-*'),
('ddssSe', '[SeD4H0](=*)(=*)(-*)-*'),
('sBr', '[BrD1]-*'),
('sSnH3', '[SnD1H3]-*'),
('ssSnH2', '[SnD2H2](-*)-*'),
('sssSnH', '[SnD3H1](-*)(-*)-*'),
('ssssSn', '[SnD4H0](-*)(-*)(-*)-*'),
('sI', '[ID1]-*'),
('sPbH3', '[PbD1H3]-*'),
('ssPbH2', '[PbD2H2](-*)-*'),
('sssPbH', '[PbD3H1](-*)(-*)-*'),
('ssssPb', '[PbD4H0](-*)(-*)(-*)-*'),
]
esPatterns = None
def BuildPatts(rawV=None):
""" Internal Use Only
"""
global esPatterns, _rawD
if rawV is None:
rawV = _rawD
esPatterns = [None] * len(rawV)
for i, (name, sma) in enumerate(rawV):
patt = Chem.MolFromSmarts(sma)
if patt is None:
sys.stderr.write('WARNING: problems with pattern %s (name: %s), skipped.\n' % (sma, name))
else:
esPatterns[i] = name, patt
def TypeAtoms(mol):
""" assigns each atom in a molecule to an EState type
**Returns:**
list of tuples (atoms can possibly match multiple patterns) with atom types
"""
if esPatterns is None:
BuildPatts()
nAtoms = mol.GetNumAtoms()
res = [None] * nAtoms
for name, patt in esPatterns:
matches = mol.GetSubstructMatches(patt, uniquify=0)
for match in matches:
idx = match[0]
if res[idx] is None:
res[idx] = [name]
elif name not in res[idx]:
res[idx].append(name)
for i, v in enumerate(res):
if v is not None:
res[i] = tuple(v)
else:
res[i] = ()
return res
| 1 | 24,026 | I don't think this is required. | rdkit-rdkit | cpp |
@@ -48,7 +48,7 @@ func TestSyncServiceContextUpdated(t *testing.T) {
}
// run the update context call once
- err := service.updateContext()
+ err := service.updateEthContext()
if err != nil {
t.Fatal(err)
} | 1 | package rollup
import (
"context"
"errors"
"fmt"
"math/big"
"reflect"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/gasprice"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params"
)
func setupLatestEthContextTest() (*SyncService, *EthContext) {
service, _, _, _ := newTestSyncService(false)
resp := &EthContext{
BlockNumber: uint64(10),
BlockHash: common.Hash{},
Timestamp: uint64(service.timestampRefreshThreshold.Seconds()) + 1,
}
setupMockClient(service, map[string]interface{}{
"GetLatestEthContext": resp,
})
return service, resp
}
// Test that if applying a transaction fails
func TestSyncServiceContextUpdated(t *testing.T) {
service, resp := setupLatestEthContextTest()
// should get the expected context
expectedCtx := &OVMContext{
blockNumber: 0,
timestamp: 0,
}
if service.OVMContext != *expectedCtx {
t.Fatal("context was not instantiated to the expected value")
}
// run the update context call once
err := service.updateContext()
if err != nil {
t.Fatal(err)
}
// should get the expected context
expectedCtx = &OVMContext{
blockNumber: resp.BlockNumber,
timestamp: resp.Timestamp,
}
if service.OVMContext != *expectedCtx {
t.Fatal("context was not updated to the expected response even though enough time passed")
}
// updating the context should be a no-op if time advanced by less than
// the refresh period
resp.BlockNumber += 1
resp.Timestamp += uint64(service.timestampRefreshThreshold.Seconds())
setupMockClient(service, map[string]interface{}{
"GetLatestEthContext": resp,
})
// call it again
err = service.updateContext()
if err != nil {
t.Fatal(err)
}
// should not get the context from the response because it was too soon
unexpectedCtx := &OVMContext{
blockNumber: resp.BlockNumber,
timestamp: resp.Timestamp,
}
if service.OVMContext == *unexpectedCtx {
t.Fatal("context should not be updated because not enough time passed")
}
}
// Test that the `RollupTransaction` ends up in the transaction cache
// after the transaction enqueued event is emitted. Set `false` as
// the argument to start as a sequencer
func TestSyncServiceTransactionEnqueued(t *testing.T) {
service, txCh, _, err := newTestSyncService(false)
if err != nil {
t.Fatal(err)
}
// The timestamp is in the rollup transaction
timestamp := uint64(24)
// The target is the `to` field on the transaction
target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
// The layer one transaction origin is in the txmeta on the transaction
l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
// The gasLimit is the `gasLimit` on the transaction
gasLimit := uint64(66)
// The data is the `data` on the transaction
data := []byte{0x02, 0x92}
// The L1 blocknumber for the transaction's evm context
l1BlockNumber := big.NewInt(100)
// The queue index of the L1 to L2 transaction
queueIndex := uint64(0)
// The index in the ctc
index := uint64(5)
tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
txMeta := types.NewTransactionMeta(
l1BlockNumber,
timestamp,
&l1TxOrigin,
types.SighashEIP155,
types.QueueOriginL1ToL2,
&index,
&queueIndex,
nil,
)
tx.SetTransactionMeta(txMeta)
setupMockClient(service, map[string]interface{}{
"GetEnqueue": []*types.Transaction{
tx,
},
})
// Run an iteration of the eloop
err = service.sequence()
if err != nil {
t.Fatal("sequencing failed", err)
}
// Wait for the tx to be confirmed into the chain and then
// make sure it is the transactions that was set up with in the mockclient
event := <-txCh
if len(event.Txs) != 1 {
t.Fatal("Unexpected number of transactions")
}
confirmed := event.Txs[0]
if !reflect.DeepEqual(tx, confirmed) {
t.Fatal("different txs")
}
}
func TestSyncServiceL1GasPrice(t *testing.T) {
service, _, _, err := newTestSyncService(true)
setupMockClient(service, map[string]interface{}{})
service.L1gpo = gasprice.NewL1Oracle(big.NewInt(0))
if err != nil {
t.Fatal(err)
}
gasBefore, err := service.L1gpo.SuggestDataPrice(context.Background())
if err != nil {
t.Fatal(err)
}
if gasBefore.Cmp(big.NewInt(0)) != 0 {
t.Fatal("expected 0 gas price, got", gasBefore)
}
// run 1 iteration of the eloop
service.sequence()
gasAfter, err := service.L1gpo.SuggestDataPrice(context.Background())
if err != nil {
t.Fatal(err)
}
if gasAfter.Cmp(big.NewInt(100*int64(params.GWei))) != 0 {
t.Fatal("expected 100 gas price, got", gasAfter)
}
}
// Pass true to set as a verifier
func TestSyncServiceSync(t *testing.T) {
service, txCh, sub, err := newTestSyncService(true)
defer sub.Unsubscribe()
if err != nil {
t.Fatal(err)
}
timestamp := uint64(24)
target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
gasLimit := uint64(66)
data := []byte{0x02, 0x92}
l1BlockNumber := big.NewInt(100)
queueIndex := uint64(0)
index := uint64(0)
tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
txMeta := types.NewTransactionMeta(
l1BlockNumber,
timestamp,
&l1TxOrigin,
types.SighashEIP155,
types.QueueOriginL1ToL2,
&index,
&queueIndex,
nil,
)
tx.SetTransactionMeta(txMeta)
setupMockClient(service, map[string]interface{}{
"GetTransaction": []*types.Transaction{
tx,
},
})
err = service.verify()
if err != nil {
t.Fatal("verification failed", err)
}
event := <-txCh
if len(event.Txs) != 1 {
t.Fatal("Unexpected number of transactions")
}
confirmed := event.Txs[0]
if !reflect.DeepEqual(tx, confirmed) {
t.Fatal("different txs")
}
}
func TestInitializeL1ContextPostGenesis(t *testing.T) {
service, _, _, err := newTestSyncService(true)
if err != nil {
t.Fatal(err)
}
timestamp := uint64(24)
target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
gasLimit := uint64(66)
data := []byte{0x02, 0x92}
l1BlockNumber := big.NewInt(100)
queueIndex := uint64(100)
index := uint64(120)
tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
txMeta := types.NewTransactionMeta(
l1BlockNumber,
timestamp,
&l1TxOrigin,
types.SighashEIP155,
types.QueueOriginL1ToL2,
&index,
&queueIndex,
nil,
)
tx.SetTransactionMeta(txMeta)
setupMockClient(service, map[string]interface{}{
"GetEnqueue": []*types.Transaction{
tx,
},
"GetEthContext": []*EthContext{
{
BlockNumber: uint64(10),
BlockHash: common.Hash{},
Timestamp: timestamp,
},
},
})
header := types.Header{
Number: big.NewInt(0),
Time: 11,
}
number := uint64(10)
tx.SetL1Timestamp(timestamp)
tx.SetL1BlockNumber(number)
block := types.NewBlock(&header, []*types.Transaction{tx}, []*types.Header{}, []*types.Receipt{})
service.bc.SetCurrentBlock(block)
err = service.initializeLatestL1(big.NewInt(0))
if err != nil {
t.Fatal(err)
}
latestL1Timestamp := service.GetLatestL1Timestamp()
latestL1BlockNumber := service.GetLatestL1BlockNumber()
if number != latestL1BlockNumber {
t.Fatalf("number does not match, got %d, expected %d", latestL1BlockNumber, number)
}
if latestL1Timestamp != timestamp {
t.Fatal("timestamp does not match")
}
}
func newTestSyncService(isVerifier bool) (*SyncService, chan core.NewTxsEvent, event.Subscription, error) {
chainCfg := params.AllEthashProtocolChanges
chainID := big.NewInt(420)
chainCfg.ChainID = chainID
engine := ethash.NewFaker()
db := rawdb.NewMemoryDatabase()
_ = new(core.Genesis).MustCommit(db)
chain, err := core.NewBlockChain(db, nil, chainCfg, engine, vm.Config{}, nil)
if err != nil {
return nil, nil, nil, fmt.Errorf("Cannot initialize blockchain: %w", err)
}
chaincfg := params.ChainConfig{ChainID: chainID}
txPool := core.NewTxPool(core.TxPoolConfig{PriceLimit: 0}, &chaincfg, chain)
cfg := Config{
CanonicalTransactionChainDeployHeight: big.NewInt(0),
IsVerifier: isVerifier,
// Set as an empty string as this is a dummy value anyways.
// The client needs to be mocked with a mockClient
RollupClientHttp: "",
}
service, err := NewSyncService(context.Background(), cfg, txPool, chain, db)
if err != nil {
return nil, nil, nil, fmt.Errorf("Cannot initialize syncservice: %w", err)
}
txCh := make(chan core.NewTxsEvent, 1)
sub := service.SubscribeNewTxsEvent(txCh)
return service, txCh, sub, nil
}
type mockClient struct {
getEnqueueCallCount int
getEnqueue []*types.Transaction
getTransactionCallCount int
getTransaction []*types.Transaction
getEthContextCallCount int
getEthContext []*EthContext
getLatestEthContext *EthContext
}
func setupMockClient(service *SyncService, responses map[string]interface{}) {
client := newMockClient(responses)
service.client = client
service.L1gpo = gasprice.NewL1Oracle(big.NewInt(0))
}
func newMockClient(responses map[string]interface{}) *mockClient {
getEnqueueResponses := []*types.Transaction{}
getTransactionResponses := []*types.Transaction{}
getEthContextResponses := []*EthContext{}
getLatestEthContextResponse := &EthContext{}
enqueue, ok := responses["GetEnqueue"]
if ok {
getEnqueueResponses = enqueue.([]*types.Transaction)
}
getTx, ok := responses["GetTransaction"]
if ok {
getTransactionResponses = getTx.([]*types.Transaction)
}
getCtx, ok := responses["GetEthContext"]
if ok {
getEthContextResponses = getCtx.([]*EthContext)
}
getLatestCtx, ok := responses["GetLatestEthContext"]
if ok {
getLatestEthContextResponse = getLatestCtx.(*EthContext)
}
return &mockClient{
getEnqueue: getEnqueueResponses,
getTransaction: getTransactionResponses,
getEthContext: getEthContextResponses,
getLatestEthContext: getLatestEthContextResponse,
}
}
func (m *mockClient) GetEnqueue(index uint64) (*types.Transaction, error) {
if m.getEnqueueCallCount < len(m.getEnqueue) {
tx := m.getEnqueue[m.getEnqueueCallCount]
m.getEnqueueCallCount++
return tx, nil
}
return nil, errors.New("")
}
func (m *mockClient) GetLatestEnqueue() (*types.Transaction, error) {
if len(m.getEnqueue) == 0 {
return &types.Transaction{}, errors.New("")
}
return m.getEnqueue[len(m.getEnqueue)-1], nil
}
func (m *mockClient) GetTransaction(index uint64) (*types.Transaction, error) {
if m.getTransactionCallCount < len(m.getTransaction) {
tx := m.getTransaction[m.getTransactionCallCount]
m.getTransactionCallCount++
return tx, nil
}
return nil, errors.New("")
}
func (m *mockClient) GetLatestTransaction() (*types.Transaction, error) {
if len(m.getTransaction) == 0 {
return nil, errors.New("")
}
return m.getTransaction[len(m.getTransaction)-1], nil
}
func (m *mockClient) GetEthContext(index uint64) (*EthContext, error) {
if m.getEthContextCallCount < len(m.getEthContext) {
ctx := m.getEthContext[m.getEthContextCallCount]
m.getEthContextCallCount++
return ctx, nil
}
return nil, errors.New("")
}
func (m *mockClient) GetLatestEthContext() (*EthContext, error) {
return m.getLatestEthContext, nil
}
func (m *mockClient) GetLastConfirmedEnqueue() (*types.Transaction, error) {
return nil, nil
}
func (m *mockClient) SyncStatus() (*SyncStatus, error) {
return &SyncStatus{
Syncing: false,
}, nil
}
func (m *mockClient) GetL1GasPrice() (*big.Int, error) {
return big.NewInt(100 * int64(params.GWei)), nil
}
| 1 | 14,999 | This rename should also ideally be in a separate PR. | ethereum-optimism-optimism | go |
@@ -86,11 +86,14 @@ public final class HttpCall<V> extends Call.Base<V> {
if (t != null) {
callback.onError(t);
} else {
+ V value = null;
try {
- callback.onSuccess(parseResponse(response, bodyConverter));
- } catch (IOException e) {
- callback.onError(e);
+ value = parseResponse(response, bodyConverter);
+ } catch (Throwable t1) {
+ propagateIfFatal(t1);
+ callback.onError(t1);
}
+ if (value != null) callback.onSuccess(value);
}
return null;
}); | 1 | /*
* Copyright 2015-2019 The OpenZipkin 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 zipkin2.elasticsearch.internal.client;
import com.linecorp.armeria.client.HttpClient;
import com.linecorp.armeria.common.AggregatedHttpRequest;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatusClass;
import com.linecorp.armeria.common.RequestContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
import io.netty.util.ReferenceCountUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
import zipkin2.Call;
import zipkin2.Callback;
public final class HttpCall<V> extends Call.Base<V> {
public interface BodyConverter<V> {
V convert(ByteBuffer content) throws IOException;
}
public static class Factory {
final HttpClient httpClient;
public Factory(HttpClient httpClient) {
this.httpClient = httpClient;
}
public <V> HttpCall<V> newCall(AggregatedHttpRequest request, BodyConverter<V> bodyConverter) {
return new HttpCall<>(httpClient, request, bodyConverter);
}
}
public final AggregatedHttpRequest request;
public final BodyConverter<V> bodyConverter;
final HttpClient httpClient;
volatile CompletableFuture<AggregatedHttpResponse> responseFuture;
HttpCall(HttpClient httpClient, AggregatedHttpRequest request, BodyConverter<V> bodyConverter) {
this.httpClient = httpClient;
if (request.content() instanceof ByteBufHolder) {
// Unfortunately it's not possible to use pooled objects in requests and support clone() after
// sending the request.
ByteBuf buf = ((ByteBufHolder) request.content()).content();
try {
this.request = AggregatedHttpRequest.of(
request.headers(), HttpData.copyOf(buf), request.trailers());
} finally {
buf.release();
}
} else {
this.request = request;
}
this.bodyConverter = bodyConverter;
}
@Override protected V doExecute() throws IOException {
AggregatedHttpResponse response = sendRequest().join();
return parseResponse(response, bodyConverter);
}
@Override protected void doEnqueue(Callback<V> callback) {
sendRequest().handle((response, t) -> {
if (t != null) {
callback.onError(t);
} else {
try {
callback.onSuccess(parseResponse(response, bodyConverter));
} catch (IOException e) {
callback.onError(e);
}
}
return null;
});
}
@Override protected void doCancel() {
CompletableFuture<AggregatedHttpResponse> responseFuture = this.responseFuture;
if (responseFuture != null) {
responseFuture.cancel(false);
}
}
@Override public HttpCall<V> clone() {
return new HttpCall<>(httpClient, request, bodyConverter);
}
@Override
public String toString() {
return "HttpCall(" + request + ")";
}
CompletableFuture<AggregatedHttpResponse> sendRequest() {
HttpResponse response = httpClient.execute(request);
CompletableFuture<AggregatedHttpResponse> responseFuture =
RequestContext.mapCurrent(
ctx -> response.aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc()),
// This should never be used in practice since the module runs in an Armeria server.
response::aggregate);
this.responseFuture = responseFuture;
return responseFuture;
}
<V> V parseResponse(AggregatedHttpResponse response, BodyConverter<V> bodyConverter)
throws IOException {
if (response.content().isEmpty()) {
if (response.status().codeClass().equals(HttpStatusClass.SUCCESS)) {
return null;
} else {
throw new IllegalStateException("response failed: " + response);
}
}
HttpData content = response.content();
try {
if (response.status().codeClass().equals(HttpStatusClass.SUCCESS)) {
final ByteBuffer buf;
if (content instanceof ByteBufHolder) {
buf = ((ByteBufHolder) content).content().nioBuffer();
} else {
buf = ByteBuffer.wrap(content.array());
}
return bodyConverter.convert(buf);
} else {
throw new IllegalStateException(
"response for " + request.path() + " failed: " + response.contentUtf8());
}
} finally {
ReferenceCountUtil.safeRelease(content);
}
}
}
| 1 | 15,316 | Think this needs to go right below line 91. `parseResponse` can return `null` (line 133), which will cause this future to never complete. | openzipkin-zipkin | java |
@@ -46,8 +46,8 @@ import java.util.List;
public class HttpCommandProcessor implements CommandProcessor {
private String pathToServlet;
- private String browserStartCommand;
- private String browserURL;
+ private final String browserStartCommand;
+ private final String browserURL;
private String sessionId;
private String extensionJs;
private String rcServerLocation; | 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 com.thoughtworks.selenium;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.openqa.selenium.net.Urls;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Sends commands and retrieves results via HTTP.
*
* @author Ben Griffiths, Jez Humble
* @deprecated The RC interface will be removed in Selenium 3.0. Please migrate to using WebDriver.
*/
@Deprecated
public class HttpCommandProcessor implements CommandProcessor {
private String pathToServlet;
private String browserStartCommand;
private String browserURL;
private String sessionId;
private String extensionJs;
private String rcServerLocation;
/**
* Specifies a server host/port, a command to launch the browser, and a starting URL for the
* browser.
*
* @param serverHost - the host name on which the Selenium Server resides
* @param serverPort - the port on which the Selenium Server is listening
* @param browserStartCommand - the command string used to launch the browser, e.g. "*firefox" or
* "c:\\program files\\internet explorer\\iexplore.exe"
* @param browserURL - the starting URL including just a domain name. We'll start the browser
* pointing at the Selenium resources on this URL,
*/
public HttpCommandProcessor(String serverHost, int serverPort, String browserStartCommand,
String browserURL) {
rcServerLocation = serverHost +
":" + Integer.toString(serverPort);
this.pathToServlet = "http://" + rcServerLocation + "/selenium-server/driver/";
this.browserStartCommand = browserStartCommand;
this.browserURL = browserURL;
this.extensionJs = "";
}
/**
* Specifies the URL to the CommandBridge servlet, a command to launch the browser, and a starting
* URL for the browser.
*
* @param pathToServlet - the URL of the Selenium Server Driver, e.g.
* "http://localhost:4444/selenium-server/driver/" (don't forget the final slash!)
* @param browserStartCommand - the command string used to launch the browser, e.g. "*firefox" or
* "c:\\program files\\internet explorer\\iexplore.exe"
* @param browserURL - the starting URL including just a domain name. We'll start the browser
* pointing at the Selenium resources on this URL,
*/
public HttpCommandProcessor(String pathToServlet, String browserStartCommand, String browserURL) {
this.pathToServlet = pathToServlet;
this.browserStartCommand = browserStartCommand;
this.browserURL = browserURL;
this.extensionJs = "";
}
@Override
public String getRemoteControlServerLocation() {
return rcServerLocation;
}
@Override
public String doCommand(String commandName, String[] args) {
DefaultRemoteCommand command = new DefaultRemoteCommand(commandName, args);
String result = executeCommandOnServlet(command.getCommandURLString());
if (result == null) {
throw new NullPointerException("Selenium Bug! result must not be null");
}
if (!result.startsWith("OK")) {
return throwAssertionFailureExceptionOrError(result);
}
return result;
}
protected String throwAssertionFailureExceptionOrError(String message) {
throw new SeleniumException(message);
}
/** Sends the specified command string to the bridge servlet
* @param command command to execute
* @return response from the command execution
*/
public String executeCommandOnServlet(String command) {
try {
return getCommandResponseAsString(command);
} catch (IOException e) {
if (e instanceof ConnectException) {
throw new SeleniumException(e.getMessage(), e);
}
e.printStackTrace();
throw new UnsupportedOperationException("Catch body broken: IOException from " + command +
" -> " + e, e);
}
}
private String stringContentsOfInputStream(Reader rdr) throws IOException {
StringBuffer sb = new StringBuffer();
int c;
try {
while ((c = rdr.read()) != -1) {
sb.append((char) c);
}
return sb.toString();
} finally {
rdr.close();
}
}
// for testing
protected HttpURLConnection getHttpUrlConnection(URL urlForServlet) throws IOException {
return (HttpURLConnection) urlForServlet.openConnection();
}
// for testing
protected Writer getOutputStreamWriter(HttpURLConnection conn) throws IOException {
return new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), UTF_8));
}
// for testing
protected Reader getInputStreamReader(HttpURLConnection conn) throws IOException {
return new InputStreamReader(conn.getInputStream(), UTF_8);
}
// for testing
protected int getResponseCode(HttpURLConnection conn) throws IOException {
return conn.getResponseCode();
}
protected String getCommandResponseAsString(String command) throws IOException {
String responseString = null;
int responseCode = HttpURLConnection.HTTP_MOVED_PERM;
HttpURLConnection uc = null;
Writer wr = null;
Reader rdr = null;
while (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
URL result = new URL(pathToServlet);
String body = buildCommandBody(command);
try {
uc = getHttpUrlConnection(result);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
uc.setInstanceFollowRedirects(false);
uc.setDoOutput(true);
wr = getOutputStreamWriter(uc);
wr.write(body);
wr.flush();
responseCode = getResponseCode(uc);
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
pathToServlet = uc.getHeaderField("Location");
} else if (responseCode != HttpURLConnection.HTTP_OK) {
throwAssertionFailureExceptionOrError(uc.getResponseMessage() + " URL: " + result);
} else {
rdr = getInputStreamReader(uc);
responseString = stringContentsOfInputStream(rdr);
}
} finally {
closeResources(uc, wr, rdr);
}
}
return responseString;
}
protected void closeResources(HttpURLConnection conn, Writer wr, Reader rdr) {
try {
if (null != wr) {
wr.close();
}
} catch (IOException ioe) {
// ignore
}
try {
if (null != rdr) {
rdr.close();
}
} catch (IOException ioe) {
// ignore
}
if (null != conn) {
conn.disconnect();
}
}
private String buildCommandBody(String command) {
StringBuffer sb = new StringBuffer();
sb.append(command);
if (sessionId != null) {
sb.append("&sessionId=");
sb.append(Urls.urlEncode(sessionId));
}
return sb.toString();
}
/**
* This should be invoked before start().
*
* @param extensionJs the extra extension Javascript to include in this browser session.
*/
@Override
public void setExtensionJs(String extensionJs) {
this.extensionJs = extensionJs;
}
@Override
public void start() {
String result = getString("getNewBrowserSession",
new String[] {browserStartCommand, browserURL, extensionJs});
setSessionInProgress(result);
}
@Override
public void start(String optionsString) {
String result = getString("getNewBrowserSession",
new String[] {browserStartCommand, browserURL,
extensionJs, optionsString});
setSessionInProgress(result);
}
/**
* Wraps the version of start() that takes a String parameter, sending it the result of calling
* toString() on optionsObject, which will likely be a BrowserConfigurationOptions instance.
*
* @param optionsObject start options
*/
@Override
public void start(Object optionsObject) {
start(optionsObject.toString());
}
protected void setSessionInProgress(String result) {
sessionId = result;
}
@Override
public void stop() {
if (hasSessionInProgress()) {
doCommand("testComplete", new String[0]);
}
setSessionInProgress(null);
}
public boolean hasSessionInProgress() {
return null != sessionId;
}
@Override
public String getString(String commandName, String[] args) {
String result = doCommand(commandName, args);
if (result.length() >= "OK,".length()) {
return result.substring("OK,".length());
}
System.err.println("WARNING: getString(" + commandName + ") saw a bad result " + result);
return "";
}
@Override
public String[] getStringArray(String commandName, String[] args) {
String result = getString(commandName, args);
return parseCSV(result);
}
/**
* Convert backslash-escaped comma-delimited string into String array. As described in SRC-CDP
* spec section 5.2.1.2, these strings are comma-delimited, but commas can be escaped with a
* backslash "\". Backslashes can also be escaped as a double-backslash.
*
* @param input the unparsed string, e.g. "veni\, vidi\, vici,c:\\foo\\bar,c:\\I came\, I
* \\saw\\\, I conquered"
* @return the string array resulting from parsing this string
*/
public static String[] parseCSV(String input) {
List<String> output = new ArrayList<>();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case ',':
output.add(sb.toString());
sb = new StringBuffer();
continue;
case '\\':
i++;
c = input.charAt(i);
// fall through to:
default:
sb.append(c);
}
}
output.add(sb.toString());
return output.toArray(new String[output.size()]);
}
@Override
public Number getNumber(String commandName, String[] args) {
String result = getString(commandName, args);
Number n;
try {
n = NumberFormat.getInstance().parse(result);
} catch (ParseException e) {
throw new RuntimeException(e);
}
if (n instanceof Long && n.intValue() == n.longValue()) {
// SRC-315 we should return Integers if possible
return Integer.valueOf(n.intValue());
}
return n;
}
@Override
public Number[] getNumberArray(String commandName, String[] args) {
String[] result = getStringArray(commandName, args);
Number[] n = new Number[result.length];
for (int i = 0; i < result.length; i++) {
try {
n[i] = NumberFormat.getInstance().parse(result[i]);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
return n;
}
@Override
public boolean getBoolean(String commandName, String[] args) {
String result = getString(commandName, args);
boolean b;
if ("true".equals(result)) {
b = true;
return b;
}
if ("false".equals(result)) {
b = false;
return b;
}
throw new RuntimeException("result was neither 'true' nor 'false': " + result);
}
@Override
public boolean[] getBooleanArray(String commandName, String[] args) {
String[] result = getStringArray(commandName, args);
boolean[] b = new boolean[result.length];
for (int i = 0; i < result.length; i++) {
if ("true".equals(result[i])) {
b[i] = true;
continue;
}
if ("false".equals(result[i])) {
b[i] = false;
continue;
}
throw new RuntimeException("result was neither 'true' nor 'false': " +
Arrays.toString(result));
}
return b;
}
}
| 1 | 19,387 | Can you please revert changes to files in the `thoughtworks` package? This is legacy code and we will eventually phase out RC. | SeleniumHQ-selenium | java |
@@ -520,8 +520,7 @@ public class AzkabanWebServer extends AzkabanServer {
startWebMetrics();
}
- if(this.props.containsKey(ConfigurationKeys.ENABLE_QUARTZ) && this.props.getBoolean(ConfigurationKeys
- .ENABLE_QUARTZ)) {
+ if (this.props.getBoolean(ConfigurationKeys.ENABLE_QUARTZ, false)) {
this.quartzScheduler.start();
}
| 1 | /*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.webapp;
import static azkaban.ServiceProvider.SERVICE_PROVIDER;
import static java.util.Objects.requireNonNull;
import azkaban.AzkabanCommonModule;
import azkaban.Constants;
import azkaban.Constants.ConfigurationKeys;
import azkaban.database.AzkabanDatabaseSetup;
import azkaban.executor.ExecutorManager;
import azkaban.jmx.JmxExecutorManager;
import azkaban.jmx.JmxJettyServer;
import azkaban.jmx.JmxTriggerManager;
import azkaban.metrics.MetricsManager;
import azkaban.project.ProjectManager;
import azkaban.scheduler.QuartzScheduler;
import azkaban.scheduler.ScheduleManager;
import azkaban.server.AzkabanServer;
import azkaban.server.session.SessionCache;
import azkaban.trigger.TriggerManager;
import azkaban.trigger.TriggerManagerException;
import azkaban.trigger.builtin.BasicTimeChecker;
import azkaban.trigger.builtin.CreateTriggerAction;
import azkaban.trigger.builtin.ExecuteFlowAction;
import azkaban.trigger.builtin.ExecutionChecker;
import azkaban.trigger.builtin.KillExecutionAction;
import azkaban.trigger.builtin.SlaAlertAction;
import azkaban.trigger.builtin.SlaChecker;
import azkaban.user.UserManager;
import azkaban.utils.FileIOUtils;
import azkaban.utils.Props;
import azkaban.utils.PropsUtils;
import azkaban.utils.StdOutErrRedirect;
import azkaban.utils.Utils;
import azkaban.webapp.plugin.PluginRegistry;
import azkaban.webapp.plugin.TriggerPlugin;
import azkaban.webapp.plugin.ViewerPlugin;
import azkaban.webapp.servlet.AbstractAzkabanServlet;
import azkaban.webapp.servlet.ExecutorServlet;
import azkaban.webapp.servlet.HistoryServlet;
import azkaban.webapp.servlet.IndexRedirectServlet;
import azkaban.webapp.servlet.JMXHttpServlet;
import azkaban.webapp.servlet.NoteServlet;
import azkaban.webapp.servlet.ProjectManagerServlet;
import azkaban.webapp.servlet.ProjectServlet;
import azkaban.webapp.servlet.ScheduleServlet;
import azkaban.webapp.servlet.StatsServlet;
import azkaban.webapp.servlet.StatusServlet;
import azkaban.webapp.servlet.TriggerManagerServlet;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.linkedin.restli.server.RestliServlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.jmx.HierarchyDynamicMBean;
import org.apache.velocity.app.VelocityEngine;
import org.joda.time.DateTimeZone;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.DefaultServlet;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.thread.QueuedThreadPool;
/**
* The Azkaban Jetty server class
*
* Global azkaban properties for setup. All of them are optional unless otherwise marked:
* azkaban.name - The displayed name of this instance. azkaban.label - Short descriptor of this
* Azkaban instance. azkaban.color - Theme color azkaban.temp.dir - Temp dir used by Azkaban for
* various file uses. web.resource.dir - The directory that contains the static web files.
* default.timezone.id - The timezone code. I.E. America/Los Angeles
*
* user.manager.class - The UserManager class used for the user manager. Default is XmlUserManager.
* project.manager.class - The ProjectManager to load projects project.global.properties - The base
* properties inherited by all projects and jobs
*
* jetty.maxThreads - # of threads for jetty jetty.ssl.port - The ssl port used for sessionizing.
* jetty.keystore - Jetty keystore . jetty.keypassword - Jetty keystore password jetty.truststore -
* Jetty truststore jetty.trustpassword - Jetty truststore password
*/
@Singleton
public class AzkabanWebServer extends AzkabanServer {
public static final String DEFAULT_CONF_PATH = "conf";
private static final String AZKABAN_ACCESS_LOGGER_NAME =
"azkaban.webapp.servlet.LoginAbstractAzkabanServlet";
private static final Logger logger = Logger.getLogger(AzkabanWebServer.class);
private static final int MAX_FORM_CONTENT_SIZE = 10 * 1024 * 1024;
private static final String DEFAULT_TIMEZONE_ID = "default.timezone.id";
private static final String DEFAULT_STATIC_DIR = "";
@Deprecated
private static AzkabanWebServer app;
private final VelocityEngine velocityEngine;
private final StatusService statusService;
private final Server server;
private final UserManager userManager;
private final ProjectManager projectManager;
private final ExecutorManager executorManager;
private final ScheduleManager scheduleManager;
private final TriggerManager triggerManager;
private final MetricsManager metricsManager;
private final Props props;
private final SessionCache sessionCache;
private final List<ObjectName> registeredMBeans = new ArrayList<>();
private final QuartzScheduler quartzScheduler;
private Map<String, TriggerPlugin> triggerPlugins;
private MBeanServer mbeanServer;
@Inject
public AzkabanWebServer(final Props props,
final Server server,
final ExecutorManager executorManager,
final ProjectManager projectManager,
final TriggerManager triggerManager,
final MetricsManager metricsManager,
final SessionCache sessionCache,
final UserManager userManager,
final ScheduleManager scheduleManager,
final VelocityEngine velocityEngine,
final QuartzScheduler quartzScheduler,
final StatusService statusService) {
this.props = requireNonNull(props, "props is null.");
this.server = requireNonNull(server, "server is null.");
this.executorManager = requireNonNull(executorManager, "executorManager is null.");
this.projectManager = requireNonNull(projectManager, "projectManager is null.");
this.triggerManager = requireNonNull(triggerManager, "triggerManager is null.");
this.metricsManager = requireNonNull(metricsManager, "metricsManager is null.");
this.sessionCache = requireNonNull(sessionCache, "sessionCache is null.");
this.userManager = requireNonNull(userManager, "userManager is null.");
this.scheduleManager = requireNonNull(scheduleManager, "scheduleManager is null.");
this.velocityEngine = requireNonNull(velocityEngine, "velocityEngine is null.");
this.quartzScheduler = requireNonNull(quartzScheduler, "quartzScheduler is null.");
this.statusService = statusService;
loadBuiltinCheckersAndActions();
// load all trigger agents here
final String triggerPluginDir =
props.getString("trigger.plugin.dir", "plugins/triggers");
new PluginCheckerAndActionsLoader().load(triggerPluginDir);
// Setup time zone
if (props.containsKey(DEFAULT_TIMEZONE_ID)) {
final String timezone = props.getString(DEFAULT_TIMEZONE_ID);
System.setProperty("user.timezone", timezone);
TimeZone.setDefault(TimeZone.getTimeZone(timezone));
DateTimeZone.setDefault(DateTimeZone.forID(timezone));
logger.info("Setting timezone to " + timezone);
}
configureMBeanServer();
}
@Deprecated
public static AzkabanWebServer getInstance() {
return app;
}
public static void main(final String[] args) throws Exception {
// Redirect all std out and err messages into log4j
StdOutErrRedirect.redirectOutAndErrToLog();
logger.info("Starting Jetty Azkaban Web Server...");
final Props props = AzkabanServer.loadProps(args);
if (props == null) {
logger.error("Azkaban Properties not loaded. Exiting..");
System.exit(1);
}
/* Initialize Guice Injector */
final Injector injector = Guice.createInjector(
new AzkabanCommonModule(props),
new AzkabanWebServerModule()
);
SERVICE_PROVIDER.setInjector(injector);
launch(injector.getInstance(AzkabanWebServer.class));
}
public static void launch(final AzkabanWebServer webServer) throws Exception {
/* This creates the Web Server instance */
app = webServer;
// TODO refactor code into ServerProvider
webServer.prepareAndStartServer();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
webServer.quartzScheduler.shutdown();
} catch (final Exception e) {
logger.error(("Exception while shutting down quartz scheduler."), e);
}
try {
logTopMemoryConsumers();
} catch (final Exception e) {
logger.error(("Exception when logging top memory consumers"), e);
}
logger.info("Shutting down http server...");
try {
webServer.close();
} catch (final Exception e) {
logger.error("Error while shutting down http server.", e);
}
logger.info("kk thx bye.");
}
public void logTopMemoryConsumers() throws Exception {
if (new File("/bin/bash").exists() && new File("/bin/ps").exists()
&& new File("/usr/bin/head").exists()) {
logger.info("logging top memeory consumer");
final java.lang.ProcessBuilder processBuilder =
new java.lang.ProcessBuilder("/bin/bash", "-c",
"/bin/ps aux --sort -rss | /usr/bin/head");
final Process p = processBuilder.start();
p.waitFor();
final InputStream is = p.getInputStream();
final java.io.BufferedReader reader =
new java.io.BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line = null;
while ((line = reader.readLine()) != null) {
logger.info(line);
}
is.close();
}
}
});
}
private static void loadViewerPlugins(final Context root, final String pluginPath,
final VelocityEngine ve) {
final File viewerPluginPath = new File(pluginPath);
if (!viewerPluginPath.exists()) {
return;
}
final ClassLoader parentLoader = AzkabanWebServer.class.getClassLoader();
final File[] pluginDirs = viewerPluginPath.listFiles();
final ArrayList<String> jarPaths = new ArrayList<>();
for (final File pluginDir : pluginDirs) {
if (!pluginDir.exists()) {
logger.error("Error viewer plugin path " + pluginDir.getPath()
+ " doesn't exist.");
continue;
}
if (!pluginDir.isDirectory()) {
logger.error("The plugin path " + pluginDir + " is not a directory.");
continue;
}
// Load the conf directory
final File propertiesDir = new File(pluginDir, "conf");
Props pluginProps = null;
if (propertiesDir.exists() && propertiesDir.isDirectory()) {
final File propertiesFile = new File(propertiesDir, "plugin.properties");
final File propertiesOverrideFile =
new File(propertiesDir, "override.properties");
if (propertiesFile.exists()) {
if (propertiesOverrideFile.exists()) {
pluginProps =
PropsUtils.loadProps(null, propertiesFile,
propertiesOverrideFile);
} else {
pluginProps = PropsUtils.loadProps(null, propertiesFile);
}
} else {
logger.error("Plugin conf file " + propertiesFile + " not found.");
continue;
}
} else {
logger.error("Plugin conf path " + propertiesDir + " not found.");
continue;
}
final String pluginName = pluginProps.getString("viewer.name");
final String pluginWebPath = pluginProps.getString("viewer.path");
final String pluginJobTypes = pluginProps.getString("viewer.jobtypes", null);
final int pluginOrder = pluginProps.getInt("viewer.order", 0);
final boolean pluginHidden = pluginProps.getBoolean("viewer.hidden", false);
final List<String> extLibClasspath =
pluginProps.getStringList("viewer.external.classpaths",
(List<String>) null);
final String pluginClass = pluginProps.getString("viewer.servlet.class");
if (pluginClass == null) {
logger.error("Viewer class is not set.");
} else {
logger.info("Plugin class " + pluginClass);
}
URLClassLoader urlClassLoader = null;
final File libDir = new File(pluginDir, "lib");
if (libDir.exists() && libDir.isDirectory()) {
final File[] files = libDir.listFiles();
final ArrayList<URL> urls = new ArrayList<>();
for (int i = 0; i < files.length; ++i) {
try {
final URL url = files[i].toURI().toURL();
urls.add(url);
} catch (final MalformedURLException e) {
logger.error(e);
}
}
// Load any external libraries.
if (extLibClasspath != null) {
for (final String extLib : extLibClasspath) {
final File extLibFile = new File(pluginDir, extLib);
if (extLibFile.exists()) {
if (extLibFile.isDirectory()) {
// extLibFile is a directory; load all the files in the
// directory.
final File[] extLibFiles = extLibFile.listFiles();
for (int i = 0; i < extLibFiles.length; ++i) {
try {
final URL url = extLibFiles[i].toURI().toURL();
urls.add(url);
} catch (final MalformedURLException e) {
logger.error(e);
}
}
} else { // extLibFile is a file
try {
final URL url = extLibFile.toURI().toURL();
urls.add(url);
} catch (final MalformedURLException e) {
logger.error(e);
}
}
} else {
logger.error("External library path "
+ extLibFile.getAbsolutePath() + " not found.");
continue;
}
}
}
urlClassLoader =
new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader);
} else {
logger
.error("Library path " + libDir.getAbsolutePath() + " not found.");
continue;
}
Class<?> viewerClass = null;
try {
viewerClass = urlClassLoader.loadClass(pluginClass);
} catch (final ClassNotFoundException e) {
logger.error("Class " + pluginClass + " not found.");
continue;
}
final String source = FileIOUtils.getSourcePathFromClass(viewerClass);
logger.info("Source jar " + source);
jarPaths.add("jar:file:" + source);
Constructor<?> constructor = null;
try {
constructor = viewerClass.getConstructor(Props.class);
} catch (final NoSuchMethodException e) {
logger.error("Constructor not found in " + pluginClass);
continue;
}
Object obj = null;
try {
obj = constructor.newInstance(pluginProps);
} catch (final Exception e) {
logger.error(e);
logger.error(e.getCause());
}
if (!(obj instanceof AbstractAzkabanServlet)) {
logger.error("The object is not an AbstractAzkabanServlet");
continue;
}
final AbstractAzkabanServlet avServlet = (AbstractAzkabanServlet) obj;
root.addServlet(new ServletHolder(avServlet), "/" + pluginWebPath + "/*");
PluginRegistry.getRegistry().register(
new ViewerPlugin(pluginName, pluginWebPath, pluginOrder,
pluginHidden, pluginJobTypes));
}
// Velocity needs the jar resource paths to be set.
final String jarResourcePath = StringUtils.join(jarPaths, ", ");
logger.info("Setting jar resource path " + jarResourcePath);
ve.addProperty("jar.resource.loader.path", jarResourcePath);
}
private void validateDatabaseVersion()
throws IOException, SQLException {
final boolean checkDB = this.props
.getBoolean(AzkabanDatabaseSetup.DATABASE_CHECK_VERSION, false);
if (checkDB) {
final AzkabanDatabaseSetup setup = new AzkabanDatabaseSetup(this.props);
setup.loadTableInfo();
if (setup.needsUpdating()) {
logger.error("Database is out of date.");
setup.printUpgradePlan();
logger.error("Exiting with error.");
System.exit(-1);
}
}
}
private void configureRoutes() throws TriggerManagerException {
final String staticDir =
this.props.getString("web.resource.dir", DEFAULT_STATIC_DIR);
logger.info("Setting up web resource dir " + staticDir);
final Context root = new Context(this.server, "/", Context.SESSIONS);
root.setMaxFormContentSize(MAX_FORM_CONTENT_SIZE);
final String defaultServletPath =
this.props.getString("azkaban.default.servlet.path", "/index");
root.setResourceBase(staticDir);
final ServletHolder indexRedirect =
new ServletHolder(new IndexRedirectServlet(defaultServletPath));
root.addServlet(indexRedirect, "/");
final ServletHolder index = new ServletHolder(new ProjectServlet());
root.addServlet(index, "/index");
final ServletHolder staticServlet = new ServletHolder(new DefaultServlet());
root.addServlet(staticServlet, "/css/*");
root.addServlet(staticServlet, "/js/*");
root.addServlet(staticServlet, "/images/*");
root.addServlet(staticServlet, "/fonts/*");
root.addServlet(staticServlet, "/favicon.ico");
root.addServlet(new ServletHolder(new ProjectManagerServlet()), "/manager");
root.addServlet(new ServletHolder(new ExecutorServlet()), "/executor");
root.addServlet(new ServletHolder(new HistoryServlet()), "/history");
root.addServlet(new ServletHolder(new ScheduleServlet()), "/schedule");
root.addServlet(new ServletHolder(new JMXHttpServlet()), "/jmx");
root.addServlet(new ServletHolder(new TriggerManagerServlet()), "/triggers");
root.addServlet(new ServletHolder(new StatsServlet()), "/stats");
root.addServlet(new ServletHolder(new StatusServlet(this.statusService)), "/status");
root.addServlet(new ServletHolder(new NoteServlet()), "/notes");
final ServletHolder restliHolder = new ServletHolder(new RestliServlet());
restliHolder.setInitParameter("resourcePackages", "azkaban.restli");
root.addServlet(restliHolder, "/restli/*");
final String viewerPluginDir =
this.props.getString("viewer.plugin.dir", "plugins/viewer");
loadViewerPlugins(root, viewerPluginDir, getVelocityEngine());
// Trigger Plugin Loader
final TriggerPluginLoader triggerPluginLoader = new TriggerPluginLoader(this.props);
final Map<String, TriggerPlugin> triggerPlugins = triggerPluginLoader.loadTriggerPlugins(root);
setTriggerPlugins(triggerPlugins);
// always have basic time trigger
// TODO: find something else to do the job
getTriggerManager().start();
root.setAttribute(Constants.AZKABAN_SERVLET_CONTEXT_KEY, this);
}
private void prepareAndStartServer()
throws Exception {
validateDatabaseVersion();
createThreadPool();
configureRoutes();
if (this.props.getBoolean(Constants.ConfigurationKeys.IS_METRICS_ENABLED, false)) {
startWebMetrics();
}
if(this.props.containsKey(ConfigurationKeys.ENABLE_QUARTZ) && this.props.getBoolean(ConfigurationKeys
.ENABLE_QUARTZ)) {
this.quartzScheduler.start();
}
try {
this.server.start();
logger.info("Server started");
} catch (final Exception e) {
logger.warn(e);
Utils.croak(e.getMessage(), 1);
}
}
private void createThreadPool() {
final int maxThreads = this.props
.getInt("jetty.maxThreads", Constants.DEFAULT_JETTY_MAX_THREAD_COUNT);
final QueuedThreadPool httpThreadPool = new QueuedThreadPool(maxThreads);
this.server.setThreadPool(httpThreadPool);
addThreadPoolGauges(httpThreadPool);
}
private void addThreadPoolGauges(final QueuedThreadPool threadPool) {
// The number of idle threads in Jetty thread pool
this.metricsManager.addGauge("JETTY-NumIdleThreads", threadPool::getIdleThreads);
// The number of threads in Jetty thread pool. The formula is:
// threads = idleThreads + busyThreads
this.metricsManager.addGauge("JETTY-NumTotalThreads", threadPool::getThreads);
// The number of requests queued in the Jetty thread pool.
this.metricsManager.addGauge("JETTY-NumQueueSize", threadPool::getQueueSize);
}
private void startWebMetrics() throws Exception {
this.metricsManager.addGauge("WEB-NumQueuedFlows", this.executorManager::getQueuedFlowSize);
/*
* TODO: Currently {@link ExecutorManager#getRunningFlows()} includes both running and non-dispatched flows.
* Originally we would like to do a subtraction between getRunningFlows and {@link ExecutorManager#getQueuedFlowSize()},
* in order to have the correct runnable flows.
* However, both getRunningFlows and getQueuedFlowSize are not synchronized, such that we can not make
* a thread safe subtraction. We need to fix this in the future.
*/
this.metricsManager
.addGauge("WEB-NumRunningFlows", () -> this.executorManager.getRunningFlows().size());
logger.info("starting reporting Web Server Metrics");
this.metricsManager.startReporting("AZ-WEB", this.props);
}
private void loadBuiltinCheckersAndActions() {
logger.info("Loading built-in checker and action types");
ExecuteFlowAction.setExecutorManager(this.executorManager);
ExecuteFlowAction.setProjectManager(this.projectManager);
ExecuteFlowAction.setTriggerManager(this.triggerManager);
KillExecutionAction.setExecutorManager(this.executorManager);
CreateTriggerAction.setTriggerManager(this.triggerManager);
ExecutionChecker.setExecutorManager(this.executorManager);
this.triggerManager.registerCheckerType(BasicTimeChecker.type, BasicTimeChecker.class);
this.triggerManager.registerCheckerType(SlaChecker.type, SlaChecker.class);
this.triggerManager.registerCheckerType(ExecutionChecker.type, ExecutionChecker.class);
this.triggerManager.registerActionType(ExecuteFlowAction.type, ExecuteFlowAction.class);
this.triggerManager.registerActionType(KillExecutionAction.type, KillExecutionAction.class);
this.triggerManager.registerActionType(SlaAlertAction.type, SlaAlertAction.class);
this.triggerManager.registerActionType(CreateTriggerAction.type, CreateTriggerAction.class);
}
/**
* Returns the web session cache.
*/
@Override
public SessionCache getSessionCache() {
return this.sessionCache;
}
/**
* Returns the velocity engine for pages to use.
*/
@Override
public VelocityEngine getVelocityEngine() {
return this.velocityEngine;
}
@Override
public UserManager getUserManager() {
return this.userManager;
}
public ProjectManager getProjectManager() {
return this.projectManager;
}
public ExecutorManager getExecutorManager() {
return this.executorManager;
}
public ScheduleManager getScheduleManager() {
return this.scheduleManager;
}
public TriggerManager getTriggerManager() {
return this.triggerManager;
}
/**
* Returns the global azkaban properties
*/
@Override
public Props getServerProps() {
return this.props;
}
public Map<String, TriggerPlugin> getTriggerPlugins() {
return this.triggerPlugins;
}
private void setTriggerPlugins(final Map<String, TriggerPlugin> triggerPlugins) {
this.triggerPlugins = triggerPlugins;
}
private void configureMBeanServer() {
logger.info("Registering MBeans...");
this.mbeanServer = ManagementFactory.getPlatformMBeanServer();
registerMbean("jetty", new JmxJettyServer(this.server));
registerMbean("triggerManager", new JmxTriggerManager(this.triggerManager));
if (this.executorManager != null) {
registerMbean("executorManager", new JmxExecutorManager(this.executorManager));
}
// Register Log4J loggers as JMX beans so the log level can be
// updated via JConsole or Java VisualVM
final HierarchyDynamicMBean log4jMBean = new HierarchyDynamicMBean();
registerMbean("log4jmxbean", log4jMBean);
final ObjectName accessLogLoggerObjName =
log4jMBean.addLoggerMBean(AZKABAN_ACCESS_LOGGER_NAME);
if (accessLogLoggerObjName == null) {
System.out
.println(
"************* loginLoggerObjName is null, make sure there is a logger with name "
+ AZKABAN_ACCESS_LOGGER_NAME);
} else {
System.out.println("******** loginLoggerObjName: "
+ accessLogLoggerObjName.getCanonicalName());
}
}
public void close() {
try {
for (final ObjectName name : this.registeredMBeans) {
this.mbeanServer.unregisterMBean(name);
logger.info("Jmx MBean " + name.getCanonicalName() + " unregistered.");
}
} catch (final Exception e) {
logger.error("Failed to cleanup MBeanServer", e);
}
this.scheduleManager.shutdown();
this.executorManager.shutdown();
try {
this.server.stop();
} catch (final Exception e) {
// Catch all while closing server
logger.error(e);
}
this.server.destroy();
}
private void registerMbean(final String name, final Object mbean) {
final Class<?> mbeanClass = mbean.getClass();
final ObjectName mbeanName;
try {
mbeanName = new ObjectName(mbeanClass.getName() + ":name=" + name);
this.mbeanServer.registerMBean(mbean, mbeanName);
logger.info("Bean " + mbeanClass.getCanonicalName() + " registered.");
this.registeredMBeans.add(mbeanName);
} catch (final Exception e) {
logger.error("Error registering mbean " + mbeanClass.getCanonicalName(),
e);
}
}
public List<ObjectName> getMbeanNames() {
return this.registeredMBeans;
}
public MBeanInfo getMBeanInfo(final ObjectName name) {
try {
return this.mbeanServer.getMBeanInfo(name);
} catch (final Exception e) {
logger.error(e);
return null;
}
}
public Object getMBeanAttribute(final ObjectName name, final String attribute) {
try {
return this.mbeanServer.getAttribute(name, attribute);
} catch (final Exception e) {
logger.error(e);
return null;
}
}
}
| 1 | 15,135 | Yeah, why not use this method instead of checking with `containsKey`? | azkaban-azkaban | java |
@@ -39,9 +39,9 @@ for i in range(loop_num):
torch.cuda.synchronize()
time_backward += timer.since_last_check()
bar.update()
-print('\nCARAFE time forward: {} ms/iter | time backward: {} ms/iter'.format(
- (time_forward + 1e-3) * 1e3 / loop_num,
- (time_backward + 1e-3) * 1e3 / loop_num))
+print(f'\nCARAFE time forward: {(time_forward + 1e-3) * 1e3 / loop_num} '
+ f'ms/iter | time backward: {(time_backward + 1e-3) * 1e3 / loop_num}'
+ ' ms/iter')
time_naive_forward = 0
time_naive_backward = 0 | 1 | import os.path as osp
import sys
import mmcv
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from mmdet.ops.carafe import CARAFE, CARAFENaive # noqa: E402, isort:skip
from mmdet.ops.carafe import carafe, carafe_naive # noqa: E402, isort:skip
feat = torch.randn(2, 64, 3, 3, requires_grad=True, device='cuda:0').double()
mask = torch.randn(
2, 100, 6, 6, requires_grad=True, device='cuda:0').sigmoid().double()
print('Gradcheck for carafe...')
test = gradcheck(CARAFE(5, 4, 2), (feat, mask), atol=1e-4, eps=1e-4)
print(test)
print('Gradcheck for carafe naive...')
test = gradcheck(CARAFENaive(5, 4, 2), (feat, mask), atol=1e-4, eps=1e-4)
print(test)
feat = torch.randn(
2, 1024, 100, 100, requires_grad=True, device='cuda:0').float()
mask = torch.randn(
2, 25, 200, 200, requires_grad=True, device='cuda:0').sigmoid().float()
loop_num = 500
time_forward = 0
time_backward = 0
bar = mmcv.ProgressBar(loop_num)
timer = mmcv.Timer()
for i in range(loop_num):
x = carafe(feat.clone(), mask.clone(), 5, 1, 2)
torch.cuda.synchronize()
time_forward += timer.since_last_check()
x.sum().backward(retain_graph=True)
torch.cuda.synchronize()
time_backward += timer.since_last_check()
bar.update()
print('\nCARAFE time forward: {} ms/iter | time backward: {} ms/iter'.format(
(time_forward + 1e-3) * 1e3 / loop_num,
(time_backward + 1e-3) * 1e3 / loop_num))
time_naive_forward = 0
time_naive_backward = 0
bar = mmcv.ProgressBar(loop_num)
timer = mmcv.Timer()
for i in range(loop_num):
x = carafe_naive(feat.clone(), mask.clone(), 5, 1, 2)
torch.cuda.synchronize()
time_naive_forward += timer.since_last_check()
x.sum().backward(retain_graph=True)
torch.cuda.synchronize()
time_naive_backward += timer.since_last_check()
bar.update()
print('\nCARAFE naive time forward: {} ms/iter | time backward: {} ms/iter'.
format((time_naive_forward + 1e-3) * 1e3 / loop_num,
(time_naive_backward + 1e-3) * 1e3 / loop_num))
| 1 | 19,265 | Compute `(time_forward + 1e-3) * 1e3 / loop_num` ahead. | open-mmlab-mmdetection | py |
@@ -74,18 +74,13 @@ namespace NLog.Internal
throw;
}
- if (LogManager.ThrowExceptions)
- {
- throw;
- }
-
ReportExceptionInHandler(ex);
}
}
private static void ReportExceptionInHandler(Exception exception)
{
- InternalLogger.Error("Exception in asynchronous handler {0}", exception);
+ InternalLogger.Error(exception, "Exception in asynchronous handler.");
}
}
} | 1 | //
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.Internal
{
using System;
using System.Threading;
using NLog.Common;
/// <summary>
/// Implements a single-call guard around given continuation function.
/// </summary>
internal class SingleCallContinuation
{
private AsyncContinuation asyncContinuation;
/// <summary>
/// Initializes a new instance of the <see cref="SingleCallContinuation"/> class.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public SingleCallContinuation(AsyncContinuation asyncContinuation)
{
this.asyncContinuation = asyncContinuation;
}
/// <summary>
/// Continuation function which implements the single-call guard.
/// </summary>
/// <param name="exception">The exception.</param>
public void Function(Exception exception)
{
try
{
var cont = Interlocked.Exchange(ref this.asyncContinuation, null);
if (cont != null)
{
cont(exception);
}
}
catch (Exception ex)
{
if (ex.MustBeRethrown())
{
throw;
}
if (LogManager.ThrowExceptions)
{
throw;
}
ReportExceptionInHandler(ex);
}
}
private static void ReportExceptionInHandler(Exception exception)
{
InternalLogger.Error("Exception in asynchronous handler {0}", exception);
}
}
} | 1 | 12,503 | Mh... `MustBeRethrown()` above already logs `ex`, so `ex` will be logged here for the second time. I think this line must be moved to before `MustBeRethrown()`. | NLog-NLog | .cs |
@@ -29,11 +29,13 @@ import java.util.Map;
*/
public class CommonDiscoveryProvider implements DiscoveryProvider {
private final DiscoveryContext context;
- private final SnippetSetRunner<Method> snippetSetRunner;
+ private final SnippetSetRunner.Generator<Method> snippetSetRunner;
private final String snippetFileName;
public CommonDiscoveryProvider(
- DiscoveryContext context, SnippetSetRunner<Method> snippetSetRunner, String snippetFileName) {
+ DiscoveryContext context,
+ SnippetSetRunner.Generator<Method> snippetSetRunner,
+ String snippetFileName) {
this.context = context;
this.snippetSetRunner = snippetSetRunner;
this.snippetFileName = snippetFileName; | 1 | /* Copyright 2016 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.
*/
package com.google.api.codegen.discovery;
import com.google.api.codegen.DiscoveryContext;
import com.google.api.codegen.GeneratedResult;
import com.google.api.codegen.SnippetSetRunner;
import com.google.api.tools.framework.snippet.Doc;
import com.google.protobuf.Api;
import com.google.protobuf.Method;
import java.util.Collections;
import java.util.Map;
/**
* Common DiscoveryProvider which runs code generation.
*/
public class CommonDiscoveryProvider implements DiscoveryProvider {
private final DiscoveryContext context;
private final SnippetSetRunner<Method> snippetSetRunner;
private final String snippetFileName;
public CommonDiscoveryProvider(
DiscoveryContext context, SnippetSetRunner<Method> snippetSetRunner, String snippetFileName) {
this.context = context;
this.snippetSetRunner = snippetSetRunner;
this.snippetFileName = snippetFileName;
}
@Override
public Map<String, Doc> generate(Method method) {
GeneratedResult result = snippetSetRunner.generate(method, snippetFileName, context);
Api api = context.getApi();
String outputRoot =
"autogenerated/"
+ api.getName()
+ "/"
+ api.getVersion()
+ "/"
+ context.getService().getDocumentation().getOverview();
String resultPath = outputRoot + "/" + result.getFilename();
return Collections.singletonMap(resultPath, result.getDoc());
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private DiscoveryContext context;
private SnippetSetRunner<Method> snippetSetRunner;
private String snippetFileName;
private Builder() {}
public Builder setContext(DiscoveryContext context) {
this.context = context;
return this;
}
public Builder setSnippetSetRunner(SnippetSetRunner<Method> snippetSetRunner) {
this.snippetSetRunner = snippetSetRunner;
return this;
}
public Builder setSnippetFileName(String snippetFileName) {
this.snippetFileName = snippetFileName;
return this;
}
public CommonDiscoveryProvider build() {
return new CommonDiscoveryProvider(context, snippetSetRunner, snippetFileName);
}
}
}
| 1 | 15,783 | Since this never changes, why not pass it into the constructor instead? | googleapis-gapic-generator | java |
@@ -48,10 +48,10 @@ namespace Nethermind.Synchronization.BeamSync
private readonly ISyncModeSelector _syncModeSelector;
- private readonly Func<bool> _writeThrough;
-
private ILogger _logger;
+ private IDb _targetDbForSaves;
+
public BeamSyncDb(IDb stateDb, IDb tempDb, ISyncModeSelector syncModeSelector, ILogManager logManager)
: base(logManager)
{ | 1 | // Copyright (c) 2018 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Db;
using Nethermind.Dirichlet.Numerics;
using Nethermind.Logging;
using Nethermind.Synchronization.FastSync;
using Nethermind.Synchronization.ParallelSync;
using Nethermind.Synchronization.Peers;
namespace Nethermind.Synchronization.BeamSync
{
public class BeamSyncDb : SyncFeed<StateSyncBatch>, IDb
{
public UInt256 RequiredPeerDifficulty { get; private set; } = UInt256.Zero;
/// <summary>
/// The actual state DB that can be used for reading the fast synced state from. Also used for writes of any
/// nodes without dependencies.
/// </summary>
private IDb _stateDb;
/// <summary>
/// This DB stands in front of the state DB for reads and serves as beam sync DB write-to DB for any writes
/// that are not final (do not have any unfilled child nodes).
/// </summary>
private IDb _tempDb;
private readonly ISyncModeSelector _syncModeSelector;
private readonly Func<bool> _writeThrough;
private ILogger _logger;
public BeamSyncDb(IDb stateDb, IDb tempDb, ISyncModeSelector syncModeSelector, ILogManager logManager)
: base(logManager)
{
_logger = logManager.GetClassLogger<BeamSyncDb>();
_stateDb = stateDb ?? throw new ArgumentNullException(nameof(stateDb));
_tempDb = tempDb ?? throw new ArgumentNullException(nameof(tempDb));
_syncModeSelector = syncModeSelector ?? throw new ArgumentNullException(nameof(syncModeSelector));
_writeThrough = () => (_syncModeSelector.Current & SyncMode.Beam) == SyncMode.None;
}
private bool _isDisposed = false;
public void Dispose()
{
_isDisposed = true;
_tempDb.Dispose();
}
public string Name => _tempDb.Name;
private int _resolvedKeysCount;
private object _diffLock = new object();
private HashSet<Keccak> _requestedNodes = new HashSet<Keccak>();
private TimeSpan _contextExpiryTimeSpan = TimeSpan.FromSeconds(4);
private TimeSpan _preProcessExpiryTimeSpan = TimeSpan.FromSeconds(15);
public byte[] this[byte[] key]
{
get
{
lock (_diffLock)
{
RequiredPeerDifficulty = UInt256.Max(RequiredPeerDifficulty, BeamSyncContext.MinimumDifficulty.Value);
}
// it is not possible for the item to be requested from the DB and missing in the DB unless the DB is corrupted
// if it is missing in the MemDb then it must exist somewhere on the web (unless the block is corrupted / invalid)
// we grab the node from the web through requests
// if the block is invalid then we will be timing out for a long time
// in such case it would be good to have some gossip about corrupted blocks
// but such gossip would be cheap
// if we keep timing out then we would finally reject the block (but only shelve it instead of marking invalid)
bool wasInDb = true;
var fromMem = _stateDb[key];
while (true)
{
if (BeamSyncContext.Cancelled.Value.IsCancellationRequested)
{
throw new TaskCanceledException("Found a better block.");
}
if (_isDisposed)
{
throw new ObjectDisposedException("Beam Sync DB disposed");
}
// shall I leave test logic forever?
if (BeamSyncContext.LoopIterationsToFailInTest.Value != null)
{
int? currentValue = BeamSyncContext.LoopIterationsToFailInTest.Value--;
if (currentValue == 0)
{
throw new Exception();
}
}
fromMem ??= _tempDb[key] ?? _stateDb[key];
if (fromMem == null)
{
if(_logger.IsTrace) _logger.Trace($"Beam sync miss - {key.ToHexString()} - retrieving");
if (Bytes.AreEqual(key, Keccak.Zero.Bytes))
{
// we store sync progress data at Keccak.Zero;
return null;
}
TimeSpan expiry = _contextExpiryTimeSpan;
if (BeamSyncContext.Description.Value?.Contains("preProcess") ?? false)
{
expiry = _preProcessExpiryTimeSpan;
}
if (DateTime.UtcNow - (BeamSyncContext.LastFetchUtc.Value ?? DateTime.UtcNow) > expiry)
{
string message = $"Beam sync request {BeamSyncContext.Description.Value} for key {key.ToHexString()} with last update on {BeamSyncContext.LastFetchUtc.Value:hh:mm:ss.fff} has expired";
if (_logger.IsDebug) _logger.Debug(message);
throw new BeamSyncException(message);
}
wasInDb = false;
// _logger.Info($"BEAM SYNC Asking for {key.ToHexString()} - resolved keys so far {_resolvedKeysCount}");
lock (_requestedNodes)
{
_requestedNodes.Add(new Keccak(key));
}
// _logger.Error($"Requested {key.ToHexString()}");
Activate();
_autoReset.WaitOne(50);
}
else
{
if (!wasInDb)
{
BeamSyncContext.ResolvedInContext.Value++;
Interlocked.Increment(ref _resolvedKeysCount);
if (_logger.IsTrace) _logger.Trace($"Resolved key {key.ToHexString()} of context {BeamSyncContext.Description.Value} - resolved ctx {BeamSyncContext.ResolvedInContext.Value} | total {_resolvedKeysCount}");
}
BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;
return fromMem;
}
}
}
set
{
if (_writeThrough())
{
if(_logger.IsTrace) _logger.Trace($"Write through beam - {key.ToHexString()}");
_stateDb[key] = value;
}
else
{
if(_logger.IsTrace) _logger.Trace($"Saving to temp - {key.ToHexString()}");
_tempDb[key] = value;
}
}
}
public KeyValuePair<byte[], byte[]>[] this[byte[][] keys] => keys.Select(k => new KeyValuePair<byte[], byte[]>(k, this[k])).ToArray();
public IEnumerable<KeyValuePair<byte[], byte[]>> GetAll(bool ordered = false)
{
throw new NotSupportedException();
}
public IEnumerable<byte[]> GetAllValues(bool ordered = false)
{
throw new NotSupportedException();
}
public void StartBatch()
{
}
public void CommitBatch()
{
}
public void Remove(byte[] key)
{
_tempDb.Remove(key);
}
public bool KeyExists(byte[] key)
{
return _tempDb.KeyExists(key);
}
public IDb Innermost => _stateDb.Innermost;
public void Flush()
{
_tempDb.Flush();
}
public void Clear()
{
_tempDb.Clear();
}
public override Task<StateSyncBatch> PrepareRequest()
{
StateSyncBatch request;
lock (_requestedNodes)
{
if (_requestedNodes.Count == 0)
{
return Task.FromResult((StateSyncBatch) null);
}
request = new StateSyncBatch();
request.ConsumerId = FeedId;
if (_requestedNodes.Count < 256)
{
// do not make it state sync item :)
request.RequestedNodes = _requestedNodes.Select(n => new StateSyncItem(n, NodeDataType.State, 0, 0)).ToArray();
_requestedNodes.Clear();
}
else
{
Keccak[] source = _requestedNodes.ToArray();
request.RequestedNodes = new StateSyncItem[256];
_requestedNodes.Clear();
for (int i = 0; i < source.Length; i++)
{
if (i < 256)
{
// not state sync item
request.RequestedNodes[i] = new StateSyncItem(source[i], NodeDataType.State, 0, 0);
}
else
{
_requestedNodes.Add(source[i]);
}
}
}
}
return Task.FromResult(request);
}
public override SyncResponseHandlingResult HandleResponse(StateSyncBatch stateSyncBatch)
{
if (stateSyncBatch.ConsumerId != FeedId)
{
return SyncResponseHandlingResult.InternalError;
}
bool wasDataInvalid = false;
int consumed = 0;
byte[][] data = stateSyncBatch.Responses;
if (data != null)
{
for (int i = 0; i < Math.Min(data.Length, stateSyncBatch.RequestedNodes.Length); i++)
{
Keccak key = stateSyncBatch.RequestedNodes[i].Hash;
if (data[i] != null)
{
if (Keccak.Compute(data[i]) == key)
{
_tempDb[key.Bytes] = data[i];
// _requestedNodes.Remove(hashes[i], out _);
consumed++;
}
else
{
wasDataInvalid = true;
if (_logger.IsDebug) _logger.Debug("Received node data which does not match hash.");
}
}
else
{
if (_tempDb[key.Bytes] == null)
{
lock (_requestedNodes)
{
_requestedNodes.Add(key);
}
}
}
}
}
_autoReset.Set();
if (wasDataInvalid)
{
return SyncResponseHandlingResult.LesserQuality;
}
return consumed == 0 ? SyncResponseHandlingResult.NoProgress : SyncResponseHandlingResult.OK;
}
private AutoResetEvent _autoReset = new AutoResetEvent(true);
public override bool IsMultiFeed => false;
public override AllocationContexts Contexts => AllocationContexts.State;
}
} | 1 | 23,711 | this is critical to avoid state root saving from beam | NethermindEth-nethermind | .cs |
@@ -231,7 +231,8 @@ class AnchorHead(nn.Module):
# map up to original set of anchors
if unmap_outputs:
num_total_anchors = flat_anchors.size(0)
- labels = unmap(labels, num_total_anchors, inside_flags)
+ labels = unmap(labels, num_total_anchors, inside_flags,
+ self.num_classes) # fill bg label
label_weights = unmap(label_weights, num_total_anchors,
inside_flags)
bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags) | 1 | import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import (anchor_inside_flags, build_anchor_generator,
build_assigner, build_bbox_coder, build_sampler,
force_fp32, images_to_levels, multi_apply,
multiclass_nms, unmap)
from ..builder import HEADS, build_loss
@HEADS.register_module
class AnchorHead(nn.Module):
"""Anchor-based head (RPN, RetinaNet, SSD, etc.).
Args:
num_classes (int): Number of categories excluding the background
category.
in_channels (int): Number of channels in the input feature map.
feat_channels (int): Number of hidden channels. Used in child classes.
anchor_generator (dict): Config dict for anchor generator
bbox_coder (dict): Config of bounding box coder.
reg_decoded_bbox (bool): If true, the regression loss would be
applied on decoded bounding boxes. Default: False
background_label (int | None): Label ID of background, set as 0 for
RPN and num_classes for other heads. It will automatically set as
num_classes if None is given.
loss_cls (dict): Config of classification loss.
loss_bbox (dict): Config of localization loss.
train_cfg (dict): Training config of anchor head.
test_cfg (dict): Testing config of anchor head.
""" # noqa: W605
def __init__(self,
num_classes,
in_channels,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
scales=[8, 16, 32],
ratios=[0.5, 1.0, 2.0],
strides=[4, 8, 16, 32, 64]),
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=(.0, .0, .0, .0),
target_stds=(1.0, 1.0, 1.0, 1.0)),
reg_decoded_bbox=False,
background_label=None,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0),
loss_bbox=dict(
type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0),
train_cfg=None,
test_cfg=None):
super(AnchorHead, self).__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.feat_channels = feat_channels
self.use_sigmoid_cls = loss_cls.get('use_sigmoid', False)
# TODO better way to determine whether sample or not
self.sampling = loss_cls['type'] not in ['FocalLoss', 'GHMC']
if self.use_sigmoid_cls:
self.cls_out_channels = num_classes
else:
self.cls_out_channels = num_classes + 1
if self.cls_out_channels <= 0:
raise ValueError(f'num_classes={num_classes} is too small')
self.reg_decoded_bbox = reg_decoded_bbox
self.background_label = (
num_classes if background_label is None else background_label)
# background_label should be either 0 or num_classes
assert (self.background_label == 0
or self.background_label == num_classes)
self.bbox_coder = build_bbox_coder(bbox_coder)
self.loss_cls = build_loss(loss_cls)
self.loss_bbox = build_loss(loss_bbox)
self.train_cfg = train_cfg
self.test_cfg = test_cfg
if self.train_cfg:
self.assigner = build_assigner(self.train_cfg.assigner)
# use PseudoSampler when sampling is False
if self.sampling and hasattr(self.train_cfg, 'sampler'):
sampler_cfg = self.train_cfg.sampler
else:
sampler_cfg = dict(type='PseudoSampler')
self.sampler = build_sampler(sampler_cfg, context=self)
self.fp16_enabled = False
self.anchor_generator = build_anchor_generator(anchor_generator)
# usually the numbers of anchors for each level are the same
# except SSD detectors
self.num_anchors = self.anchor_generator.num_base_anchors[0]
self._init_layers()
def _init_layers(self):
self.conv_cls = nn.Conv2d(self.in_channels,
self.num_anchors * self.cls_out_channels, 1)
self.conv_reg = nn.Conv2d(self.in_channels, self.num_anchors * 4, 1)
def init_weights(self):
normal_init(self.conv_cls, std=0.01)
normal_init(self.conv_reg, std=0.01)
def forward_single(self, x):
cls_score = self.conv_cls(x)
bbox_pred = self.conv_reg(x)
return cls_score, bbox_pred
def forward(self, feats):
return multi_apply(self.forward_single, feats)
def get_anchors(self, featmap_sizes, img_metas, device='cuda'):
"""Get anchors according to feature map sizes.
Args:
featmap_sizes (list[tuple]): Multi-level feature map sizes.
img_metas (list[dict]): Image meta info.
device (torch.device | str): Device for returned tensors
Returns:
tuple:
anchor_list (list[Tensor]): Anchors of each image
valid_flag_list (list[Tensor]): Valid flags of each image
"""
num_imgs = len(img_metas)
# since feature map sizes of all images are the same, we only compute
# anchors for one time
multi_level_anchors = self.anchor_generator.grid_anchors(
featmap_sizes, device)
anchor_list = [multi_level_anchors for _ in range(num_imgs)]
# for each image, we compute valid flags of multi level anchors
valid_flag_list = []
for img_id, img_meta in enumerate(img_metas):
multi_level_flags = self.anchor_generator.valid_flags(
featmap_sizes, img_meta['pad_shape'], device)
valid_flag_list.append(multi_level_flags)
return anchor_list, valid_flag_list
def _get_targets_single(self,
flat_anchors,
valid_flags,
gt_bboxes,
gt_bboxes_ignore,
gt_labels,
img_meta,
label_channels=1,
unmap_outputs=True):
"""Compute regression and classification targets for anchors in
a single image.
Args:
flat_anchors (Tensor): Multi-level anchors of the image, which are
concatenated into a single tensor of shape (num_anchors ,4)
valid_flags (Tensor): Multi level valid flags of the image,
which are concatenated into a single tensor of
shape (num_anchors,).
gt_bboxes (Tensor): Ground truth bboxes of the image,
shape (num_gts, 4).
img_meta (dict): Meta info of the image.
gt_bboxes_ignore (Tensor): Ground truth bboxes to be
ignored, shape (num_ignored_gts, 4).
img_meta (dict): Meta info of the image.
gt_labels (Tensor): Ground truth labels of each box,
shape (num_gts,).
label_channels (int): Channel of label.
unmap_outputs (bool): Whether to map outputs back to the original
set of anchors.
Returns:
tuple:
labels_list (list[Tensor]): Labels of each level
label_weights_list (list[Tensor]): Label weights of each level
bbox_targets_list (list[Tensor]): BBox targets of each level
bbox_weights_list (list[Tensor]): BBox weights of each level
num_total_pos (int): Number of positive samples in all images
num_total_neg (int): Number of negative samples in all images
"""
inside_flags = anchor_inside_flags(flat_anchors, valid_flags,
img_meta['img_shape'][:2],
self.train_cfg.allowed_border)
if not inside_flags.any():
return (None, ) * 6
# assign gt and sample anchors
anchors = flat_anchors[inside_flags, :]
assign_result = self.assigner.assign(
anchors, gt_bboxes, gt_bboxes_ignore,
None if self.sampling else gt_labels)
sampling_result = self.sampler.sample(assign_result, anchors,
gt_bboxes)
num_valid_anchors = anchors.shape[0]
bbox_targets = torch.zeros_like(anchors)
bbox_weights = torch.zeros_like(anchors)
labels = anchors.new_full((num_valid_anchors, ),
self.background_label,
dtype=torch.long)
label_weights = anchors.new_zeros(num_valid_anchors, dtype=torch.float)
pos_inds = sampling_result.pos_inds
neg_inds = sampling_result.neg_inds
if len(pos_inds) > 0:
if not self.reg_decoded_bbox:
pos_bbox_targets = self.bbox_coder.encode(
sampling_result.pos_bboxes, sampling_result.pos_gt_bboxes)
else:
pos_bbox_targets = sampling_result.pos_gt_bboxes
bbox_targets[pos_inds, :] = pos_bbox_targets
bbox_weights[pos_inds, :] = 1.0
if gt_labels is None:
# only rpn gives gt_labels as None, this time FG is 1
labels[pos_inds] = 1
else:
labels[pos_inds] = gt_labels[
sampling_result.pos_assigned_gt_inds]
if self.train_cfg.pos_weight <= 0:
label_weights[pos_inds] = 1.0
else:
label_weights[pos_inds] = self.train_cfg.pos_weight
if len(neg_inds) > 0:
label_weights[neg_inds] = 1.0
# map up to original set of anchors
if unmap_outputs:
num_total_anchors = flat_anchors.size(0)
labels = unmap(labels, num_total_anchors, inside_flags)
label_weights = unmap(label_weights, num_total_anchors,
inside_flags)
bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)
bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags)
return (labels, label_weights, bbox_targets, bbox_weights, pos_inds,
neg_inds)
def get_targets(self,
anchor_list,
valid_flag_list,
gt_bboxes_list,
img_metas,
gt_bboxes_ignore_list=None,
gt_labels_list=None,
label_channels=1,
unmap_outputs=True):
"""Compute regression and classification targets for anchors in
multiple images.
Args:
anchor_list (list[list[Tensor]]): Multi level anchors of each
image. The outer list indicates images, and the inner list
corresponds to feature levels of the image. Each element of
the inner list is a tensor of shape (num_anchors, 4).
valid_flag_list (list[list[Tensor]]): Multi level valid flags of
each image. The outer list indicates images, and the inner list
corresponds to feature levels of the image. Each element of
the inner list is a tensor of shape (num_anchors, )
gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image.
img_metas (list[dict]): Meta info of each image.
gt_bboxes_ignore_list (list[Tensor]): Ground truth bboxes to be
ignored.
gt_labels_list (list[Tensor]): Ground truth labels of each box.
label_channels (int): Channel of label.
unmap_outputs (bool): Whether to map outputs back to the original
set of anchors.
Returns:
tuple:
labels_list (list[Tensor]): Labels of each level
label_weights_list (list[Tensor]): Label weights of each level
bbox_targets_list (list[Tensor]): BBox targets of each level
bbox_weights_list (list[Tensor]): BBox weights of each level
num_total_pos (int): Number of positive samples in all images
num_total_neg (int): Number of negative samples in all images
"""
num_imgs = len(img_metas)
assert len(anchor_list) == len(valid_flag_list) == num_imgs
# anchor number of multi levels
num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]
# concat all level anchors to a single tensor
concat_anchor_list = []
concat_valid_flag_list = []
for i in range(num_imgs):
assert len(anchor_list[i]) == len(valid_flag_list[i])
concat_anchor_list.append(torch.cat(anchor_list[i]))
concat_valid_flag_list.append(torch.cat(valid_flag_list[i]))
# compute targets for each image
if gt_bboxes_ignore_list is None:
gt_bboxes_ignore_list = [None for _ in range(num_imgs)]
if gt_labels_list is None:
gt_labels_list = [None for _ in range(num_imgs)]
(all_labels, all_label_weights, all_bbox_targets, all_bbox_weights,
pos_inds_list, neg_inds_list) = multi_apply(
self._get_targets_single,
concat_anchor_list,
concat_valid_flag_list,
gt_bboxes_list,
gt_bboxes_ignore_list,
gt_labels_list,
img_metas,
label_channels=label_channels,
unmap_outputs=unmap_outputs)
# no valid anchors
if any([labels is None for labels in all_labels]):
return None
# sampled anchors of all images
num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])
num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])
# split targets to a list w.r.t. multiple levels
labels_list = images_to_levels(all_labels, num_level_anchors)
label_weights_list = images_to_levels(all_label_weights,
num_level_anchors)
bbox_targets_list = images_to_levels(all_bbox_targets,
num_level_anchors)
bbox_weights_list = images_to_levels(all_bbox_weights,
num_level_anchors)
return (labels_list, label_weights_list, bbox_targets_list,
bbox_weights_list, num_total_pos, num_total_neg)
def loss_single(self, cls_score, bbox_pred, anchors, labels, label_weights,
bbox_targets, bbox_weights, num_total_samples):
# classification loss
labels = labels.reshape(-1)
label_weights = label_weights.reshape(-1)
cls_score = cls_score.permute(0, 2, 3,
1).reshape(-1, self.cls_out_channels)
loss_cls = self.loss_cls(
cls_score, labels, label_weights, avg_factor=num_total_samples)
# regression loss
bbox_targets = bbox_targets.reshape(-1, 4)
bbox_weights = bbox_weights.reshape(-1, 4)
bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)
if self.reg_decoded_bbox:
anchors = anchors.reshape(-1, 4)
bbox_pred = self.bbox_coder.decode(anchors, bbox_pred)
loss_bbox = self.loss_bbox(
bbox_pred,
bbox_targets,
bbox_weights,
avg_factor=num_total_samples)
return loss_cls, loss_bbox
@force_fp32(apply_to=('cls_scores', 'bbox_preds'))
def loss(self,
cls_scores,
bbox_preds,
gt_bboxes,
gt_labels,
img_metas,
gt_bboxes_ignore=None):
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == self.anchor_generator.num_levels
device = cls_scores[0].device
anchor_list, valid_flag_list = self.get_anchors(
featmap_sizes, img_metas, device=device)
label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1
cls_reg_targets = self.get_targets(
anchor_list,
valid_flag_list,
gt_bboxes,
img_metas,
gt_bboxes_ignore_list=gt_bboxes_ignore,
gt_labels_list=gt_labels,
label_channels=label_channels)
if cls_reg_targets is None:
return None
(labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,
num_total_pos, num_total_neg) = cls_reg_targets
num_total_samples = (
num_total_pos + num_total_neg if self.sampling else num_total_pos)
# anchor number of multi levels
num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]
# concat all level anchors and flags to a single tensor
concat_anchor_list = []
for i in range(len(anchor_list)):
concat_anchor_list.append(torch.cat(anchor_list[i]))
all_anchor_list = images_to_levels(concat_anchor_list,
num_level_anchors)
losses_cls, losses_bbox = multi_apply(
self.loss_single,
cls_scores,
bbox_preds,
all_anchor_list,
labels_list,
label_weights_list,
bbox_targets_list,
bbox_weights_list,
num_total_samples=num_total_samples)
return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)
@force_fp32(apply_to=('cls_scores', 'bbox_preds'))
def get_bboxes(self,
cls_scores,
bbox_preds,
img_metas,
cfg=None,
rescale=False):
"""
Transform network output for a batch into labeled boxes.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W)
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W)
img_metas (list[dict]): Size / scale info for each image
cfg (mmcv.Config): Test / postprocessing configuration,
if None, test_cfg would be used
rescale (bool): If True, return boxes in original image space
Returns:
list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple.
The first item is an (n, 5) tensor, where the first 4 columns
are bounding box positions (tl_x, tl_y, br_x, br_y) and the
5-th column is a score between 0 and 1. The second item is a
(n,) tensor where each item is the class index of the
corresponding box.
Example:
>>> import mmcv
>>> self = AnchorHead(
>>> num_classes=9,
>>> in_channels=1,
>>> anchor_generator=dict(
>>> type='AnchorGenerator',
>>> scales=[8],
>>> ratios=[0.5, 1.0, 2.0],
>>> strides=[4]))
>>> img_metas = [{'img_shape': (32, 32, 3), 'scale_factor': 1}]
>>> cfg = mmcv.Config(dict(
>>> score_thr=0.00,
>>> nms=dict(type='nms', iou_thr=1.0),
>>> max_per_img=10))
>>> feat = torch.rand(1, 1, 3, 3)
>>> cls_score, bbox_pred = self.forward_single(feat)
>>> # note the input lists are over different levels, not images
>>> cls_scores, bbox_preds = [cls_score], [bbox_pred]
>>> result_list = self.get_bboxes(cls_scores, bbox_preds,
>>> img_metas, cfg)
>>> det_bboxes, det_labels = result_list[0]
>>> assert len(result_list) == 1
>>> assert det_bboxes.shape[1] == 5
>>> assert len(det_bboxes) == len(det_labels) == cfg.max_per_img
"""
assert len(cls_scores) == len(bbox_preds)
num_levels = len(cls_scores)
device = cls_scores[0].device
featmap_sizes = [cls_scores[i].shape[-2:] for i in range(num_levels)]
mlvl_anchors = self.anchor_generator.grid_anchors(
featmap_sizes, device=device)
result_list = []
for img_id in range(len(img_metas)):
cls_score_list = [
cls_scores[i][img_id].detach() for i in range(num_levels)
]
bbox_pred_list = [
bbox_preds[i][img_id].detach() for i in range(num_levels)
]
img_shape = img_metas[img_id]['img_shape']
scale_factor = img_metas[img_id]['scale_factor']
proposals = self._get_bboxes_single(cls_score_list, bbox_pred_list,
mlvl_anchors, img_shape,
scale_factor, cfg, rescale)
result_list.append(proposals)
return result_list
def _get_bboxes_single(self,
cls_score_list,
bbox_pred_list,
mlvl_anchors,
img_shape,
scale_factor,
cfg,
rescale=False):
"""
Transform outputs for a single batch item into labeled boxes.
"""
cfg = self.test_cfg if cfg is None else cfg
assert len(cls_score_list) == len(bbox_pred_list) == len(mlvl_anchors)
mlvl_bboxes = []
mlvl_scores = []
for cls_score, bbox_pred, anchors in zip(cls_score_list,
bbox_pred_list, mlvl_anchors):
assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
cls_score = cls_score.permute(1, 2,
0).reshape(-1, self.cls_out_channels)
if self.use_sigmoid_cls:
scores = cls_score.sigmoid()
else:
scores = cls_score.softmax(-1)
bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4)
nms_pre = cfg.get('nms_pre', -1)
if nms_pre > 0 and scores.shape[0] > nms_pre:
# Get maximum scores for foreground classes.
if self.use_sigmoid_cls:
max_scores, _ = scores.max(dim=1)
else:
# remind that we set FG labels to [0, num_class-1]
# since mmdet v2.0
# BG cat_id: num_class
max_scores, _ = scores[:, :-1].max(dim=1)
_, topk_inds = max_scores.topk(nms_pre)
anchors = anchors[topk_inds, :]
bbox_pred = bbox_pred[topk_inds, :]
scores = scores[topk_inds, :]
bboxes = self.bbox_coder.decode(
anchors, bbox_pred, max_shape=img_shape)
mlvl_bboxes.append(bboxes)
mlvl_scores.append(scores)
mlvl_bboxes = torch.cat(mlvl_bboxes)
if rescale:
mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)
mlvl_scores = torch.cat(mlvl_scores)
if self.use_sigmoid_cls:
# Add a dummy background class to the backend when using sigmoid
# remind that we set FG labels to [0, num_class-1] since mmdet v2.0
# BG cat_id: num_class
padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)
mlvl_scores = torch.cat([mlvl_scores, padding], dim=1)
det_bboxes, det_labels = multiclass_nms(mlvl_bboxes, mlvl_scores,
cfg.score_thr, cfg.nms,
cfg.max_per_img)
return det_bboxes, det_labels
| 1 | 19,315 | To make it more clear, `fill=self.num_classes`. | open-mmlab-mmdetection | py |
@@ -78,6 +78,11 @@ type Message struct {
AfterSend func(asFunc func(interface{}) bool) error
}
+// Implement batcher item for byte sized based batching
+func (m *Message) ByteSize() int {
+ return len(m.Body)
+}
+
// Topic publishes messages.
// Drivers may optionally also implement io.Closer; Close will be called
// when the pubsub.Topic is Shutdown. | 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 driver defines interfaces to be implemented by pubsub drivers, which
// will be used by the pubsub package to interact with the underlying services.
// Application code should use package pubsub.
package driver // import "gocloud.dev/pubsub/driver"
import (
"context"
"gocloud.dev/gcerrors"
)
// AckID is the identifier of a message for purposes of acknowledgement.
type AckID interface{}
// AckInfo represents an action on an AckID.
type AckInfo struct {
// AckID is the AckID the action is for.
AckID AckID
// IsAck is true if the AckID should be acked, false if it should be nacked.
IsAck bool
}
// Message is data to be published (sent) to a topic and later received from
// subscriptions on that topic.
type Message struct {
// LoggableID should be set to an opaque message identifer for
// received messages.
LoggableID string
// 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, or to Subscription.SendNacks. This field should only
// be set by methods implementing Subscription.ReceiveBatch.
AckID AckID
// AsFunc allows drivers to expose driver-specific types;
// see Topic.As for more details.
// AsFunc must be populated on messages returned from ReceiveBatch.
AsFunc func(interface{}) bool
// BeforeSend is a callback used when sending a message. It should remain
// nil on messages returned from ReceiveBatch.
//
// The callback must be called exactly once, before the message is sent.
//
// asFunc converts its argument to driver-specific types.
// See https://gocloud.dev/concepts/as/ for background information.
BeforeSend func(asFunc func(interface{}) bool) error
// AfterSend is a callback used when sending a message. It should remain
// nil on messages returned from ReceiveBatch.
//
// The callback must be called at most once, after the message is sent.
// If Send returns an error, AfterSend will not be called.
//
// asFunc converts its argument to driver-specific types.
// See https://gocloud.dev/concepts/as/ for background information.
AfterSend func(asFunc func(interface{}) bool) error
}
// Topic publishes messages.
// Drivers may optionally also implement io.Closer; Close will be called
// when the pubsub.Topic is Shutdown.
type Topic interface {
// SendBatch should publish all the messages in ms. It 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.
//
// Drivers can control the number of messages sent in a single batch
// and the concurrency of calls to SendBatch via a batcher.Options
// passed to pubsub.NewTopic.
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 drivers to expose driver-specific types.
// See https://gocloud.dev/concepts/as/ for background information.
As(i interface{}) bool
// ErrorAs allows drivers to expose driver-specific types for errors.
// See https://gocloud.dev/concepts/as/ for background information.
ErrorAs(error, interface{}) bool
// ErrorCode should return a code that describes the error, which was returned by
// one of the other methods in this interface.
ErrorCode(error) gcerrors.ErrorCode
// Close cleans up any resources used by the Topic. Once Close is called,
// there will be no method calls to the Topic other than As, ErrorAs, and
// ErrorCode.
Close() error
}
// Subscription receives published messages.
// Drivers may optionally also implement io.Closer; Close will be called
// when the pubsub.Subscription is Shutdown.
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 no messages are currently available, this method should block for
// no more than about 1 second. It can return an empty
// slice of messages and no error. ReceiveBatch will be called again
// immediately, so implementations should try to wait for messages for some
// non-zero amount of time before returning zero messages. If the underlying
// service doesn't support waiting, then a time.Sleep can be used.
//
// ReceiveBatch may be called concurrently from multiple goroutines.
//
// Drivers can control the maximum value of maxMessages and the concurrency
// of calls to ReceiveBatch via a batcher.Options passed to
// pubsub.NewSubscription.
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.
//
// It is acceptable for SendAcks to be a no-op for drivers that don't
// support message acknowledgement.
//
// Drivers should suppress errors caused by double-acking a message.
//
// SendAcks may be called concurrently from multiple goroutines.
//
// Drivers can control the maximum size of ackIDs and the concurrency
// of calls to SendAcks/SendNacks via a batcher.Options passed to
// pubsub.NewSubscription.
SendAcks(ctx context.Context, ackIDs []AckID) error
// CanNack must return true iff the driver supports Nacking messages.
//
// If CanNack returns false, SendNacks will never be called, and Nack will
// panic if called.
CanNack() bool
// SendNacks should notify the server that the messages with the given ackIDs
// are not being processed by this client, so that they will be received
// again later, potentially by another subscription.
// This method should return only after all the ackIDs are sent, an
// error occurs, or the context is done.
//
// If the service does not suppport nacking of messages, return false from
// CanNack, and SendNacks will never be called.
//
// SendNacks may be called concurrently from multiple goroutines.
//
// Drivers can control the maximum size of ackIDs and the concurrency
// of calls to SendAcks/Nacks via a batcher.Options passed to
// pubsub.NewSubscription.
SendNacks(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 converts i to driver-specific types.
// See https://gocloud.dev/concepts/as/ for background information.
As(i interface{}) bool
// ErrorAs allows drivers to expose driver-specific types for errors.
// See https://gocloud.dev/concepts/as/ for background information.
ErrorAs(error, interface{}) bool
// ErrorCode should return a code that describes the error, which was returned by
// one of the other methods in this interface.
ErrorCode(error) gcerrors.ErrorCode
// Close cleans up any resources used by the Topic. Once Close is called,
// there will be no method calls to the Topic other than As, ErrorAs, and
// ErrorCode.
Close() error
}
| 1 | 20,569 | Nit: "ByteSize estimates the size in bytes of the message for the purpose of restricting batch sizes." | google-go-cloud | go |
@@ -61,9 +61,11 @@ namespace SampleApp
// The following section should be used to demo sockets
//options.ListenUnixSocket("/tmp/kestrel-test.sock");
-
+ })
+ .UseLibuv(options =>
+ {
// Uncomment the following line to change the default number of libuv threads for all endpoints.
- //options.ThreadCount = 4;
+ options.ThreadCount = 4;
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>() | 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.IO;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Internal;
using Microsoft.Extensions.Logging;
namespace SampleApp
{
public class Startup
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Trace);
var logger = loggerFactory.CreateLogger("Default");
app.Run(async context =>
{
var connectionFeature = context.Connection;
logger.LogDebug($"Peer: {connectionFeature.RemoteIpAddress?.ToString()}:{connectionFeature.RemotePort}"
+ $"{Environment.NewLine}"
+ $"Sock: {connectionFeature.LocalIpAddress?.ToString()}:{connectionFeature.LocalPort}");
var response = $"hello, world{Environment.NewLine}";
context.Response.ContentLength = response.Length;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(response);
});
}
public static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
Console.WriteLine("Unobserved exception: {0}", e.Exception);
};
var host = new WebHostBuilder()
.UseKestrel(options =>
{
options.Listen(IPAddress.Loopback, 5000, listenOptions =>
{
// Uncomment the following to enable Nagle's algorithm for this endpoint.
//listenOptions.NoDelay = false;
listenOptions.UseConnectionLogging();
});
options.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
listenOptions.UseConnectionLogging();
});
options.UseSystemd();
// The following section should be used to demo sockets
//options.ListenUnixSocket("/tmp/kestrel-test.sock");
// Uncomment the following line to change the default number of libuv threads for all endpoints.
//options.ThreadCount = 4;
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.ServerFeatures.Get<InternalKestrelServerOptions>().ThreadPoolDispatching = false;
host.Run();
}
}
} | 1 | 12,314 | It's weird to have this on the same level as kestrel. This needs to move to options. | aspnet-KestrelHttpServer | .cs |
@@ -476,7 +476,11 @@ module.exports = class Webcam extends Plugin {
}
getVideo () {
- const mimeType = this.recordingChunks[0].type
+ // Sometimes in iOS Safari, Blobs (especially the first Blob in the recordingChunks Array)
+ // have empty 'type' attributes (e.g. '') so we need to find a Blob that has a defined 'type'
+ // attribute in order to determine the correct MIME type.
+ const mimeType = this.recordingChunks.find(blob => blob.type?.length > 0).type
+
const fileExtension = getFileTypeExtension(mimeType)
if (!fileExtension) { | 1 | const { h } = require('preact')
const { Plugin } = require('@uppy/core')
const Translator = require('@uppy/utils/lib/Translator')
const getFileTypeExtension = require('@uppy/utils/lib/getFileTypeExtension')
const mimeTypes = require('@uppy/utils/lib/mimeTypes')
const canvasToBlob = require('@uppy/utils/lib/canvasToBlob')
const supportsMediaRecorder = require('./supportsMediaRecorder')
const CameraIcon = require('./CameraIcon')
const CameraScreen = require('./CameraScreen')
const PermissionsScreen = require('./PermissionsScreen')
/**
* Normalize a MIME type or file extension into a MIME type.
*
* @param {string} fileType - MIME type or a file extension prefixed with `.`.
* @returns {string|undefined} The MIME type or `undefined` if the fileType is an extension and is not known.
*/
function toMimeType (fileType) {
if (fileType[0] === '.') {
return mimeTypes[fileType.slice(1)]
}
return fileType
}
/**
* Is this MIME type a video?
*
* @param {string} mimeType - MIME type.
* @returns {boolean}
*/
function isVideoMimeType (mimeType) {
return /^video\/[^*]+$/.test(mimeType)
}
/**
* Is this MIME type an image?
*
* @param {string} mimeType - MIME type.
* @returns {boolean}
*/
function isImageMimeType (mimeType) {
return /^image\/[^*]+$/.test(mimeType)
}
/**
* Setup getUserMedia, with polyfill for older browsers
* Adapted from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
*/
function getMediaDevices () {
// eslint-disable-next-line compat/compat
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// eslint-disable-next-line compat/compat
return navigator.mediaDevices
}
const getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia
if (!getUserMedia) {
return null
}
return {
getUserMedia (opts) {
return new Promise((resolve, reject) => {
getUserMedia.call(navigator, opts, resolve, reject)
})
},
}
}
/**
* Webcam
*/
module.exports = class Webcam extends Plugin {
static VERSION = require('../package.json').version
constructor (uppy, opts) {
super(uppy, opts)
this.mediaDevices = getMediaDevices()
this.supportsUserMedia = !!this.mediaDevices
this.protocol = location.protocol.match(/https/i) ? 'https' : 'http'
this.id = this.opts.id || 'Webcam'
this.title = this.opts.title || 'Camera'
this.type = 'acquirer'
this.icon = () => (
<svg aria-hidden="true" focusable="false" width="32" height="32" viewBox="0 0 32 32">
<g fill="none" fillRule="evenodd">
<rect className="uppy-ProviderIconBg" fill="#03BFEF" width="32" height="32" rx="16" />
<path d="M22 11c1.133 0 2 .867 2 2v7.333c0 1.134-.867 2-2 2H10c-1.133 0-2-.866-2-2V13c0-1.133.867-2 2-2h2.333l1.134-1.733C13.6 9.133 13.8 9 14 9h4c.2 0 .4.133.533.267L19.667 11H22zm-6 1.533a3.764 3.764 0 0 0-3.8 3.8c0 2.129 1.672 3.801 3.8 3.801s3.8-1.672 3.8-3.8c0-2.13-1.672-3.801-3.8-3.801zm0 6.261c-1.395 0-2.46-1.066-2.46-2.46 0-1.395 1.065-2.461 2.46-2.461s2.46 1.066 2.46 2.46c0 1.395-1.065 2.461-2.46 2.461z" fill="#FFF" fillRule="nonzero" />
</g>
</svg>
)
this.defaultLocale = {
strings: {
smile: 'Smile!',
takePicture: 'Take a picture',
startRecording: 'Begin video recording',
stopRecording: 'Stop video recording',
allowAccessTitle: 'Please allow access to your camera',
allowAccessDescription: 'In order to take pictures or record video with your camera, please allow camera access for this site.',
noCameraTitle: 'Camera Not Available',
noCameraDescription: 'In order to take pictures or record video, please connect a camera device',
recordingStoppedMaxSize: 'Recording stopped because the file size is about to exceed the limit',
recordingLength: 'Recording length %{recording_length}',
},
}
// set default options
const defaultOptions = {
onBeforeSnapshot: () => Promise.resolve(),
countdown: false,
modes: [
'video-audio',
'video-only',
'audio-only',
'picture',
],
mirror: true,
showVideoSourceDropdown: false,
facingMode: 'user',
preferredImageMimeType: null,
preferredVideoMimeType: null,
showRecordingLength: false,
}
this.opts = { ...defaultOptions, ...opts }
this.i18nInit()
this.install = this.install.bind(this)
this.setPluginState = this.setPluginState.bind(this)
this.render = this.render.bind(this)
// Camera controls
this._start = this._start.bind(this)
this._stop = this._stop.bind(this)
this._takeSnapshot = this._takeSnapshot.bind(this)
this._startRecording = this._startRecording.bind(this)
this._stopRecording = this._stopRecording.bind(this)
this._oneTwoThreeSmile = this._oneTwoThreeSmile.bind(this)
this._focus = this._focus.bind(this)
this._changeVideoSource = this._changeVideoSource.bind(this)
this.webcamActive = false
if (this.opts.countdown) {
this.opts.onBeforeSnapshot = this._oneTwoThreeSmile
}
this.setPluginState({
hasCamera: false,
cameraReady: false,
cameraError: null,
recordingLengthSeconds: 0,
videoSources: [],
currentDeviceId: null,
})
}
setOptions (newOpts) {
super.setOptions({
...newOpts,
videoConstraints: {
// May be undefined but ... handles that
...this.opts.videoConstraints,
...newOpts?.videoConstraints,
},
})
this.i18nInit()
}
i18nInit () {
this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
this.i18n = this.translator.translate.bind(this.translator)
this.i18nArray = this.translator.translateArray.bind(this.translator)
this.setPluginState() // so that UI re-renders and we see the updated locale
}
hasCameraCheck () {
if (!this.mediaDevices) {
return Promise.resolve(false)
}
return this.mediaDevices.enumerateDevices().then(devices => {
return devices.some(device => device.kind === 'videoinput')
})
}
isAudioOnly () {
return this.opts.modes.length === 1 && this.opts.modes[0] === 'audio-only'
}
getConstraints (deviceId = null) {
const acceptsAudio = this.opts.modes.indexOf('video-audio') !== -1
|| this.opts.modes.indexOf('audio-only') !== -1
const acceptsVideo = !this.isAudioOnly()
&& (this.opts.modes.indexOf('video-audio') !== -1
|| this.opts.modes.indexOf('video-only') !== -1
|| this.opts.modes.indexOf('picture') !== -1)
const videoConstraints = {
...(this.opts.videoConstraints ?? { facingMode: this.opts.facingMode }),
// facingMode takes precedence over deviceId, and not needed
// when specific device is selected
...(deviceId ? { deviceId, facingMode: null } : {}),
}
return {
audio: acceptsAudio,
video: acceptsVideo ? videoConstraints : false,
}
}
_start (options = null) {
if (!this.supportsUserMedia) {
return Promise.reject(new Error('Webcam access not supported'))
}
this.webcamActive = true
const constraints = this.getConstraints(options && options.deviceId ? options.deviceId : null)
this.hasCameraCheck().then(hasCamera => {
this.setPluginState({
hasCamera,
})
// ask user for access to their camera
return this.mediaDevices.getUserMedia(constraints)
.then((stream) => {
this.stream = stream
let currentDeviceId = null
const tracks = this.isAudioOnly() ? stream.getAudioTracks() : stream.getVideoTracks()
if (!options || !options.deviceId) {
currentDeviceId = tracks[0].getSettings().deviceId
} else {
tracks.forEach((track) => {
if (track.getSettings().deviceId === options.deviceId) {
currentDeviceId = track.getSettings().deviceId
}
})
}
// Update the sources now, so we can access the names.
this.updateVideoSources()
this.setPluginState({
currentDeviceId,
cameraReady: true,
})
})
.catch((err) => {
this.setPluginState({
cameraReady: false,
cameraError: err,
})
this.uppy.info(err.message, 'error')
})
})
}
/**
* @returns {object}
*/
_getMediaRecorderOptions () {
const options = {}
// Try to use the `opts.preferredVideoMimeType` or one of the `allowedFileTypes` for the recording.
// If the browser doesn't support it, we'll fall back to the browser default instead.
// Safari doesn't have the `isTypeSupported` API.
if (MediaRecorder.isTypeSupported) {
const { restrictions } = this.uppy.opts
let preferredVideoMimeTypes = []
if (this.opts.preferredVideoMimeType) {
preferredVideoMimeTypes = [this.opts.preferredVideoMimeType]
} else if (restrictions.allowedFileTypes) {
preferredVideoMimeTypes = restrictions.allowedFileTypes.map(toMimeType).filter(isVideoMimeType)
}
const acceptableMimeTypes = preferredVideoMimeTypes.filter((candidateType) => MediaRecorder.isTypeSupported(candidateType)
&& getFileTypeExtension(candidateType))
if (acceptableMimeTypes.length > 0) {
options.mimeType = acceptableMimeTypes[0]
}
}
return options
}
_startRecording () {
// only used if supportsMediaRecorder() returned true
// eslint-disable-next-line compat/compat
this.recorder = new MediaRecorder(this.stream, this._getMediaRecorderOptions())
this.recordingChunks = []
let stoppingBecauseOfMaxSize = false
this.recorder.addEventListener('dataavailable', (event) => {
this.recordingChunks.push(event.data)
const { restrictions } = this.uppy.opts
if (this.recordingChunks.length > 1
&& restrictions.maxFileSize != null
&& !stoppingBecauseOfMaxSize) {
const totalSize = this.recordingChunks.reduce((acc, chunk) => acc + chunk.size, 0)
// Exclude the initial chunk from the average size calculation because it is likely to be a very small outlier
const averageChunkSize = (totalSize - this.recordingChunks[0].size) / (this.recordingChunks.length - 1)
const expectedEndChunkSize = averageChunkSize * 3
const maxSize = Math.max(0, restrictions.maxFileSize - expectedEndChunkSize)
if (totalSize > maxSize) {
stoppingBecauseOfMaxSize = true
this.uppy.info(this.i18n('recordingStoppedMaxSize'), 'warning', 4000)
this._stopRecording()
}
}
})
// use a "time slice" of 500ms: ondataavailable will be called each 500ms
// smaller time slices mean we can more accurately check the max file size restriction
this.recorder.start(500)
if (this.opts.showRecordingLength) {
// Start the recordingLengthTimer if we are showing the recording length.
this.recordingLengthTimer = setInterval(() => {
const currentRecordingLength = this.getPluginState().recordingLengthSeconds
this.setPluginState({ recordingLengthSeconds: currentRecordingLength + 1 })
}, 1000)
}
this.setPluginState({
isRecording: true,
})
}
_stopRecording () {
const stopped = new Promise((resolve, reject) => {
this.recorder.addEventListener('stop', () => {
resolve()
})
this.recorder.stop()
if (this.opts.showRecordingLength) {
// Stop the recordingLengthTimer if we are showing the recording length.
clearInterval(this.recordingLengthTimer)
this.setPluginState({ recordingLengthSeconds: 0 })
}
})
return stopped.then(() => {
this.setPluginState({
isRecording: false,
})
return this.getVideo()
}).then((file) => {
try {
this.uppy.addFile(file)
} catch (err) {
// Logging the error, exept restrictions, which is handled in Core
if (!err.isRestriction) {
this.uppy.log(err)
}
}
}).then(() => {
this.recordingChunks = null
this.recorder = null
}, (error) => {
this.recordingChunks = null
this.recorder = null
throw error
})
}
_stop () {
if (this.stream) {
this.stream.getAudioTracks().forEach((track) => {
track.stop()
})
this.stream.getVideoTracks().forEach((track) => {
track.stop()
})
}
this.webcamActive = false
this.stream = null
}
_getVideoElement () {
return this.el.querySelector('.uppy-Webcam-video')
}
_oneTwoThreeSmile () {
return new Promise((resolve, reject) => {
let count = this.opts.countdown
const countDown = setInterval(() => {
if (!this.webcamActive) {
clearInterval(countDown)
this.captureInProgress = false
return reject(new Error('Webcam is not active'))
}
if (count > 0) {
this.uppy.info(`${count}...`, 'warning', 800)
count--
} else {
clearInterval(countDown)
this.uppy.info(this.i18n('smile'), 'success', 1500)
setTimeout(() => resolve(), 1500)
}
}, 1000)
})
}
_takeSnapshot () {
if (this.captureInProgress) return
this.captureInProgress = true
this.opts.onBeforeSnapshot().catch((err) => {
const message = typeof err === 'object' ? err.message : err
this.uppy.info(message, 'error', 5000)
return Promise.reject(new Error(`onBeforeSnapshot: ${message}`))
}).then(() => {
return this._getImage()
}).then((tagFile) => {
this.captureInProgress = false
try {
this.uppy.addFile(tagFile)
} catch (err) {
// Logging the error, except restrictions, which is handled in Core
if (!err.isRestriction) {
this.uppy.log(err)
}
}
}, (error) => {
this.captureInProgress = false
throw error
})
}
_getImage () {
const video = this._getVideoElement()
if (!video) {
return Promise.reject(new Error('No video element found, likely due to the Webcam tab being closed.'))
}
const width = video.videoWidth
const height = video.videoHeight
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(video, 0, 0)
const { restrictions } = this.uppy.opts
let preferredImageMimeTypes = []
if (this.opts.preferredImageMimeType) {
preferredImageMimeTypes = [this.opts.preferredImageMimeType]
} else if (restrictions.allowedFileTypes) {
preferredImageMimeTypes = restrictions.allowedFileTypes.map(toMimeType).filter(isImageMimeType)
}
const mimeType = preferredImageMimeTypes[0] || 'image/jpeg'
const ext = getFileTypeExtension(mimeType) || 'jpg'
const name = `cam-${Date.now()}.${ext}`
return canvasToBlob(canvas, mimeType).then((blob) => {
return {
source: this.id,
name,
data: new Blob([blob], { type: mimeType }),
type: mimeType,
}
})
}
getVideo () {
const mimeType = this.recordingChunks[0].type
const fileExtension = getFileTypeExtension(mimeType)
if (!fileExtension) {
return Promise.reject(new Error(`Could not retrieve recording: Unsupported media type "${mimeType}"`))
}
const name = `webcam-${Date.now()}.${fileExtension}`
const blob = new Blob(this.recordingChunks, { type: mimeType })
const file = {
source: this.id,
name,
data: new Blob([blob], { type: mimeType }),
type: mimeType,
}
return Promise.resolve(file)
}
_focus () {
if (!this.opts.countdown) return
setTimeout(() => {
this.uppy.info(this.i18n('smile'), 'success', 1500)
}, 1000)
}
_changeVideoSource (deviceId) {
this._stop()
this._start({ deviceId })
}
updateVideoSources () {
this.mediaDevices.enumerateDevices().then(devices => {
this.setPluginState({
videoSources: devices.filter((device) => device.kind === 'videoinput'),
})
})
}
render () {
if (!this.webcamActive) {
this._start()
}
const webcamState = this.getPluginState()
if (!webcamState.cameraReady || !webcamState.hasCamera) {
return (
<PermissionsScreen
icon={CameraIcon}
i18n={this.i18n}
hasCamera={webcamState.hasCamera}
/>
)
}
return (
<CameraScreen
{...webcamState}
onChangeVideoSource={this._changeVideoSource}
onSnapshot={this._takeSnapshot}
onStartRecording={this._startRecording}
onStopRecording={this._stopRecording}
onFocus={this._focus}
onStop={this._stop}
i18n={this.i18n}
modes={this.opts.modes}
showRecordingLength={this.opts.showRecordingLength}
showVideoSourceDropdown={this.opts.showVideoSourceDropdown}
supportsRecording={supportsMediaRecorder()}
recording={webcamState.isRecording}
mirror={this.opts.mirror}
src={this.stream}
/>
)
}
install () {
this.setPluginState({
cameraReady: false,
recordingLengthSeconds: 0,
})
const { target } = this.opts
if (target) {
this.mount(target, this)
}
if (this.mediaDevices) {
this.updateVideoSources()
this.mediaDevices.ondevicechange = (event) => {
this.updateVideoSources()
if (this.stream) {
let restartStream = true
const { videoSources, currentDeviceId } = this.getPluginState()
videoSources.forEach((videoSource) => {
if (currentDeviceId === videoSource.deviceId) {
restartStream = false
}
})
if (restartStream) {
this._stop()
this._start()
}
}
}
}
}
uninstall () {
if (this.stream) {
this._stop()
}
this.unmount()
}
}
| 1 | 13,942 | is it safe for us to use the `blob.type?.length` optional chaining with IE11 support? @goto-bus-stop | transloadit-uppy | js |
@@ -125,13 +125,14 @@ class User < ActiveRecord::Base
# @param new_organisation_id [Integer] the id for an organisation
# @return [String] the empty string as a causality of setting api_token
def org_id=(new_org_id)
+ puts "$$$$ new_org_id: #{new_org_id}"
unless self.can_change_org? || new_org_id.nil? || self.org.nil? || (new_org_id.to_s == self.org.id.to_s)
# rip all permissions from the user
self.perms.delete_all
end
# set the user's new organisation
super(new_org_id)
- self.save!
+ # self.save!
# rip api permissions from the user
self.remove_token!
end | 1 | class User < ActiveRecord::Base
include ConditionalUserMailer
##
# Devise
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :registerable, :recoverable,
:rememberable, :trackable, :validatable, :omniauthable,
:omniauth_providers => [:shibboleth, :orcid]
##
# User Notification Preferences
serialize :prefs, Hash
##
# Associations
has_and_belongs_to_many :perms, join_table: :users_perms
belongs_to :language
belongs_to :org
has_one :pref
has_many :answers
has_many :notes
has_many :exported_plans
has_many :roles, dependent: :destroy
has_many :plans, through: :roles do
def filter(query)
return self unless query.present?
t = self.arel_table
q = "%#{query}%"
conditions = t[:title].matches(q)
columns = %i(
grant_number identifier description principal_investigator data_contact
)
columns = ['grant_number', 'identifier', 'description', 'principal_investigator', 'data_contact']
columns.each {|col| conditions = conditions.or(t[col].matches(q)) }
self.where(conditions)
end
end
has_many :user_identifiers
has_many :identifier_schemes, through: :user_identifiers
validates :email, email: true, allow_nil: true, uniqueness: {message: _("must be unique")}
##
# Scopes
default_scope { includes(:org, :perms) }
# Retrieves all of the org_admins for the specified org
scope :org_admins, -> (org_id) {
joins(:perms).where("users.org_id = ? AND perms.name IN (?)", org_id,
['grant_permissions', 'modify_templates', 'modify_guidance', 'change_org_details'])
}
scope :search, -> (term) {
search_pattern = "%#{term}%"
# MySQL does not support standard string concatenation and since concat_ws or concat functions do
# not exist for sqlite, we have to come up with this conditional
if ActiveRecord::Base.connection.adapter_name == "Mysql2"
where("concat_ws(' ', firstname, surname) LIKE ? OR email LIKE ?", search_pattern, search_pattern)
else
where("firstname || ' ' || surname LIKE ? OR email LIKE ?", search_pattern, search_pattern)
end
}
# EVALUATE CLASS AND INSTANCE METHODS BELOW
#
# What do they do? do they do it efficiently, and do we need them?
# Determines the locale set for the user or the organisation he/she belongs
# @return String or nil
def get_locale
if !self.language.nil?
return self.language.abbreviation
elsif !self.org.nil?
return self.org.get_locale
else
return nil
end
end
##
# gives either the name of the user, or the email if name unspecified
#
# @param user_email [Boolean] defaults to true, allows the use of email if there is no firstname or surname
# @return [String] the email or the firstname and surname of the user
def name(use_email = true)
if (firstname.blank? && surname.blank?) || use_email then
return email
else
name = "#{firstname} #{surname}"
return name.strip
end
end
##
# returns all active plans for a user
#
# @return [Plans]
def active_plans
self.plans.includes(:template).where("roles.active": true).where(Role.not_reviewer_condition)
end
##
# Returns the user's identifier for the specified scheme name
#
# @param the identifier scheme name (e.g. ORCID)
# @return [UserIdentifier] the user's identifier for that scheme
def identifier_for(scheme)
user_identifiers.where(identifier_scheme: scheme).first
end
# TODO: Check the logic here. Its deleting the permissions if the user does not have permission
# to change orgs and either the incoming or existing org is nil.
# We should also NOT be auto-saving here!!!
##
# sets a new organisation id for the user
# if the user has any perms such as org_admin or admin, those are removed
# if the user had an api_token, that is removed
#
# @param new_organisation_id [Integer] the id for an organisation
# @return [String] the empty string as a causality of setting api_token
def org_id=(new_org_id)
unless self.can_change_org? || new_org_id.nil? || self.org.nil? || (new_org_id.to_s == self.org.id.to_s)
# rip all permissions from the user
self.perms.delete_all
end
# set the user's new organisation
super(new_org_id)
self.save!
# rip api permissions from the user
self.remove_token!
end
##
# sets a new organisation for the user
#
# @param new_organisation [Organisation] the new organisation for the user
def organisation=(new_org)
org_id = new_org.id unless new_org.nil?
end
##
# checks if the user is a super admin
# if the user has any privelege which requires them to see the super admin page
# then they are a super admin
#
# @return [Boolean] true if the user is an admin
def can_super_admin?
return self.can_add_orgs? || self.can_grant_api_to_orgs? || self.can_change_org?
end
##
# checks if the user is an organisation admin
# if the user has any privlege which requires them to see the org-admin pages
# then they are an org admin
#
# @return [Boolean] true if the user is an organisation admin
def can_org_admin?
return self.can_grant_permissions? || self.can_modify_guidance? ||
self.can_modify_templates? || self.can_modify_org_details?
end
##
# checks if the user can add new organisations
#
# @return [Boolean] true if the user can add new organisations
def can_add_orgs?
perms.include? Perm.add_orgs
end
##
# checks if the user can change their organisation affiliations
#
# @return [Boolean] true if the user can change their organisation affiliations
def can_change_org?
perms.include? Perm.change_affiliation
end
##
# checks if the user can grant their permissions to others
#
# @return [Boolean] true if the user can grant their permissions to others
def can_grant_permissions?
perms.include? Perm.grant_permissions
end
##
# checks if the user can modify organisation templates
#
# @return [Boolean] true if the user can modify organisation templates
def can_modify_templates?
self.perms.include? Perm.modify_templates
end
##
# checks if the user can modify organisation guidance
#
# @return [Boolean] true if the user can modify organistion guidance
def can_modify_guidance?
perms.include? Perm.modify_guidance
end
##
# checks if the user can use the api
#
# @return [Boolean] true if the user can use the api
def can_use_api?
perms.include? Perm.use_api
end
##
# checks if the user can modify their org's details
#
# @return [Boolean] true if the user can modify the org's details
def can_modify_org_details?
perms.include? Perm.change_org_details
end
##
# checks if the user can grant the api to organisations
#
# @return [Boolean] true if the user can grant api permissions to organisations
def can_grant_api_to_orgs?
perms.include? Perm.grant_api
end
##
# removes the api_token from the user
# modifies the user model
def remove_token!
unless api_token.blank?
self.api_token = ""
self.save!
end
end
##
# generates a new token for the user unless the user already has a token.
# modifies the user's model.
def keep_or_generate_token!
if api_token.nil? || api_token.empty?
self.api_token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless User.exists?(api_token: random_token)
end
self.save!
deliver_if(recipients: self, key: 'users.admin_privileges') do |r|
UserMailer.api_token_granted_notification(r).deliver_now
end
end
end
##
# Load the user based on the scheme and id provided by the Omniauth call
# --------------------------------------------------------------
def self.from_omniauth(auth)
scheme = IdentifierScheme.find_by(name: auth.provider.downcase)
if scheme.nil?
throw Exception.new('Unknown OAuth provider: ' + auth.provider)
else
joins(:user_identifiers).where('user_identifiers.identifier': auth.uid,
'user_identifiers.identifier_scheme_id': scheme.id).first
end
end
##
# Return the user's preferences for a given base key
#
# @return [JSON] with symbols as keys
def get_preferences(key)
defaults = Pref.default_settings[key.to_sym] || Pref.default_settings[key.to_s]
if self.pref.present?
existing = self.pref.settings[key.to_s].deep_symbolize_keys
# Check for new preferences
defaults.keys.each do |grp|
defaults[grp].keys.each do |pref, v|
# If the group isn't present in the saved values add all of it's preferences
existing[grp] = defaults[grp] if existing[grp].nil?
# If the preference isn't present in the saved values add the default
existing[grp][pref] = defaults[grp][pref] if existing[grp][pref].nil?
end
end
existing
else
defaults
end
end
##
# Override devise_invitable email title
# --------------------------------------------------------------
def deliver_invitation(options = {})
super(options.merge(subject: _('A Data Management Plan in %{application_name} has been shared with you') % {application_name: Rails.configuration.branding[:application][:name]}))
end
##
# Case insensitive search over User model
# @param field [string] The name of the field being queried
# @param val [string] The string to search for, case insensitive. val is duck typed to check whether or not downcase method exist
# @return [ActiveRecord::Relation] The result of the search
def self.where_case_insensitive(field, val)
User.where("lower(#{field}) = ?", val.respond_to?(:downcase) ? val.downcase : val.to_s)
end
end
| 1 | 17,420 | remove this debug statement | DMPRoadmap-roadmap | rb |
@@ -2357,7 +2357,12 @@ bool StatelessValidation::manual_PreCallValidateCmdCopyImage(VkCommandBuffer com
VkImageAspectFlags legal_aspect_flags =
VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_METADATA_BIT;
- if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
+ // YCbCr is core after 1.1
+ if (api_version >= VK_API_VERSION_1_1) {
+ legal_aspect_flags |= (VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT | VK_IMAGE_ASPECT_PLANE_2_BIT);
+ }
+ // If physical device does not support 1.1, check for YCbCr extension support
+ else if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
legal_aspect_flags |= (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR | VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
}
| 1 | /* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
* Copyright (C) 2015-2019 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.
*
* Author: Mark Lobodzinski <mark@LunarG.com>
* Author: John Zulauf <jzulauf@lunarg.com>
*/
#define NOMINMAX
#include <math.h>
#include "chassis.h"
#include "stateless_validation.h"
static const int MaxParamCheckerStringLength = 256;
template <typename T>
inline bool in_inclusive_range(const T &value, const T &min, const T &max) {
// Using only < for generality and || for early abort
return !((value < min) || (max < value));
}
bool StatelessValidation::validate_string(const char *apiName, const ParameterName &stringName, const std::string &vuid,
const char *validateString) {
bool skip = false;
VkStringErrorFlags result = vk_string_validate(MaxParamCheckerStringLength, validateString);
if (result == VK_STRING_ERROR_NONE) {
return skip;
} else if (result & VK_STRING_ERROR_LENGTH) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: string %s exceeds max length %d", apiName, stringName.get_name().c_str(), MaxParamCheckerStringLength);
} else if (result & VK_STRING_ERROR_BAD_DATA) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: string %s contains invalid characters or is badly formed", apiName, stringName.get_name().c_str());
}
return skip;
}
bool StatelessValidation::ValidateDeviceQueueFamily(uint32_t queue_family, const char *cmd_name, const char *parameter_name,
const std::string &error_code, bool optional = false) {
bool skip = false;
if (!optional && queue_family == VK_QUEUE_FAMILY_IGNORED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
error_code,
"%s: %s is VK_QUEUE_FAMILY_IGNORED, but it is required to provide a valid queue family index value.",
cmd_name, parameter_name);
} else if (queueFamilyIndexMap.find(queue_family) == queueFamilyIndexMap.end()) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), error_code,
"%s: %s (= %" PRIu32
") is not one of the queue families given via VkDeviceQueueCreateInfo structures when the device was created.",
cmd_name, parameter_name, queue_family);
}
return skip;
}
bool StatelessValidation::ValidateQueueFamilies(uint32_t queue_family_count, const uint32_t *queue_families, const char *cmd_name,
const char *array_parameter_name, const std::string &unique_error_code,
const std::string &valid_error_code, bool optional = false) {
bool skip = false;
if (queue_families) {
std::unordered_set<uint32_t> set;
for (uint32_t i = 0; i < queue_family_count; ++i) {
std::string parameter_name = std::string(array_parameter_name) + "[" + std::to_string(i) + "]";
if (set.count(queue_families[i])) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkDeviceCreateInfo-queueFamilyIndex-00372",
"%s: %s (=%" PRIu32 ") is not unique within %s array.", cmd_name, parameter_name.c_str(),
queue_families[i], array_parameter_name);
} else {
set.insert(queue_families[i]);
skip |= ValidateDeviceQueueFamily(queue_families[i], cmd_name, parameter_name.c_str(), valid_error_code, optional);
}
}
}
return skip;
}
bool StatelessValidation::validate_api_version(uint32_t api_version, uint32_t effective_api_version) {
bool skip = false;
uint32_t api_version_nopatch = VK_MAKE_VERSION(VK_VERSION_MAJOR(api_version), VK_VERSION_MINOR(api_version), 0);
if (api_version_nopatch != effective_api_version) {
if (api_version_nopatch < VK_API_VERSION_1_0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT,
HandleToUint64(instance), kVUIDUndefined,
"Invalid CreateInstance->pCreateInfo->pApplicationInfo.apiVersion number (0x%08x). "
"Using VK_API_VERSION_%" PRIu32 "_%" PRIu32 ".",
api_version, VK_VERSION_MAJOR(effective_api_version), VK_VERSION_MINOR(effective_api_version));
} else {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT,
HandleToUint64(instance), kVUIDUndefined,
"Unrecognized CreateInstance->pCreateInfo->pApplicationInfo.apiVersion number (0x%08x). "
"Assuming VK_API_VERSION_%" PRIu32 "_%" PRIu32 ".",
api_version, VK_VERSION_MAJOR(effective_api_version), VK_VERSION_MINOR(effective_api_version));
}
}
return skip;
}
bool StatelessValidation::validate_instance_extensions(const VkInstanceCreateInfo *pCreateInfo) {
bool skip = false;
for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
skip |= validate_extension_reqs(instance_extensions, "VUID-vkCreateInstance-ppEnabledExtensionNames-01388", "instance",
pCreateInfo->ppEnabledExtensionNames[i]);
}
return skip;
}
template <typename ExtensionState>
bool extension_state_by_name(const ExtensionState &extensions, const char *extension_name) {
if (!extension_name) return false; // null strings specify nothing
auto info = ExtensionState::get_info(extension_name);
bool state = info.state ? extensions.*(info.state) : false; // unknown extensions can't be enabled in extension struct
return state;
}
bool StatelessValidation::manual_PreCallValidateCreateInstance(const VkInstanceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) {
bool skip = false;
// Note: From the spec--
// Providing a NULL VkInstanceCreateInfo::pApplicationInfo or providing an apiVersion of 0 is equivalent to providing
// an apiVersion of VK_MAKE_VERSION(1, 0, 0). (a.k.a. VK_API_VERSION_1_0)
uint32_t local_api_version = (pCreateInfo->pApplicationInfo && pCreateInfo->pApplicationInfo->apiVersion)
? pCreateInfo->pApplicationInfo->apiVersion
: VK_API_VERSION_1_0;
skip |= validate_api_version(local_api_version, api_version);
skip |= validate_instance_extensions(pCreateInfo);
return skip;
}
void StatelessValidation::PostCallRecordCreateInstance(const VkInstanceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkInstance *pInstance,
VkResult result) {
auto instance_data = GetLayerDataPtr(get_dispatch_key(*pInstance), layer_data_map);
// Copy extension data into local object
if (result != VK_SUCCESS) return;
this->instance_extensions = instance_data->instance_extensions;
}
void StatelessValidation::PostCallRecordCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
auto device_data = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
if (result != VK_SUCCESS) return;
ValidationObject *validation_data = GetValidationObject(device_data->object_dispatch, LayerObjectTypeParameterValidation);
StatelessValidation *stateless_validation = static_cast<StatelessValidation *>(validation_data);
// Store queue family data
if ((pCreateInfo != nullptr) && (pCreateInfo->pQueueCreateInfos != nullptr)) {
for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; ++i) {
stateless_validation->queueFamilyIndexMap.insert(
std::make_pair(pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, pCreateInfo->pQueueCreateInfos[i].queueCount));
}
}
// Parmeter validation also uses extension data
stateless_validation->device_extensions = this->device_extensions;
VkPhysicalDeviceProperties device_properties = {};
// Need to get instance and do a getlayerdata call...
ValidationObject *instance_object = GetLayerDataPtr(get_dispatch_key(physicalDevice), layer_data_map);
instance_object->instance_dispatch_table.GetPhysicalDeviceProperties(physicalDevice, &device_properties);
memcpy(&stateless_validation->device_limits, &device_properties.limits, sizeof(VkPhysicalDeviceLimits));
if (device_extensions.vk_nv_shading_rate_image) {
// Get the needed shading rate image limits
auto shading_rate_image_props = lvl_init_struct<VkPhysicalDeviceShadingRateImagePropertiesNV>();
auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&shading_rate_image_props);
instance_object->instance_dispatch_table.GetPhysicalDeviceProperties2KHR(physicalDevice, &prop2);
phys_dev_ext_props.shading_rate_image_props = shading_rate_image_props;
}
if (device_extensions.vk_nv_mesh_shader) {
// Get the needed mesh shader limits
auto mesh_shader_props = lvl_init_struct<VkPhysicalDeviceMeshShaderPropertiesNV>();
auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&mesh_shader_props);
instance_object->instance_dispatch_table.GetPhysicalDeviceProperties2KHR(physicalDevice, &prop2);
phys_dev_ext_props.mesh_shader_props = mesh_shader_props;
}
// Save app-enabled features in this device's validation object
// The enabled features can come from either pEnabledFeatures, or from the pNext chain
const VkPhysicalDeviceFeatures *enabled_features_found = pCreateInfo->pEnabledFeatures;
if ((nullptr == enabled_features_found) && device_extensions.vk_khr_get_physical_device_properties_2) {
const auto *features2 = lvl_find_in_chain<VkPhysicalDeviceFeatures2KHR>(pCreateInfo->pNext);
if (features2) {
enabled_features_found = &(features2->features);
}
}
if (enabled_features_found) {
stateless_validation->physical_device_features = *enabled_features_found;
} else {
memset(&stateless_validation->physical_device_features, 0, sizeof(VkPhysicalDeviceFeatures));
}
}
bool StatelessValidation::manual_PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) {
bool skip = false;
bool maint1 = false;
bool negative_viewport = false;
if ((pCreateInfo->enabledLayerCount > 0) && (pCreateInfo->ppEnabledLayerNames != NULL)) {
for (size_t i = 0; i < pCreateInfo->enabledLayerCount; i++) {
skip |= validate_string("vkCreateDevice", "pCreateInfo->ppEnabledLayerNames",
"VUID-VkDeviceCreateInfo-ppEnabledLayerNames-parameter", pCreateInfo->ppEnabledLayerNames[i]);
}
}
if ((pCreateInfo->enabledExtensionCount > 0) && (pCreateInfo->ppEnabledExtensionNames != NULL)) {
maint1 = extension_state_by_name(device_extensions, VK_KHR_MAINTENANCE1_EXTENSION_NAME);
negative_viewport = extension_state_by_name(device_extensions, VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME);
for (size_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
skip |= validate_string("vkCreateDevice", "pCreateInfo->ppEnabledExtensionNames",
"VUID-VkDeviceCreateInfo-ppEnabledExtensionNames-parameter",
pCreateInfo->ppEnabledExtensionNames[i]);
skip |= validate_extension_reqs(device_extensions, "VUID-vkCreateDevice-ppEnabledExtensionNames-01387", "device",
pCreateInfo->ppEnabledExtensionNames[i]);
}
}
if (maint1 && negative_viewport) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkDeviceCreateInfo-ppEnabledExtensionNames-00374",
"VkDeviceCreateInfo->ppEnabledExtensionNames must not simultaneously include VK_KHR_maintenance1 and "
"VK_AMD_negative_viewport_height.");
}
if (pCreateInfo->pNext != NULL && pCreateInfo->pEnabledFeatures) {
// Check for get_physical_device_properties2 struct
const auto *features2 = lvl_find_in_chain<VkPhysicalDeviceFeatures2KHR>(pCreateInfo->pNext);
if (features2) {
// Cannot include VkPhysicalDeviceFeatures2KHR and have non-null pEnabledFeatures
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_InvalidUsage,
"VkDeviceCreateInfo->pNext includes a VkPhysicalDeviceFeatures2KHR struct when "
"pCreateInfo->pEnabledFeatures is non-NULL.");
}
}
// Validate pCreateInfo->pQueueCreateInfos
if (pCreateInfo->pQueueCreateInfos) {
std::unordered_set<uint32_t> set;
for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; ++i) {
const uint32_t requested_queue_family = pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex;
if (requested_queue_family == VK_QUEUE_FAMILY_IGNORED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), "VUID-VkDeviceQueueCreateInfo-queueFamilyIndex-00381",
"vkCreateDevice: pCreateInfo->pQueueCreateInfos[%" PRIu32
"].queueFamilyIndex is VK_QUEUE_FAMILY_IGNORED, but it is required to provide a valid queue family "
"index value.",
i);
} else if (set.count(requested_queue_family)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), "VUID-VkDeviceCreateInfo-queueFamilyIndex-00372",
"vkCreateDevice: pCreateInfo->pQueueCreateInfos[%" PRIu32 "].queueFamilyIndex (=%" PRIu32
") is not unique within pCreateInfo->pQueueCreateInfos array.",
i, requested_queue_family);
} else {
set.insert(requested_queue_family);
}
if (pCreateInfo->pQueueCreateInfos[i].pQueuePriorities != nullptr) {
for (uint32_t j = 0; j < pCreateInfo->pQueueCreateInfos[i].queueCount; ++j) {
const float queue_priority = pCreateInfo->pQueueCreateInfos[i].pQueuePriorities[j];
if (!(queue_priority >= 0.f) || !(queue_priority <= 1.f)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), "VUID-VkDeviceQueueCreateInfo-pQueuePriorities-00383",
"vkCreateDevice: pCreateInfo->pQueueCreateInfos[%" PRIu32 "].pQueuePriorities[%" PRIu32
"] (=%f) is not between 0 and 1 (inclusive).",
i, j, queue_priority);
}
}
}
}
}
return skip;
}
bool StatelessValidation::require_device_extension(bool flag, char const *function_name, char const *extension_name) {
if (!flag) {
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_ExtensionNotEnabled,
"%s() called even though the %s extension was not enabled for this VkDevice.", function_name,
extension_name);
}
return false;
}
bool StatelessValidation::manual_PreCallValidateGetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex,
VkQueue *pQueue) {
bool skip = false;
skip |= ValidateDeviceQueueFamily(queueFamilyIndex, "vkGetDeviceQueue", "queueFamilyIndex",
"VUID-vkGetDeviceQueue-queueFamilyIndex-00384");
const auto &queue_data = queueFamilyIndexMap.find(queueFamilyIndex);
if (queue_data != queueFamilyIndexMap.end() && queue_data->second <= queueIndex) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-vkGetDeviceQueue-queueIndex-00385",
"vkGetDeviceQueue: queueIndex (=%" PRIu32
") is not less than the number of queues requested from queueFamilyIndex (=%" PRIu32
") when the device was created (i.e. is not less than %" PRIu32 ").",
queueIndex, queueFamilyIndex, queue_data->second);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
bool skip = false;
const LogMiscParams log_misc{VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, VK_NULL_HANDLE, "vkCreateBuffer"};
if (pCreateInfo != nullptr) {
skip |= ValidateGreaterThanZero(pCreateInfo->size, "pCreateInfo->size", "VUID-VkBufferCreateInfo-size-00912", log_misc);
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT) {
// If sharingMode is VK_SHARING_MODE_CONCURRENT, queueFamilyIndexCount must be greater than 1
if (pCreateInfo->queueFamilyIndexCount <= 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkBufferCreateInfo-sharingMode-00914",
"vkCreateBuffer: if pCreateInfo->sharingMode is VK_SHARING_MODE_CONCURRENT, "
"pCreateInfo->queueFamilyIndexCount must be greater than 1.");
}
// If sharingMode is VK_SHARING_MODE_CONCURRENT, pQueueFamilyIndices must be a pointer to an array of
// queueFamilyIndexCount uint32_t values
if (pCreateInfo->pQueueFamilyIndices == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkBufferCreateInfo-sharingMode-00913",
"vkCreateBuffer: if pCreateInfo->sharingMode is VK_SHARING_MODE_CONCURRENT, "
"pCreateInfo->pQueueFamilyIndices must be a pointer to an array of "
"pCreateInfo->queueFamilyIndexCount uint32_t values.");
} else {
skip |= ValidateQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices,
"vkCreateBuffer", "pCreateInfo->pQueueFamilyIndices", kVUID_PVError_InvalidUsage,
kVUID_PVError_InvalidUsage, false);
}
}
// If flags contains VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT or VK_BUFFER_CREATE_SPARSE_ALIASED_BIT, it must also contain
// VK_BUFFER_CREATE_SPARSE_BINDING_BIT
if (((pCreateInfo->flags & (VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT)) != 0) &&
((pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) != VK_BUFFER_CREATE_SPARSE_BINDING_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkBufferCreateInfo-flags-00918",
"vkCreateBuffer: if pCreateInfo->flags contains VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT or "
"VK_BUFFER_CREATE_SPARSE_ALIASED_BIT, it must also contain VK_BUFFER_CREATE_SPARSE_BINDING_BIT.");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
bool skip = false;
const LogMiscParams log_misc{VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, VK_NULL_HANDLE, "vkCreateImage"};
if (pCreateInfo != nullptr) {
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT) {
// If sharingMode is VK_SHARING_MODE_CONCURRENT, queueFamilyIndexCount must be greater than 1
if (pCreateInfo->queueFamilyIndexCount <= 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-sharingMode-00942",
"vkCreateImage(): if pCreateInfo->sharingMode is VK_SHARING_MODE_CONCURRENT, "
"pCreateInfo->queueFamilyIndexCount must be greater than 1.");
}
// If sharingMode is VK_SHARING_MODE_CONCURRENT, pQueueFamilyIndices must be a pointer to an array of
// queueFamilyIndexCount uint32_t values
if (pCreateInfo->pQueueFamilyIndices == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-sharingMode-00941",
"vkCreateImage(): if pCreateInfo->sharingMode is VK_SHARING_MODE_CONCURRENT, "
"pCreateInfo->pQueueFamilyIndices must be a pointer to an array of "
"pCreateInfo->queueFamilyIndexCount uint32_t values.");
} else {
skip |= ValidateQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices, "vkCreateImage",
"pCreateInfo->pQueueFamilyIndices", kVUID_PVError_InvalidUsage,
kVUID_PVError_InvalidUsage, false);
}
}
skip |= ValidateGreaterThanZero(pCreateInfo->extent.width, "pCreateInfo->extent.width",
"VUID-VkImageCreateInfo-extent-00944", log_misc);
skip |= ValidateGreaterThanZero(pCreateInfo->extent.height, "pCreateInfo->extent.height",
"VUID-VkImageCreateInfo-extent-00945", log_misc);
skip |= ValidateGreaterThanZero(pCreateInfo->extent.depth, "pCreateInfo->extent.depth",
"VUID-VkImageCreateInfo-extent-00946", log_misc);
skip |= ValidateGreaterThanZero(pCreateInfo->mipLevels, "pCreateInfo->mipLevels", "VUID-VkImageCreateInfo-mipLevels-00947",
log_misc);
skip |= ValidateGreaterThanZero(pCreateInfo->arrayLayers, "pCreateInfo->arrayLayers",
"VUID-VkImageCreateInfo-arrayLayers-00948", log_misc);
// InitialLayout must be PREINITIALIZED or UNDEFINED
if ((pCreateInfo->initialLayout != VK_IMAGE_LAYOUT_UNDEFINED) &&
(pCreateInfo->initialLayout != VK_IMAGE_LAYOUT_PREINITIALIZED)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-initialLayout-00993",
"vkCreateImage(): initialLayout is %s, must be VK_IMAGE_LAYOUT_UNDEFINED or VK_IMAGE_LAYOUT_PREINITIALIZED.",
string_VkImageLayout(pCreateInfo->initialLayout));
}
// If imageType is VK_IMAGE_TYPE_1D, both extent.height and extent.depth must be 1
if ((pCreateInfo->imageType == VK_IMAGE_TYPE_1D) &&
((pCreateInfo->extent.height != 1) || (pCreateInfo->extent.depth != 1))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00956",
"vkCreateImage(): if pCreateInfo->imageType is VK_IMAGE_TYPE_1D, both pCreateInfo->extent.height and "
"pCreateInfo->extent.depth must be 1.");
}
if (pCreateInfo->imageType == VK_IMAGE_TYPE_2D) {
if (pCreateInfo->flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) {
if (pCreateInfo->extent.width != pCreateInfo->extent.height) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
VK_NULL_HANDLE, "VUID-VkImageCreateInfo-imageType-00954",
"vkCreateImage(): pCreateInfo->flags contains VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, but "
"pCreateInfo->extent.width (=%" PRIu32 ") and pCreateInfo->extent.height (=%" PRIu32
") are not equal.",
pCreateInfo->extent.width, pCreateInfo->extent.height);
}
if (pCreateInfo->arrayLayers < 6) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
VK_NULL_HANDLE, "VUID-VkImageCreateInfo-imageType-00954",
"vkCreateImage(): pCreateInfo->flags contains VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, but "
"pCreateInfo->arrayLayers (=%" PRIu32 ") is not greater than or equal to 6.",
pCreateInfo->arrayLayers);
}
}
if (pCreateInfo->extent.depth != 1) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00957",
"vkCreateImage(): if pCreateInfo->imageType is VK_IMAGE_TYPE_2D, pCreateInfo->extent.depth must be 1.");
}
}
// 3D image may have only 1 layer
if ((pCreateInfo->imageType == VK_IMAGE_TYPE_3D) && (pCreateInfo->arrayLayers != 1)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00961",
"vkCreateImage(): if pCreateInfo->imageType is VK_IMAGE_TYPE_3D, pCreateInfo->arrayLayers must be 1.");
}
// If multi-sample, validate type, usage, tiling and mip levels.
if ((pCreateInfo->samples != VK_SAMPLE_COUNT_1_BIT) &&
((pCreateInfo->imageType != VK_IMAGE_TYPE_2D) || (pCreateInfo->flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) ||
(pCreateInfo->mipLevels != 1) || (pCreateInfo->tiling != VK_IMAGE_TILING_OPTIMAL))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-samples-02257",
"vkCreateImage(): Multi-sample image with incompatible type, usage, tiling, or mips.");
}
if (0 != (pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
VkImageUsageFlags legal_flags = (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT);
// At least one of the legal attachment bits must be set
if (0 == (pCreateInfo->usage & legal_flags)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-usage-00966",
"vkCreateImage(): Transient attachment image without a compatible attachment flag set.");
}
// No flags other than the legal attachment bits may be set
legal_flags |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
if (0 != (pCreateInfo->usage & ~legal_flags)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-usage-00963",
"vkCreateImage(): Transient attachment image with incompatible usage flags set.");
}
}
// mipLevels must be less than or equal to the number of levels in the complete mipmap chain
uint32_t maxDim = std::max(std::max(pCreateInfo->extent.width, pCreateInfo->extent.height), pCreateInfo->extent.depth);
// Max mip levels is different for corner-sampled images vs normal images.
uint32_t maxMipLevels = (pCreateInfo->flags & VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV) ? (uint32_t)(ceil(log2(maxDim)))
: (uint32_t)(floor(log2(maxDim)) + 1);
if (maxDim > 0 && pCreateInfo->mipLevels > maxMipLevels) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-mipLevels-00958",
"vkCreateImage(): pCreateInfo->mipLevels must be less than or equal to "
"floor(log2(max(pCreateInfo->extent.width, pCreateInfo->extent.height, pCreateInfo->extent.depth)))+1.");
}
if ((pCreateInfo->flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT) && (pCreateInfo->imageType != VK_IMAGE_TYPE_3D)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, VK_NULL_HANDLE,
"VUID-VkImageCreateInfo-flags-00950",
"vkCreateImage(): pCreateInfo->flags contains VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT but "
"pCreateInfo->imageType is not VK_IMAGE_TYPE_3D.");
}
if ((pCreateInfo->flags & VK_IMAGE_CREATE_SPARSE_BINDING_BIT) && (!physical_device_features.sparseBinding)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, VK_NULL_HANDLE,
"VUID-VkImageCreateInfo-flags-00969",
"vkCreateImage(): pCreateInfo->flags contains VK_IMAGE_CREATE_SPARSE_BINDING_BIT, but the "
"VkPhysicalDeviceFeatures::sparseBinding feature is disabled.");
}
// If flags contains VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT or VK_IMAGE_CREATE_SPARSE_ALIASED_BIT, it must also contain
// VK_IMAGE_CREATE_SPARSE_BINDING_BIT
if (((pCreateInfo->flags & (VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT)) != 0) &&
((pCreateInfo->flags & VK_IMAGE_CREATE_SPARSE_BINDING_BIT) != VK_IMAGE_CREATE_SPARSE_BINDING_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-flags-00987",
"vkCreateImage: if pCreateInfo->flags contains VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT or "
"VK_IMAGE_CREATE_SPARSE_ALIASED_BIT, it must also contain VK_IMAGE_CREATE_SPARSE_BINDING_BIT.");
}
// Check for combinations of attributes that are incompatible with having VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set
if ((pCreateInfo->flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) != 0) {
// Linear tiling is unsupported
if (VK_IMAGE_TILING_LINEAR == pCreateInfo->tiling) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_InvalidUsage,
"vkCreateImage: if pCreateInfo->flags contains VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT then image "
"tiling of VK_IMAGE_TILING_LINEAR is not supported");
}
// Sparse 1D image isn't valid
if (VK_IMAGE_TYPE_1D == pCreateInfo->imageType) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00970",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 1D image.");
}
// Sparse 2D image when device doesn't support it
if ((VK_FALSE == physical_device_features.sparseResidencyImage2D) && (VK_IMAGE_TYPE_2D == pCreateInfo->imageType)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00971",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 2D image if corresponding "
"feature is not enabled on the device.");
}
// Sparse 3D image when device doesn't support it
if ((VK_FALSE == physical_device_features.sparseResidencyImage3D) && (VK_IMAGE_TYPE_3D == pCreateInfo->imageType)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00972",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 3D image if corresponding "
"feature is not enabled on the device.");
}
// Multi-sample 2D image when device doesn't support it
if (VK_IMAGE_TYPE_2D == pCreateInfo->imageType) {
if ((VK_FALSE == physical_device_features.sparseResidency2Samples) &&
(VK_SAMPLE_COUNT_2_BIT == pCreateInfo->samples)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00973",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 2-sample image if "
"corresponding feature is not enabled on the device.");
} else if ((VK_FALSE == physical_device_features.sparseResidency4Samples) &&
(VK_SAMPLE_COUNT_4_BIT == pCreateInfo->samples)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00974",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 4-sample image if "
"corresponding feature is not enabled on the device.");
} else if ((VK_FALSE == physical_device_features.sparseResidency8Samples) &&
(VK_SAMPLE_COUNT_8_BIT == pCreateInfo->samples)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00975",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 8-sample image if "
"corresponding feature is not enabled on the device.");
} else if ((VK_FALSE == physical_device_features.sparseResidency16Samples) &&
(VK_SAMPLE_COUNT_16_BIT == pCreateInfo->samples)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-00976",
"vkCreateImage: cannot specify VK_IMAGE_CREATE_SPARSE_BINDING_BIT for 16-sample image if "
"corresponding feature is not enabled on the device.");
}
}
}
if (pCreateInfo->usage & VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV) {
if (pCreateInfo->imageType != VK_IMAGE_TYPE_2D) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-imageType-02082",
"vkCreateImage: if usage includes VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, "
"imageType must be VK_IMAGE_TYPE_2D.");
}
if (pCreateInfo->samples != VK_SAMPLE_COUNT_1_BIT) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-samples-02083",
"vkCreateImage: if usage includes VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, "
"samples must be VK_SAMPLE_COUNT_1_BIT.");
}
if (pCreateInfo->tiling != VK_IMAGE_TILING_OPTIMAL) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-tiling-02084",
"vkCreateImage: if usage includes VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, "
"tiling must be VK_IMAGE_TILING_OPTIMAL.");
}
}
if (pCreateInfo->flags & VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV) {
if (pCreateInfo->imageType != VK_IMAGE_TYPE_2D && pCreateInfo->imageType != VK_IMAGE_TYPE_3D) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-flags-02050",
"vkCreateImage: If flags contains VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV, "
"imageType must be VK_IMAGE_TYPE_2D or VK_IMAGE_TYPE_3D.");
}
if ((pCreateInfo->flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) || FormatIsDepthOrStencil(pCreateInfo->format)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-flags-02051",
"vkCreateImage: If flags contains VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV, "
"it must not also contain VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT and format must "
"not be a depth/stencil format.");
}
if (pCreateInfo->imageType == VK_IMAGE_TYPE_2D && (pCreateInfo->extent.width == 1 || pCreateInfo->extent.height == 1)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-flags-02052",
"vkCreateImage: If flags contains VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV and "
"imageType is VK_IMAGE_TYPE_2D, extent.width and extent.height must be "
"greater than 1.");
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_3D &&
(pCreateInfo->extent.width == 1 || pCreateInfo->extent.height == 1 || pCreateInfo->extent.depth == 1)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageCreateInfo-flags-02053",
"vkCreateImage: If flags contains VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV and "
"imageType is VK_IMAGE_TYPE_3D, extent.width, extent.height, and extent.depth "
"must be greater than 1.");
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkImageView *pView) {
bool skip = false;
if (pCreateInfo != nullptr) {
// Validate chained VkImageViewUsageCreateInfo struct, if present
if (nullptr != pCreateInfo->pNext) {
auto chained_ivuci_struct = lvl_find_in_chain<VkImageViewUsageCreateInfoKHR>(pCreateInfo->pNext);
if (chained_ivuci_struct) {
if (0 == chained_ivuci_struct->usage) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageViewUsageCreateInfo-usage-requiredbitmask",
"vkCreateImageView: Chained VkImageViewUsageCreateInfo usage field must not be 0.");
} else if (chained_ivuci_struct->usage & ~AllVkImageUsageFlagBits) {
std::stringstream ss;
ss << "vkCreateImageView: Chained VkImageViewUsageCreateInfo usage field (0x" << std::hex
<< chained_ivuci_struct->usage << ") contains invalid flag bits.";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageViewUsageCreateInfo-usage-parameter", "%s", ss.str().c_str());
}
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateViewport(const VkViewport &viewport, const char *fn_name, const char *param_name,
VkDebugReportObjectTypeEXT object_type, uint64_t object = 0) {
bool skip = false;
// Note: for numerical correctness
// - float comparisons should expect NaN (comparison always false).
// - VkPhysicalDeviceLimits::maxViewportDimensions is uint32_t, not float -> careful.
const auto f_lte_u32_exact = [](const float v1_f, const uint32_t v2_u32) {
if (std::isnan(v1_f)) return false;
if (v1_f <= 0.0f) return true;
float intpart;
const float fract = modff(v1_f, &intpart);
assert(std::numeric_limits<float>::radix == 2);
const float u32_max_plus1 = ldexpf(1.0f, 32); // hopefully exact
if (intpart >= u32_max_plus1) return false;
uint32_t v1_u32 = static_cast<uint32_t>(intpart);
if (v1_u32 < v2_u32)
return true;
else if (v1_u32 == v2_u32 && fract == 0.0f)
return true;
else
return false;
};
const auto f_lte_u32_direct = [](const float v1_f, const uint32_t v2_u32) {
const float v2_f = static_cast<float>(v2_u32); // not accurate for > radix^digits; and undefined rounding mode
return (v1_f <= v2_f);
};
// width
bool width_healthy = true;
const auto max_w = device_limits.maxViewportDimensions[0];
if (!(viewport.width > 0.0f)) {
width_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-width-01770",
"%s: %s.width (=%f) is not greater than 0.0.", fn_name, param_name, viewport.width);
} else if (!(f_lte_u32_exact(viewport.width, max_w) || f_lte_u32_direct(viewport.width, max_w))) {
width_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-width-01771",
"%s: %s.width (=%f) exceeds VkPhysicalDeviceLimits::maxViewportDimensions[0] (=%" PRIu32 ").", fn_name,
param_name, viewport.width, max_w);
} else if (!f_lte_u32_exact(viewport.width, max_w) && f_lte_u32_direct(viewport.width, max_w)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, object_type, object, kVUID_PVError_NONE,
"%s: %s.width (=%f) technically exceeds VkPhysicalDeviceLimits::maxViewportDimensions[0] (=%" PRIu32
"), but it is within the static_cast<float>(maxViewportDimensions[0]) limit.",
fn_name, param_name, viewport.width, max_w);
}
// height
bool height_healthy = true;
const bool negative_height_enabled = api_version >= VK_API_VERSION_1_1 || device_extensions.vk_khr_maintenance1 ||
device_extensions.vk_amd_negative_viewport_height;
const auto max_h = device_limits.maxViewportDimensions[1];
if (!negative_height_enabled && !(viewport.height > 0.0f)) {
height_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-height-01772",
"%s: %s.height (=%f) is not greater 0.0.", fn_name, param_name, viewport.height);
} else if (!(f_lte_u32_exact(fabsf(viewport.height), max_h) || f_lte_u32_direct(fabsf(viewport.height), max_h))) {
height_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-height-01773",
"%s: Absolute value of %s.height (=%f) exceeds VkPhysicalDeviceLimits::maxViewportDimensions[1] (=%" PRIu32
").",
fn_name, param_name, viewport.height, max_h);
} else if (!f_lte_u32_exact(fabsf(viewport.height), max_h) && f_lte_u32_direct(fabsf(viewport.height), max_h)) {
height_healthy = false;
skip |= log_msg(
report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, object_type, object, kVUID_PVError_NONE,
"%s: Absolute value of %s.height (=%f) technically exceeds VkPhysicalDeviceLimits::maxViewportDimensions[1] (=%" PRIu32
"), but it is within the static_cast<float>(maxViewportDimensions[1]) limit.",
fn_name, param_name, viewport.height, max_h);
}
// x
bool x_healthy = true;
if (!(viewport.x >= device_limits.viewportBoundsRange[0])) {
x_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-x-01774",
"%s: %s.x (=%f) is less than VkPhysicalDeviceLimits::viewportBoundsRange[0] (=%f).", fn_name, param_name,
viewport.x, device_limits.viewportBoundsRange[0]);
}
// x + width
if (x_healthy && width_healthy) {
const float right_bound = viewport.x + viewport.width;
if (!(right_bound <= device_limits.viewportBoundsRange[1])) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-x-01232",
"%s: %s.x + %s.width (=%f + %f = %f) is greater than VkPhysicalDeviceLimits::viewportBoundsRange[1] (=%f).",
fn_name, param_name, param_name, viewport.x, viewport.width, right_bound, device_limits.viewportBoundsRange[1]);
}
}
// y
bool y_healthy = true;
if (!(viewport.y >= device_limits.viewportBoundsRange[0])) {
y_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-y-01775",
"%s: %s.y (=%f) is less than VkPhysicalDeviceLimits::viewportBoundsRange[0] (=%f).", fn_name, param_name,
viewport.y, device_limits.viewportBoundsRange[0]);
} else if (negative_height_enabled && !(viewport.y <= device_limits.viewportBoundsRange[1])) {
y_healthy = false;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-y-01776",
"%s: %s.y (=%f) exceeds VkPhysicalDeviceLimits::viewportBoundsRange[1] (=%f).", fn_name, param_name,
viewport.y, device_limits.viewportBoundsRange[1]);
}
// y + height
if (y_healthy && height_healthy) {
const float boundary = viewport.y + viewport.height;
if (!(boundary <= device_limits.viewportBoundsRange[1])) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-y-01233",
"%s: %s.y + %s.height (=%f + %f = %f) exceeds VkPhysicalDeviceLimits::viewportBoundsRange[1] (=%f).",
fn_name, param_name, param_name, viewport.y, viewport.height, boundary,
device_limits.viewportBoundsRange[1]);
} else if (negative_height_enabled && !(boundary >= device_limits.viewportBoundsRange[0])) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-y-01777",
"%s: %s.y + %s.height (=%f + %f = %f) is less than VkPhysicalDeviceLimits::viewportBoundsRange[0] (=%f).", fn_name,
param_name, param_name, viewport.y, viewport.height, boundary, device_limits.viewportBoundsRange[0]);
}
}
if (!device_extensions.vk_ext_depth_range_unrestricted) {
// minDepth
if (!(viewport.minDepth >= 0.0) || !(viewport.minDepth <= 1.0)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-minDepth-01234",
"%s: VK_EXT_depth_range_unrestricted extension is not enabled and %s.minDepth (=%f) is not within the "
"[0.0, 1.0] range.",
fn_name, param_name, viewport.minDepth);
}
// maxDepth
if (!(viewport.maxDepth >= 0.0) || !(viewport.maxDepth <= 1.0)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object, "VUID-VkViewport-maxDepth-01235",
"%s: VK_EXT_depth_range_unrestricted extension is not enabled and %s.maxDepth (=%f) is not within the "
"[0.0, 1.0] range.",
fn_name, param_name, viewport.maxDepth);
}
}
return skip;
}
struct SampleOrderInfo {
VkShadingRatePaletteEntryNV shadingRate;
uint32_t width;
uint32_t height;
};
// All palette entries with more than one pixel per fragment
static SampleOrderInfo sampleOrderInfos[] = {
{VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, 1, 2},
{VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV, 2, 1},
{VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV, 2, 2},
{VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV, 4, 2},
{VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV, 2, 4},
{VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV, 4, 4},
};
bool StatelessValidation::ValidateCoarseSampleOrderCustomNV(const VkCoarseSampleOrderCustomNV *order) {
bool skip = false;
SampleOrderInfo *sampleOrderInfo;
uint32_t infoIdx = 0;
for (sampleOrderInfo = nullptr; infoIdx < ARRAY_SIZE(sampleOrderInfos); ++infoIdx) {
if (sampleOrderInfos[infoIdx].shadingRate == order->shadingRate) {
sampleOrderInfo = &sampleOrderInfos[infoIdx];
break;
}
}
if (sampleOrderInfo == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleOrderCustomNV-shadingRate-02073",
"VkCoarseSampleOrderCustomNV shadingRate must be a shading rate "
"that generates fragments with more than one pixel.");
return skip;
}
if (order->sampleCount == 0 || (order->sampleCount & (order->sampleCount - 1)) ||
!(order->sampleCount & device_limits.framebufferNoAttachmentsSampleCounts)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleOrderCustomNV-sampleCount-02074",
"VkCoarseSampleOrderCustomNV sampleCount (=%" PRIu32
") must "
"correspond to a sample count enumerated in VkSampleCountFlags whose corresponding bit "
"is set in framebufferNoAttachmentsSampleCounts.",
order->sampleCount);
}
if (order->sampleLocationCount != order->sampleCount * sampleOrderInfo->width * sampleOrderInfo->height) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02075",
"VkCoarseSampleOrderCustomNV sampleLocationCount (=%" PRIu32
") must "
"be equal to the product of sampleCount (=%" PRIu32
"), the fragment width for shadingRate "
"(=%" PRIu32 "), and the fragment height for shadingRate (=%" PRIu32 ").",
order->sampleLocationCount, order->sampleCount, sampleOrderInfo->width, sampleOrderInfo->height);
}
if (order->sampleLocationCount > phys_dev_ext_props.shading_rate_image_props.shadingRateMaxCoarseSamples) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02076",
"VkCoarseSampleOrderCustomNV sampleLocationCount (=%" PRIu32
") must "
"be less than or equal to VkPhysicalDeviceShadingRateImagePropertiesNV shadingRateMaxCoarseSamples (=%" PRIu32 ").",
order->sampleLocationCount, phys_dev_ext_props.shading_rate_image_props.shadingRateMaxCoarseSamples);
}
// Accumulate a bitmask tracking which (x,y,sample) tuples are seen. Expect
// the first width*height*sampleCount bits to all be set. Note: There is no
// guarantee that 64 bits is enough, but practically it's unlikely for an
// implementation to support more than 32 bits for samplemask.
assert(phys_dev_ext_props.shading_rate_image_props.shadingRateMaxCoarseSamples <= 64);
uint64_t sampleLocationsMask = 0;
for (uint32_t i = 0; i < order->sampleLocationCount; ++i) {
const VkCoarseSampleLocationNV *sampleLoc = &order->pSampleLocations[i];
if (sampleLoc->pixelX >= sampleOrderInfo->width) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleLocationNV-pixelX-02078",
"pixelX must be less than the width (in pixels) of the fragment.");
}
if (sampleLoc->pixelY >= sampleOrderInfo->height) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleLocationNV-pixelY-02079",
"pixelY must be less than the height (in pixels) of the fragment.");
}
if (sampleLoc->sample >= order->sampleCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleLocationNV-sample-02080",
"sample must be less than the number of coverage samples in each pixel belonging to the fragment.");
}
uint32_t idx = sampleLoc->sample + order->sampleCount * (sampleLoc->pixelX + sampleOrderInfo->width * sampleLoc->pixelY);
sampleLocationsMask |= 1ULL << idx;
}
uint64_t expectedMask = (order->sampleLocationCount == 64) ? ~0ULL : ((1ULL << order->sampleLocationCount) - 1);
if (sampleLocationsMask != expectedMask) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkCoarseSampleOrderCustomNV-pSampleLocations-02077",
"The array pSampleLocations must contain exactly one entry for "
"every combination of valid values for pixelX, pixelY, and sample in the structure VkCoarseSampleOrderCustomNV.");
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines) {
bool skip = false;
if (pCreateInfos != nullptr) {
for (uint32_t i = 0; i < createInfoCount; ++i) {
bool has_dynamic_viewport = false;
bool has_dynamic_scissor = false;
bool has_dynamic_line_width = false;
bool has_dynamic_viewport_w_scaling_nv = false;
bool has_dynamic_discard_rectangle_ext = false;
bool has_dynamic_sample_locations_ext = false;
bool has_dynamic_exclusive_scissor_nv = false;
bool has_dynamic_shading_rate_palette_nv = false;
if (pCreateInfos[i].pDynamicState != nullptr) {
const auto &dynamic_state_info = *pCreateInfos[i].pDynamicState;
for (uint32_t state_index = 0; state_index < dynamic_state_info.dynamicStateCount; ++state_index) {
const auto &dynamic_state = dynamic_state_info.pDynamicStates[state_index];
if (dynamic_state == VK_DYNAMIC_STATE_VIEWPORT) has_dynamic_viewport = true;
if (dynamic_state == VK_DYNAMIC_STATE_SCISSOR) has_dynamic_scissor = true;
if (dynamic_state == VK_DYNAMIC_STATE_LINE_WIDTH) has_dynamic_line_width = true;
if (dynamic_state == VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV) has_dynamic_viewport_w_scaling_nv = true;
if (dynamic_state == VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT) has_dynamic_discard_rectangle_ext = true;
if (dynamic_state == VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT) has_dynamic_sample_locations_ext = true;
if (dynamic_state == VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV) has_dynamic_exclusive_scissor_nv = true;
if (dynamic_state == VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV)
has_dynamic_shading_rate_palette_nv = true;
}
}
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if (pCreateInfos[i].pVertexInputState != nullptr) {
auto const &vertex_input_state = pCreateInfos[i].pVertexInputState;
if (vertex_input_state->vertexBindingDescriptionCount > device_limits.maxVertexInputBindings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineVertexInputStateCreateInfo-vertexBindingDescriptionCount-00613",
"vkCreateGraphicsPipelines: pararameter "
"pCreateInfo[%d].pVertexInputState->vertexBindingDescriptionCount (%u) is "
"greater than VkPhysicalDeviceLimits::maxVertexInputBindings (%u).",
i, vertex_input_state->vertexBindingDescriptionCount, device_limits.maxVertexInputBindings);
}
if (vertex_input_state->vertexAttributeDescriptionCount > device_limits.maxVertexInputAttributes) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineVertexInputStateCreateInfo-vertexAttributeDescriptionCount-00614",
"vkCreateGraphicsPipelines: pararameter "
"pCreateInfo[%d].pVertexInputState->vertexAttributeDescriptionCount (%u) is "
"greater than VkPhysicalDeviceLimits::maxVertexInputAttributes (%u).",
i, vertex_input_state->vertexBindingDescriptionCount, device_limits.maxVertexInputAttributes);
}
std::unordered_set<uint32_t> vertex_bindings(vertex_input_state->vertexBindingDescriptionCount);
for (uint32_t d = 0; d < vertex_input_state->vertexBindingDescriptionCount; ++d) {
auto const &vertex_bind_desc = vertex_input_state->pVertexBindingDescriptions[d];
auto const &binding_it = vertex_bindings.find(vertex_bind_desc.binding);
if (binding_it != vertex_bindings.cend()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineVertexInputStateCreateInfo-pVertexBindingDescriptions-00616",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfo[%d].pVertexInputState->pVertexBindingDescription[%d].binding "
"(%" PRIu32 ") is not distinct.",
i, d, vertex_bind_desc.binding);
}
vertex_bindings.insert(vertex_bind_desc.binding);
if (vertex_bind_desc.binding >= device_limits.maxVertexInputBindings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkVertexInputBindingDescription-binding-00618",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfos[%u].pVertexInputState->pVertexBindingDescriptions[%u].binding (%u) is "
"greater than or equal to VkPhysicalDeviceLimits::maxVertexInputBindings (%u).",
i, d, vertex_bind_desc.binding, device_limits.maxVertexInputBindings);
}
if (vertex_bind_desc.stride > device_limits.maxVertexInputBindingStride) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkVertexInputBindingDescription-stride-00619",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfos[%u].pVertexInputState->pVertexBindingDescriptions[%u].stride (%u) is greater "
"than VkPhysicalDeviceLimits::maxVertexInputBindingStride (%u).",
i, d, vertex_bind_desc.stride, device_limits.maxVertexInputBindingStride);
}
}
std::unordered_set<uint32_t> attribute_locations(vertex_input_state->vertexAttributeDescriptionCount);
for (uint32_t d = 0; d < vertex_input_state->vertexAttributeDescriptionCount; ++d) {
auto const &vertex_attrib_desc = vertex_input_state->pVertexAttributeDescriptions[d];
auto const &location_it = attribute_locations.find(vertex_attrib_desc.location);
if (location_it != attribute_locations.cend()) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineVertexInputStateCreateInfo-pVertexAttributeDescriptions-00617",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfo[%d].pVertexInputState->vertexAttributeDescriptions[%d].location (%u) is not distinct.",
i, d, vertex_attrib_desc.location);
}
attribute_locations.insert(vertex_attrib_desc.location);
auto const &binding_it = vertex_bindings.find(vertex_attrib_desc.binding);
if (binding_it == vertex_bindings.cend()) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineVertexInputStateCreateInfo-binding-00615",
"vkCreateGraphicsPipelines: parameter "
" pCreateInfo[%d].pVertexInputState->vertexAttributeDescriptions[%d].binding (%u) does not exist "
"in any pCreateInfo[%d].pVertexInputState->pVertexBindingDescription.",
i, d, vertex_attrib_desc.binding, i);
}
if (vertex_attrib_desc.location >= device_limits.maxVertexInputAttributes) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkVertexInputAttributeDescription-location-00620",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfos[%u].pVertexInputState->pVertexAttributeDescriptions[%u].location (%u) is "
"greater than or equal to VkPhysicalDeviceLimits::maxVertexInputAttributes (%u).",
i, d, vertex_attrib_desc.location, device_limits.maxVertexInputAttributes);
}
if (vertex_attrib_desc.binding >= device_limits.maxVertexInputBindings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkVertexInputAttributeDescription-binding-00621",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfos[%u].pVertexInputState->pVertexAttributeDescriptions[%u].binding (%u) is "
"greater than or equal to VkPhysicalDeviceLimits::maxVertexInputBindings (%u).",
i, d, vertex_attrib_desc.binding, device_limits.maxVertexInputBindings);
}
if (vertex_attrib_desc.offset > device_limits.maxVertexInputAttributeOffset) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkVertexInputAttributeDescription-offset-00622",
"vkCreateGraphicsPipelines: parameter "
"pCreateInfos[%u].pVertexInputState->pVertexAttributeDescriptions[%u].offset (%u) is "
"greater than VkPhysicalDeviceLimits::maxVertexInputAttributeOffset (%u).",
i, d, vertex_attrib_desc.offset, device_limits.maxVertexInputAttributeOffset);
}
}
}
if (pCreateInfos[i].pStages != nullptr) {
bool has_control = false;
bool has_eval = false;
for (uint32_t stage_index = 0; stage_index < pCreateInfos[i].stageCount; ++stage_index) {
if (pCreateInfos[i].pStages[stage_index].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
has_control = true;
} else if (pCreateInfos[i].pStages[stage_index].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
has_eval = true;
}
}
// pTessellationState is ignored without both tessellation control and tessellation evaluation shaders stages
if (has_control && has_eval) {
if (pCreateInfos[i].pTessellationState == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkGraphicsPipelineCreateInfo-pStages-00731",
"vkCreateGraphicsPipelines: if pCreateInfos[%d].pStages includes a tessellation control "
"shader stage and a tessellation evaluation shader stage, "
"pCreateInfos[%d].pTessellationState must not be NULL.",
i, i);
} else {
skip |= validate_struct_pnext(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pTessellationState->pNext", ParameterName::IndexVector{i}), NULL,
pCreateInfos[i].pTessellationState->pNext, 0, NULL, GeneratedVulkanHeaderVersion,
"VUID-VkGraphicsPipelineCreateInfo-pNext-pNext");
skip |= validate_reserved_flags(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pTessellationState->flags", ParameterName::IndexVector{i}),
pCreateInfos[i].pTessellationState->flags,
"VUID-VkPipelineTessellationStateCreateInfo-flags-zerobitmask");
if (pCreateInfos[i].pTessellationState->sType !=
VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineTessellationStateCreateInfo-sType-sType",
"vkCreateGraphicsPipelines: parameter pCreateInfos[%d].pTessellationState->sType must "
"be VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO.",
i);
}
if (pCreateInfos[i].pTessellationState->patchControlPoints == 0 ||
pCreateInfos[i].pTessellationState->patchControlPoints > device_limits.maxTessellationPatchSize) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineTessellationStateCreateInfo-patchControlPoints-01214",
"vkCreateGraphicsPipelines: invalid parameter "
"pCreateInfos[%d].pTessellationState->patchControlPoints value %u. patchControlPoints "
"should be >0 and <=%u.",
i, pCreateInfos[i].pTessellationState->patchControlPoints,
device_limits.maxTessellationPatchSize);
}
}
}
}
// pViewportState, pMultisampleState, pDepthStencilState, and pColorBlendState ignored when rasterization is disabled
if ((pCreateInfos[i].pRasterizationState != nullptr) &&
(pCreateInfos[i].pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) {
if (pCreateInfos[i].pViewportState == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00750",
"vkCreateGraphicsPipelines: Rasterization is enabled (pCreateInfos[%" PRIu32
"].pRasterizationState->rasterizerDiscardEnable is VK_FALSE), but pCreateInfos[%" PRIu32
"].pViewportState (=NULL) is not a valid pointer.",
i, i);
} else {
const auto &viewport_state = *pCreateInfos[i].pViewportState;
if (viewport_state.sType != VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-sType-sType",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pViewportState->sType is not VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO.",
i);
}
const VkStructureType allowed_structs_VkPipelineViewportStateCreateInfo[] = {
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SWIZZLE_STATE_CREATE_INFO_NV,
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV,
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV,
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV,
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV,
};
skip |= validate_struct_pnext(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pViewportState->pNext", ParameterName::IndexVector{i}),
"VkPipelineViewportSwizzleStateCreateInfoNV, VkPipelineViewportWScalingStateCreateInfoNV, "
"VkPipelineViewportExclusiveScissorStateCreateInfoNV, VkPipelineViewportShadingRateImageStateCreateInfoNV, "
"VkPipelineViewportCoarseSampleOrderStateCreateInfoNV",
viewport_state.pNext, ARRAY_SIZE(allowed_structs_VkPipelineViewportStateCreateInfo),
allowed_structs_VkPipelineViewportStateCreateInfo, 65,
"VUID-VkPipelineViewportStateCreateInfo-pNext-pNext");
skip |= validate_reserved_flags(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pViewportState->flags", ParameterName::IndexVector{i}),
viewport_state.flags, "VUID-VkPipelineViewportStateCreateInfo-flags-zerobitmask");
auto exclusive_scissor_struct = lvl_find_in_chain<VkPipelineViewportExclusiveScissorStateCreateInfoNV>(
pCreateInfos[i].pViewportState->pNext);
auto shading_rate_image_struct = lvl_find_in_chain<VkPipelineViewportShadingRateImageStateCreateInfoNV>(
pCreateInfos[i].pViewportState->pNext);
auto coarse_sample_order_struct = lvl_find_in_chain<VkPipelineViewportCoarseSampleOrderStateCreateInfoNV>(
pCreateInfos[i].pViewportState->pNext);
const auto vp_swizzle_struct =
lvl_find_in_chain<VkPipelineViewportSwizzleStateCreateInfoNV>(pCreateInfos[i].pViewportState->pNext);
if (!physical_device_features.multiViewport) {
if (viewport_state.viewportCount != 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-viewportCount-01216",
"vkCreateGraphicsPipelines: The VkPhysicalDeviceFeatures::multiViewport feature is "
"disabled, but pCreateInfos[%" PRIu32 "].pViewportState->viewportCount (=%" PRIu32
") is not 1.",
i, viewport_state.viewportCount);
}
if (viewport_state.scissorCount != 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-scissorCount-01217",
"vkCreateGraphicsPipelines: The VkPhysicalDeviceFeatures::multiViewport feature is "
"disabled, but pCreateInfos[%" PRIu32 "].pViewportState->scissorCount (=%" PRIu32
") is not 1.",
i, viewport_state.scissorCount);
}
if (exclusive_scissor_struct && (exclusive_scissor_struct->exclusiveScissorCount != 0 &&
exclusive_scissor_struct->exclusiveScissorCount != 1)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE,
"VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-exclusiveScissorCount-02027",
"vkCreateGraphicsPipelines: The VkPhysicalDeviceFeatures::multiViewport feature is "
"disabled, but pCreateInfos[%" PRIu32
"] VkPipelineViewportExclusiveScissorStateCreateInfoNV::exclusiveScissorCount (=%" PRIu32
") is not 1.",
i, exclusive_scissor_struct->exclusiveScissorCount);
}
if (shading_rate_image_struct &&
(shading_rate_image_struct->viewportCount != 0 && shading_rate_image_struct->viewportCount != 1)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE,
"VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-viewportCount-02054",
"vkCreateGraphicsPipelines: The VkPhysicalDeviceFeatures::multiViewport feature is "
"disabled, but pCreateInfos[%" PRIu32
"] VkPipelineViewportShadingRateImageStateCreateInfoNV::viewportCount (=%" PRIu32
") is neither 0 nor 1.",
i, shading_rate_image_struct->viewportCount);
}
} else { // multiViewport enabled
if (viewport_state.viewportCount == 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-viewportCount-arraylength",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32 "].pViewportState->viewportCount is 0.", i);
} else if (viewport_state.viewportCount > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-viewportCount-01218",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pViewportState->viewportCount (=%" PRIu32
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
i, viewport_state.viewportCount, device_limits.maxViewports);
}
if (viewport_state.scissorCount == 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-scissorCount-arraylength",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32 "].pViewportState->scissorCount is 0.", i);
} else if (viewport_state.scissorCount > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-scissorCount-01219",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pViewportState->scissorCount (=%" PRIu32
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
i, viewport_state.scissorCount, device_limits.maxViewports);
}
}
if (exclusive_scissor_struct && exclusive_scissor_struct->exclusiveScissorCount > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE,
"VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-exclusiveScissorCount-02028",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32 "] exclusiveScissorCount (=%" PRIu32
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
i, exclusive_scissor_struct->exclusiveScissorCount, device_limits.maxViewports);
}
if (shading_rate_image_struct && shading_rate_image_struct->viewportCount > device_limits.maxViewports) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-viewportCount-02055",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"] VkPipelineViewportShadingRateImageStateCreateInfoNV viewportCount (=%" PRIu32
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
i, shading_rate_image_struct->viewportCount, device_limits.maxViewports);
}
if (viewport_state.scissorCount != viewport_state.viewportCount) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportStateCreateInfo-scissorCount-01220",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32 "].pViewportState->scissorCount (=%" PRIu32
") is not identical to pCreateInfos[%" PRIu32 "].pViewportState->viewportCount (=%" PRIu32 ").",
i, viewport_state.scissorCount, i, viewport_state.viewportCount);
}
if (exclusive_scissor_struct && exclusive_scissor_struct->exclusiveScissorCount != 0 &&
exclusive_scissor_struct->exclusiveScissorCount != viewport_state.viewportCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE,
"VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-exclusiveScissorCount-02029",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32 "] exclusiveScissorCount (=%" PRIu32
") must be zero or identical to pCreateInfos[%" PRIu32
"].pViewportState->viewportCount (=%" PRIu32 ").",
i, exclusive_scissor_struct->exclusiveScissorCount, i, viewport_state.viewportCount);
}
if (shading_rate_image_struct && shading_rate_image_struct->shadingRateImageEnable &&
shading_rate_image_struct->viewportCount != viewport_state.viewportCount) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, VK_NULL_HANDLE,
"VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-shadingRateImageEnable-02056",
"vkCreateGraphicsPipelines: If shadingRateImageEnable is enabled, pCreateInfos[%" PRIu32
"] "
"VkPipelineViewportShadingRateImageStateCreateInfoNV viewportCount (=%" PRIu32
") must identical to pCreateInfos[%" PRIu32 "].pViewportState->viewportCount (=%" PRIu32 ").",
i, shading_rate_image_struct->viewportCount, i, viewport_state.viewportCount);
}
if (!has_dynamic_viewport && viewport_state.viewportCount > 0 && viewport_state.pViewports == nullptr) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, VK_NULL_HANDLE,
"VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-00747",
"vkCreateGraphicsPipelines: The viewport state is static (pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates does not contain VK_DYNAMIC_STATE_VIEWPORT), but pCreateInfos[%" PRIu32
"].pViewportState->pViewports (=NULL) is an invalid pointer.",
i, i);
}
if (!has_dynamic_scissor && viewport_state.scissorCount > 0 && viewport_state.pScissors == nullptr) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, VK_NULL_HANDLE,
"VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-00748",
"vkCreateGraphicsPipelines: The scissor state is static (pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates does not contain VK_DYNAMIC_STATE_SCISSOR), but pCreateInfos[%" PRIu32
"].pViewportState->pScissors (=NULL) is an invalid pointer.",
i, i);
}
if (!has_dynamic_exclusive_scissor_nv && exclusive_scissor_struct &&
exclusive_scissor_struct->exclusiveScissorCount > 0 &&
exclusive_scissor_struct->pExclusiveScissors == nullptr) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-pDynamicStates-02030",
"vkCreateGraphicsPipelines: The exclusive scissor state is static (pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates does not contain VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV), but "
"pCreateInfos[%" PRIu32 "] pExclusiveScissors (=NULL) is an invalid pointer.",
i, i);
}
if (!has_dynamic_shading_rate_palette_nv && shading_rate_image_struct &&
shading_rate_image_struct->viewportCount > 0 &&
shading_rate_image_struct->pShadingRatePalettes == nullptr) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, VK_NULL_HANDLE,
"VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-pDynamicStates-02057",
"vkCreateGraphicsPipelines: The shading rate palette state is static (pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates does not contain VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV), "
"but pCreateInfos[%" PRIu32 "] pShadingRatePalettes (=NULL) is an invalid pointer.",
i, i);
}
if (vp_swizzle_struct) {
if (vp_swizzle_struct->viewportCount != viewport_state.viewportCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, "VUID-VkPipelineViewportSwizzleStateCreateInfoNV-viewportCount-01215",
"vkCreateGraphicsPipelines: The viewport swizzle state vieport count of %" PRIu32
" does "
"not match the viewport count of %" PRIu32 " in VkPipelineViewportStateCreateInfo.",
vp_swizzle_struct->viewportCount, viewport_state.viewportCount);
}
}
// validate the VkViewports
if (!has_dynamic_viewport && viewport_state.pViewports) {
for (uint32_t viewport_i = 0; viewport_i < viewport_state.viewportCount; ++viewport_i) {
const auto &viewport = viewport_state.pViewports[viewport_i]; // will crash on invalid ptr
const char fn_name[] = "vkCreateGraphicsPipelines";
const std::string param_name = "pCreateInfos[" + std::to_string(i) + "].pViewportState->pViewports[" +
std::to_string(viewport_i) + "]";
skip |= manual_PreCallValidateViewport(viewport, fn_name, param_name.c_str(),
VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT);
}
}
if (has_dynamic_viewport_w_scaling_nv && !device_extensions.vk_nv_clip_space_w_scaling) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, kVUID_PVError_ExtensionNotEnabled,
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates contains VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV, but "
"VK_NV_clip_space_w_scaling extension is not enabled.",
i);
}
if (has_dynamic_discard_rectangle_ext && !device_extensions.vk_ext_discard_rectangles) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, kVUID_PVError_ExtensionNotEnabled,
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates contains VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT, but "
"VK_EXT_discard_rectangles extension is not enabled.",
i);
}
if (has_dynamic_sample_locations_ext && !device_extensions.vk_ext_sample_locations) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, kVUID_PVError_ExtensionNotEnabled,
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates contains VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT, but "
"VK_EXT_sample_locations extension is not enabled.",
i);
}
if (has_dynamic_exclusive_scissor_nv && !device_extensions.vk_nv_scissor_exclusive) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE, kVUID_PVError_ExtensionNotEnabled,
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates contains VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV, but "
"VK_NV_scissor_exclusive extension is not enabled.",
i);
}
if (coarse_sample_order_struct &&
coarse_sample_order_struct->sampleOrderType != VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV &&
coarse_sample_order_struct->customSampleOrderCount != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
VK_NULL_HANDLE,
"VUID-VkPipelineViewportCoarseSampleOrderStateCreateInfoNV-sampleOrderType-02072",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
"] "
"VkPipelineViewportCoarseSampleOrderStateCreateInfoNV sampleOrderType is not "
"VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV and customSampleOrderCount is not 0.",
i);
}
if (coarse_sample_order_struct) {
for (uint32_t order_i = 0; order_i < coarse_sample_order_struct->customSampleOrderCount; ++order_i) {
skip |= ValidateCoarseSampleOrderCustomNV(&coarse_sample_order_struct->pCustomSampleOrders[order_i]);
}
}
}
if (pCreateInfos[i].pMultisampleState == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00751",
"vkCreateGraphicsPipelines: if pCreateInfos[%d].pRasterizationState->rasterizerDiscardEnable "
"is VK_FALSE, pCreateInfos[%d].pMultisampleState must not be NULL.",
i, i);
} else {
const VkStructureType valid_next_stypes[] = {LvlTypeMap<VkPipelineCoverageModulationStateCreateInfoNV>::kSType,
LvlTypeMap<VkPipelineCoverageToColorStateCreateInfoNV>::kSType,
LvlTypeMap<VkPipelineSampleLocationsStateCreateInfoEXT>::kSType};
const char *valid_struct_names =
"VkPipelineCoverageModulationStateCreateInfoNV, VkPipelineCoverageToColorStateCreateInfoNV, "
"VkPipelineSampleLocationsStateCreateInfoEXT";
skip |= validate_struct_pnext(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pMultisampleState->pNext", ParameterName::IndexVector{i}),
valid_struct_names, pCreateInfos[i].pMultisampleState->pNext, 3, valid_next_stypes,
GeneratedVulkanHeaderVersion, "VUID-VkPipelineMultisampleStateCreateInfo-pNext-pNext");
skip |= validate_reserved_flags(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pMultisampleState->flags", ParameterName::IndexVector{i}),
pCreateInfos[i].pMultisampleState->flags, "VUID-VkPipelineMultisampleStateCreateInfo-flags-zerobitmask");
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pMultisampleState->sampleShadingEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pMultisampleState->sampleShadingEnable);
skip |= validate_array(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pMultisampleState->rasterizationSamples", ParameterName::IndexVector{i}),
ParameterName("pCreateInfos[%i].pMultisampleState->pSampleMask", ParameterName::IndexVector{i}),
pCreateInfos[i].pMultisampleState->rasterizationSamples, &pCreateInfos[i].pMultisampleState->pSampleMask,
true, false, kVUIDUndefined, kVUIDUndefined);
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pMultisampleState->alphaToCoverageEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pMultisampleState->alphaToCoverageEnable);
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pMultisampleState->alphaToOneEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pMultisampleState->alphaToOneEnable);
if (pCreateInfos[i].pMultisampleState->sType != VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_InvalidStructSType,
"vkCreateGraphicsPipelines: parameter pCreateInfos[%d].pMultisampleState->sType must be "
"VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO",
i);
}
if (pCreateInfos[i].pMultisampleState->sampleShadingEnable == VK_TRUE) {
if (!physical_device_features.sampleRateShading) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineMultisampleStateCreateInfo-sampleShadingEnable-00784",
"vkCreateGraphicsPipelines(): parameter "
"pCreateInfos[%d].pMultisampleState->sampleShadingEnable.",
i);
}
// TODO Add documentation issue about when minSampleShading must be in range and when it is ignored
// For now a "least noise" test *only* when sampleShadingEnable is VK_TRUE.
if (!in_inclusive_range(pCreateInfos[i].pMultisampleState->minSampleShading, 0.F, 1.0F)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineMultisampleStateCreateInfo-minSampleShading-00786",
"vkCreateGraphicsPipelines(): parameter pCreateInfos[%d].pMultisampleState->minSampleShading.", i);
}
}
}
bool uses_color_attachment = false;
bool uses_depthstencil_attachment = false;
{
const auto subpasses_uses_it = renderpasses_states.find(pCreateInfos[i].renderPass);
if (subpasses_uses_it != renderpasses_states.end()) {
const auto &subpasses_uses = subpasses_uses_it->second;
if (subpasses_uses.subpasses_using_color_attachment.count(pCreateInfos[i].subpass))
uses_color_attachment = true;
if (subpasses_uses.subpasses_using_depthstencil_attachment.count(pCreateInfos[i].subpass))
uses_depthstencil_attachment = true;
}
}
if (pCreateInfos[i].pDepthStencilState != nullptr && uses_depthstencil_attachment) {
skip |= validate_struct_pnext(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->pNext", ParameterName::IndexVector{i}), NULL,
pCreateInfos[i].pDepthStencilState->pNext, 0, NULL, GeneratedVulkanHeaderVersion,
"VUID-VkPipelineDepthStencilStateCreateInfo-pNext-pNext");
skip |= validate_reserved_flags(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->flags", ParameterName::IndexVector{i}),
pCreateInfos[i].pDepthStencilState->flags, "VUID-VkPipelineDepthStencilStateCreateInfo-flags-zerobitmask");
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->depthTestEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pDepthStencilState->depthTestEnable);
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->depthWriteEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pDepthStencilState->depthWriteEnable);
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->depthCompareOp", ParameterName::IndexVector{i}),
"VkCompareOp", AllVkCompareOpEnums, pCreateInfos[i].pDepthStencilState->depthCompareOp,
"VUID-VkPipelineDepthStencilStateCreateInfo-depthCompareOp-parameter");
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->depthBoundsTestEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pDepthStencilState->depthBoundsTestEnable);
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->stencilTestEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pDepthStencilState->stencilTestEnable);
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->front.failOp", ParameterName::IndexVector{i}),
"VkStencilOp", AllVkStencilOpEnums, pCreateInfos[i].pDepthStencilState->front.failOp,
"VUID-VkStencilOpState-failOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->front.passOp", ParameterName::IndexVector{i}),
"VkStencilOp", AllVkStencilOpEnums, pCreateInfos[i].pDepthStencilState->front.passOp,
"VUID-VkStencilOpState-passOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->front.depthFailOp", ParameterName::IndexVector{i}),
"VkStencilOp", AllVkStencilOpEnums, pCreateInfos[i].pDepthStencilState->front.depthFailOp,
"VUID-VkStencilOpState-depthFailOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->front.compareOp", ParameterName::IndexVector{i}),
"VkCompareOp", AllVkCompareOpEnums, pCreateInfos[i].pDepthStencilState->front.compareOp,
"VUID-VkPipelineDepthStencilStateCreateInfo-depthCompareOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->back.failOp", ParameterName::IndexVector{i}),
"VkStencilOp", AllVkStencilOpEnums, pCreateInfos[i].pDepthStencilState->back.failOp,
"VUID-VkStencilOpState-failOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->back.passOp", ParameterName::IndexVector{i}),
"VkStencilOp", AllVkStencilOpEnums, pCreateInfos[i].pDepthStencilState->back.passOp,
"VUID-VkStencilOpState-passOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->back.depthFailOp", ParameterName::IndexVector{i}),
"VkStencilOp", AllVkStencilOpEnums, pCreateInfos[i].pDepthStencilState->back.depthFailOp,
"VUID-VkStencilOpState-depthFailOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pDepthStencilState->back.compareOp", ParameterName::IndexVector{i}),
"VkCompareOp", AllVkCompareOpEnums, pCreateInfos[i].pDepthStencilState->back.compareOp,
"VUID-VkPipelineDepthStencilStateCreateInfo-depthCompareOp-parameter");
if (pCreateInfos[i].pDepthStencilState->sType != VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_InvalidStructSType,
"vkCreateGraphicsPipelines: parameter pCreateInfos[%d].pDepthStencilState->sType must be "
"VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO",
i);
}
}
const VkStructureType allowed_structs_VkPipelineColorBlendStateCreateInfo[] = {
VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT};
if (pCreateInfos[i].pColorBlendState != nullptr && uses_color_attachment) {
skip |= validate_struct_pnext(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pNext", ParameterName::IndexVector{i}),
"VkPipelineColorBlendAdvancedStateCreateInfoEXT", pCreateInfos[i].pColorBlendState->pNext,
ARRAY_SIZE(allowed_structs_VkPipelineColorBlendStateCreateInfo),
allowed_structs_VkPipelineColorBlendStateCreateInfo, GeneratedVulkanHeaderVersion,
"VUID-VkPipelineColorBlendStateCreateInfo-pNext-pNext");
skip |= validate_reserved_flags(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->flags", ParameterName::IndexVector{i}),
pCreateInfos[i].pColorBlendState->flags, "VUID-VkPipelineColorBlendStateCreateInfo-flags-zerobitmask");
skip |= validate_bool32(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->logicOpEnable", ParameterName::IndexVector{i}),
pCreateInfos[i].pColorBlendState->logicOpEnable);
skip |= validate_array(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->attachmentCount", ParameterName::IndexVector{i}),
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments", ParameterName::IndexVector{i}),
pCreateInfos[i].pColorBlendState->attachmentCount, &pCreateInfos[i].pColorBlendState->pAttachments, false,
true, kVUIDUndefined, kVUIDUndefined);
if (pCreateInfos[i].pColorBlendState->pAttachments != NULL) {
for (uint32_t attachmentIndex = 0; attachmentIndex < pCreateInfos[i].pColorBlendState->attachmentCount;
++attachmentIndex) {
skip |= validate_bool32("vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].blendEnable",
ParameterName::IndexVector{i, attachmentIndex}),
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].blendEnable);
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].srcColorBlendFactor",
ParameterName::IndexVector{i, attachmentIndex}),
"VkBlendFactor", AllVkBlendFactorEnums,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].srcColorBlendFactor,
"VUID-VkPipelineColorBlendAttachmentState-srcColorBlendFactor-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].dstColorBlendFactor",
ParameterName::IndexVector{i, attachmentIndex}),
"VkBlendFactor", AllVkBlendFactorEnums,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].dstColorBlendFactor,
"VUID-VkPipelineColorBlendAttachmentState-dstColorBlendFactor-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].colorBlendOp",
ParameterName::IndexVector{i, attachmentIndex}),
"VkBlendOp", AllVkBlendOpEnums,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].colorBlendOp,
"VUID-VkPipelineColorBlendAttachmentState-colorBlendOp-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].srcAlphaBlendFactor",
ParameterName::IndexVector{i, attachmentIndex}),
"VkBlendFactor", AllVkBlendFactorEnums,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].srcAlphaBlendFactor,
"VUID-VkPipelineColorBlendAttachmentState-srcAlphaBlendFactor-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].dstAlphaBlendFactor",
ParameterName::IndexVector{i, attachmentIndex}),
"VkBlendFactor", AllVkBlendFactorEnums,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].dstAlphaBlendFactor,
"VUID-VkPipelineColorBlendAttachmentState-dstAlphaBlendFactor-parameter");
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].alphaBlendOp",
ParameterName::IndexVector{i, attachmentIndex}),
"VkBlendOp", AllVkBlendOpEnums,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].alphaBlendOp,
"VUID-VkPipelineColorBlendAttachmentState-alphaBlendOp-parameter");
skip |=
validate_flags("vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->pAttachments[%i].colorWriteMask",
ParameterName::IndexVector{i, attachmentIndex}),
"VkColorComponentFlagBits", AllVkColorComponentFlagBits,
pCreateInfos[i].pColorBlendState->pAttachments[attachmentIndex].colorWriteMask,
false, false, "VUID-VkPipelineColorBlendAttachmentState-colorWriteMask-parameter");
}
}
if (pCreateInfos[i].pColorBlendState->sType != VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_InvalidStructSType,
"vkCreateGraphicsPipelines: parameter pCreateInfos[%d].pColorBlendState->sType must be "
"VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO",
i);
}
// If logicOpEnable is VK_TRUE, logicOp must be a valid VkLogicOp value
if (pCreateInfos[i].pColorBlendState->logicOpEnable == VK_TRUE) {
skip |= validate_ranged_enum(
"vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pColorBlendState->logicOp", ParameterName::IndexVector{i}), "VkLogicOp",
AllVkLogicOpEnums, pCreateInfos[i].pColorBlendState->logicOp,
"VUID-VkPipelineColorBlendStateCreateInfo-logicOpEnable-00607");
}
}
}
if (pCreateInfos[i].flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) {
if (pCreateInfos[i].basePipelineIndex != -1) {
if (pCreateInfos[i].basePipelineHandle != VK_NULL_HANDLE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkGraphicsPipelineCreateInfo-flags-00724",
"vkCreateGraphicsPipelines parameter, pCreateInfos->basePipelineHandle, must be "
"VK_NULL_HANDLE if pCreateInfos->flags contains the VK_PIPELINE_CREATE_DERIVATIVE_BIT flag "
"and pCreateInfos->basePipelineIndex is not -1.");
}
}
if (pCreateInfos[i].basePipelineHandle != VK_NULL_HANDLE) {
if (pCreateInfos[i].basePipelineIndex != -1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkGraphicsPipelineCreateInfo-flags-00725",
"vkCreateGraphicsPipelines parameter, pCreateInfos->basePipelineIndex, must be -1 if "
"pCreateInfos->flags contains the VK_PIPELINE_CREATE_DERIVATIVE_BIT flag and "
"pCreateInfos->basePipelineHandle is not VK_NULL_HANDLE.");
}
}
}
if (pCreateInfos[i].pRasterizationState) {
if ((pCreateInfos[i].pRasterizationState->polygonMode != VK_POLYGON_MODE_FILL) &&
(physical_device_features.fillModeNonSolid == false)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_DeviceFeature,
"vkCreateGraphicsPipelines parameter, VkPolygonMode "
"pCreateInfos->pRasterizationState->polygonMode cannot be VK_POLYGON_MODE_POINT or "
"VK_POLYGON_MODE_LINE if VkPhysicalDeviceFeatures->fillModeNonSolid is false.");
}
if (!has_dynamic_line_width && !physical_device_features.wideLines &&
(pCreateInfos[i].pRasterizationState->lineWidth != 1.0f)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, 0,
"VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-00749",
"The line width state is static (pCreateInfos[%" PRIu32
"].pDynamicState->pDynamicStates does not contain VK_DYNAMIC_STATE_LINE_WIDTH) and "
"VkPhysicalDeviceFeatures::wideLines is disabled, but pCreateInfos[%" PRIu32
"].pRasterizationState->lineWidth (=%f) is not 1.0.",
i, i, pCreateInfos[i].pRasterizationState->lineWidth);
}
}
for (size_t j = 0; j < pCreateInfos[i].stageCount; j++) {
skip |= validate_string("vkCreateGraphicsPipelines",
ParameterName("pCreateInfos[%i].pStages[%i].pName", ParameterName::IndexVector{i, j}),
"VUID-VkGraphicsPipelineCreateInfo-pStages-parameter", pCreateInfos[i].pStages[j].pName);
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines) {
bool skip = false;
for (uint32_t i = 0; i < createInfoCount; i++) {
skip |= validate_string("vkCreateComputePipelines",
ParameterName("pCreateInfos[%i].stage.pName", ParameterName::IndexVector{i}),
"VUID-VkPipelineShaderStageCreateInfo-pName-parameter", pCreateInfos[i].stage.pName);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSampler *pSampler) {
bool skip = false;
if (pCreateInfo != nullptr) {
const auto &features = physical_device_features;
const auto &limits = device_limits;
if (pCreateInfo->anisotropyEnable == VK_TRUE) {
if (!in_inclusive_range(pCreateInfo->maxAnisotropy, 1.0F, limits.maxSamplerAnisotropy)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-anisotropyEnable-01071",
"vkCreateSampler(): value of %s must be in range [1.0, %f] %s, but %f found.",
"pCreateInfo->maxAnisotropy", limits.maxSamplerAnisotropy,
"VkPhysicalDeviceLimits::maxSamplerAnistropy", pCreateInfo->maxAnisotropy);
}
// Anistropy cannot be enabled in sampler unless enabled as a feature
if (features.samplerAnisotropy == VK_FALSE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-anisotropyEnable-01070",
"vkCreateSampler(): Anisotropic sampling feature is not enabled, %s must be VK_FALSE.",
"pCreateInfo->anisotropyEnable");
}
}
if (pCreateInfo->unnormalizedCoordinates == VK_TRUE) {
if (pCreateInfo->minFilter != pCreateInfo->magFilter) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01072",
"vkCreateSampler(): when pCreateInfo->unnormalizedCoordinates is VK_TRUE, "
"pCreateInfo->minFilter (%s) and pCreateInfo->magFilter (%s) must be equal.",
string_VkFilter(pCreateInfo->minFilter), string_VkFilter(pCreateInfo->magFilter));
}
if (pCreateInfo->mipmapMode != VK_SAMPLER_MIPMAP_MODE_NEAREST) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01073",
"vkCreateSampler(): when pCreateInfo->unnormalizedCoordinates is VK_TRUE, "
"pCreateInfo->mipmapMode (%s) must be VK_SAMPLER_MIPMAP_MODE_NEAREST.",
string_VkSamplerMipmapMode(pCreateInfo->mipmapMode));
}
if (pCreateInfo->minLod != 0.0f || pCreateInfo->maxLod != 0.0f) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01074",
"vkCreateSampler(): when pCreateInfo->unnormalizedCoordinates is VK_TRUE, "
"pCreateInfo->minLod (%f) and pCreateInfo->maxLod (%f) must both be zero.",
pCreateInfo->minLod, pCreateInfo->maxLod);
}
if ((pCreateInfo->addressModeU != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
pCreateInfo->addressModeU != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) ||
(pCreateInfo->addressModeV != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
pCreateInfo->addressModeV != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075",
"vkCreateSampler(): when pCreateInfo->unnormalizedCoordinates is VK_TRUE, "
"pCreateInfo->addressModeU (%s) and pCreateInfo->addressModeV (%s) must both be "
"VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE or VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER.",
string_VkSamplerAddressMode(pCreateInfo->addressModeU),
string_VkSamplerAddressMode(pCreateInfo->addressModeV));
}
if (pCreateInfo->anisotropyEnable == VK_TRUE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01076",
"vkCreateSampler(): pCreateInfo->anisotropyEnable and pCreateInfo->unnormalizedCoordinates must "
"not both be VK_TRUE.");
}
if (pCreateInfo->compareEnable == VK_TRUE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01077",
"vkCreateSampler(): pCreateInfo->compareEnable and pCreateInfo->unnormalizedCoordinates must "
"not both be VK_TRUE.");
}
}
// If compareEnable is VK_TRUE, compareOp must be a valid VkCompareOp value
if (pCreateInfo->compareEnable == VK_TRUE) {
skip |= validate_ranged_enum("vkCreateSampler", "pCreateInfo->compareOp", "VkCompareOp", AllVkCompareOpEnums,
pCreateInfo->compareOp, "VUID-VkSamplerCreateInfo-compareEnable-01080");
}
// If any of addressModeU, addressModeV or addressModeW are VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, borderColor must be a
// valid VkBorderColor value
if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) ||
(pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) ||
(pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER)) {
skip |= validate_ranged_enum("vkCreateSampler", "pCreateInfo->borderColor", "VkBorderColor", AllVkBorderColorEnums,
pCreateInfo->borderColor, "VUID-VkSamplerCreateInfo-addressModeU-01078");
}
// If any of addressModeU, addressModeV or addressModeW are VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, the
// VK_KHR_sampler_mirror_clamp_to_edge extension must be enabled
if (!device_extensions.vk_khr_sampler_mirror_clamp_to_edge &&
((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE) ||
(pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE) ||
(pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE))) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-addressModeU-01079",
"vkCreateSampler(): A VkSamplerAddressMode value is set to VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE "
"but the VK_KHR_sampler_mirror_clamp_to_edge extension has not been enabled.");
}
// Checks for the IMG cubic filtering extension
if (device_extensions.vk_img_filter_cubic) {
if ((pCreateInfo->anisotropyEnable == VK_TRUE) &&
((pCreateInfo->minFilter == VK_FILTER_CUBIC_IMG) || (pCreateInfo->magFilter == VK_FILTER_CUBIC_IMG))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSamplerCreateInfo-magFilter-01081",
"vkCreateSampler(): Anisotropic sampling must not be VK_TRUE when either minFilter or magFilter "
"are VK_FILTER_CUBIC_IMG.");
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateDescriptorSetLayout(VkDevice device,
const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorSetLayout *pSetLayout) {
bool skip = false;
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if ((pCreateInfo != nullptr) && (pCreateInfo->pBindings != nullptr)) {
for (uint32_t i = 0; i < pCreateInfo->bindingCount; ++i) {
if (pCreateInfo->pBindings[i].descriptorCount != 0) {
// If descriptorType is VK_DESCRIPTOR_TYPE_SAMPLER or VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, and descriptorCount
// is not 0 and pImmutableSamplers is not NULL, pImmutableSamplers must be a pointer to an array of descriptorCount
// valid VkSampler handles
if (((pCreateInfo->pBindings[i].descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) ||
(pCreateInfo->pBindings[i].descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)) &&
(pCreateInfo->pBindings[i].pImmutableSamplers != nullptr)) {
for (uint32_t descriptor_index = 0; descriptor_index < pCreateInfo->pBindings[i].descriptorCount;
++descriptor_index) {
if (pCreateInfo->pBindings[i].pImmutableSamplers[descriptor_index] == VK_NULL_HANDLE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_RequiredParameter,
"vkCreateDescriptorSetLayout: required parameter "
"pCreateInfo->pBindings[%d].pImmutableSamplers[%d] specified as VK_NULL_HANDLE",
i, descriptor_index);
}
}
}
// If descriptorCount is not 0, stageFlags must be a valid combination of VkShaderStageFlagBits values
if ((pCreateInfo->pBindings[i].stageFlags != 0) &&
((pCreateInfo->pBindings[i].stageFlags & (~AllVkShaderStageFlagBits)) != 0)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkDescriptorSetLayoutBinding-descriptorCount-00283",
"vkCreateDescriptorSetLayout(): if pCreateInfo->pBindings[%d].descriptorCount is not 0, "
"pCreateInfo->pBindings[%d].stageFlags must be a valid combination of VkShaderStageFlagBits "
"values.",
i, i);
}
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool,
uint32_t descriptorSetCount,
const VkDescriptorSet *pDescriptorSets) {
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
// This is an array of handles, where the elements are allowed to be VK_NULL_HANDLE, and does not require any validation beyond
// validate_array()
return validate_array("vkFreeDescriptorSets", "descriptorSetCount", "pDescriptorSets", descriptorSetCount, &pDescriptorSets,
true, true, kVUIDUndefined, kVUIDUndefined);
}
bool StatelessValidation::manual_PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
const VkWriteDescriptorSet *pDescriptorWrites,
uint32_t descriptorCopyCount,
const VkCopyDescriptorSet *pDescriptorCopies) {
bool skip = false;
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if (pDescriptorWrites != NULL) {
for (uint32_t i = 0; i < descriptorWriteCount; ++i) {
// descriptorCount must be greater than 0
if (pDescriptorWrites[i].descriptorCount == 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkWriteDescriptorSet-descriptorCount-arraylength",
"vkUpdateDescriptorSets(): parameter pDescriptorWrites[%d].descriptorCount must be greater than 0.", i);
}
// dstSet must be a valid VkDescriptorSet handle
skip |= validate_required_handle("vkUpdateDescriptorSets",
ParameterName("pDescriptorWrites[%i].dstSet", ParameterName::IndexVector{i}),
pDescriptorWrites[i].dstSet);
if ((pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)) {
// If descriptorType is VK_DESCRIPTOR_TYPE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
// VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE or VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT,
// pImageInfo must be a pointer to an array of descriptorCount valid VkDescriptorImageInfo structures
if (pDescriptorWrites[i].pImageInfo == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkWriteDescriptorSet-descriptorType-00322",
"vkUpdateDescriptorSets(): if pDescriptorWrites[%d].descriptorType is "
"VK_DESCRIPTOR_TYPE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, "
"VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE or "
"VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, pDescriptorWrites[%d].pImageInfo must not be NULL.",
i, i);
} else if (pDescriptorWrites[i].descriptorType != VK_DESCRIPTOR_TYPE_SAMPLER) {
// If descriptorType is VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
// VK_DESCRIPTOR_TYPE_STORAGE_IMAGE or VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, the imageView and imageLayout
// members of any given element of pImageInfo must be a valid VkImageView and VkImageLayout, respectively
for (uint32_t descriptor_index = 0; descriptor_index < pDescriptorWrites[i].descriptorCount;
++descriptor_index) {
skip |= validate_required_handle("vkUpdateDescriptorSets",
ParameterName("pDescriptorWrites[%i].pImageInfo[%i].imageView",
ParameterName::IndexVector{i, descriptor_index}),
pDescriptorWrites[i].pImageInfo[descriptor_index].imageView);
skip |= validate_ranged_enum("vkUpdateDescriptorSets",
ParameterName("pDescriptorWrites[%i].pImageInfo[%i].imageLayout",
ParameterName::IndexVector{i, descriptor_index}),
"VkImageLayout", AllVkImageLayoutEnums,
pDescriptorWrites[i].pImageInfo[descriptor_index].imageLayout, kVUIDUndefined);
}
}
} else if ((pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
// If descriptorType is VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
// VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC or VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, pBufferInfo must be a
// pointer to an array of descriptorCount valid VkDescriptorBufferInfo structures
if (pDescriptorWrites[i].pBufferInfo == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkWriteDescriptorSet-descriptorType-00324",
"vkUpdateDescriptorSets(): if pDescriptorWrites[%d].descriptorType is "
"VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, "
"VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC or VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, "
"pDescriptorWrites[%d].pBufferInfo must not be NULL.",
i, i);
} else {
for (uint32_t descriptorIndex = 0; descriptorIndex < pDescriptorWrites[i].descriptorCount; ++descriptorIndex) {
skip |= validate_required_handle("vkUpdateDescriptorSets",
ParameterName("pDescriptorWrites[%i].pBufferInfo[%i].buffer",
ParameterName::IndexVector{i, descriptorIndex}),
pDescriptorWrites[i].pBufferInfo[descriptorIndex].buffer);
}
}
} else if ((pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)) {
// If descriptorType is VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER or VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER,
// pTexelBufferView must be a pointer to an array of descriptorCount valid VkBufferView handles
if (pDescriptorWrites[i].pTexelBufferView == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkWriteDescriptorSet-descriptorType-00323",
"vkUpdateDescriptorSets(): if pDescriptorWrites[%d].descriptorType is "
"VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER or VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, "
"pDescriptorWrites[%d].pTexelBufferView must not be NULL.",
i, i);
} else {
for (uint32_t descriptor_index = 0; descriptor_index < pDescriptorWrites[i].descriptorCount;
++descriptor_index) {
skip |= validate_required_handle("vkUpdateDescriptorSets",
ParameterName("pDescriptorWrites[%i].pTexelBufferView[%i]",
ParameterName::IndexVector{i, descriptor_index}),
pDescriptorWrites[i].pTexelBufferView[descriptor_index]);
}
}
}
if ((pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC)) {
VkDeviceSize uniformAlignment = device_limits.minUniformBufferOffsetAlignment;
for (uint32_t j = 0; j < pDescriptorWrites[i].descriptorCount; j++) {
if (pDescriptorWrites[i].pBufferInfo != NULL) {
if (SafeModulo(pDescriptorWrites[i].pBufferInfo[j].offset, uniformAlignment) != 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
0, "VUID-VkWriteDescriptorSet-descriptorType-00327",
"vkUpdateDescriptorSets(): pDescriptorWrites[%d].pBufferInfo[%d].offset (0x%" PRIxLEAST64
") must be a multiple of device limit minUniformBufferOffsetAlignment 0x%" PRIxLEAST64 ".",
i, j, pDescriptorWrites[i].pBufferInfo[j].offset, uniformAlignment);
}
}
}
} else if ((pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) ||
(pDescriptorWrites[i].descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
VkDeviceSize storageAlignment = device_limits.minStorageBufferOffsetAlignment;
for (uint32_t j = 0; j < pDescriptorWrites[i].descriptorCount; j++) {
if (pDescriptorWrites[i].pBufferInfo != NULL) {
if (SafeModulo(pDescriptorWrites[i].pBufferInfo[j].offset, storageAlignment) != 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
0, "VUID-VkWriteDescriptorSet-descriptorType-00328",
"vkUpdateDescriptorSets(): pDescriptorWrites[%d].pBufferInfo[%d].offset (0x%" PRIxLEAST64
") must be a multiple of device limit minStorageBufferOffsetAlignment 0x%" PRIxLEAST64 ".",
i, j, pDescriptorWrites[i].pBufferInfo[j].offset, storageAlignment);
}
}
}
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkRenderPass *pRenderPass) {
return CreateRenderPassGeneric(device, pCreateInfo, pAllocator, pRenderPass, RENDER_PASS_VERSION_1);
}
bool StatelessValidation::manual_PreCallValidateCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2KHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkRenderPass *pRenderPass) {
return CreateRenderPassGeneric(device, pCreateInfo, pAllocator, pRenderPass, RENDER_PASS_VERSION_2);
}
bool StatelessValidation::manual_PreCallValidateFreeCommandBuffers(VkDevice device, VkCommandPool commandPool,
uint32_t commandBufferCount,
const VkCommandBuffer *pCommandBuffers) {
bool skip = false;
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
// This is an array of handles, where the elements are allowed to be VK_NULL_HANDLE, and does not require any validation beyond
// validate_array()
skip |= validate_array("vkFreeCommandBuffers", "commandBufferCount", "pCommandBuffers", commandBufferCount, &pCommandBuffers,
true, true, kVUIDUndefined, kVUIDUndefined);
return skip;
}
bool StatelessValidation::manual_PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
const VkCommandBufferBeginInfo *pBeginInfo) {
bool skip = false;
const VkCommandBufferInheritanceInfo *pInfo = pBeginInfo->pInheritanceInfo;
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
// TODO: pBeginInfo->pInheritanceInfo must not be NULL if commandBuffer is a secondary command buffer
skip |= validate_struct_type("vkBeginCommandBuffer", "pBeginInfo->pInheritanceInfo",
"VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO", pBeginInfo->pInheritanceInfo,
VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, false,
"VUID_vkBeginCommandBuffer-pBeginInfo-parameter", "VUID_VkCommandBufferBeginInfo-sType-sType");
if (pBeginInfo->pInheritanceInfo != NULL) {
skip |= validate_struct_pnext("vkBeginCommandBuffer", "pBeginInfo->pInheritanceInfo->pNext", NULL,
pBeginInfo->pInheritanceInfo->pNext, 0, NULL, GeneratedVulkanHeaderVersion,
"VUID-VkCommandBufferBeginInfo-pNext-pNext");
skip |= validate_bool32("vkBeginCommandBuffer", "pBeginInfo->pInheritanceInfo->occlusionQueryEnable",
pBeginInfo->pInheritanceInfo->occlusionQueryEnable);
// TODO: This only needs to be validated when the inherited queries feature is enabled
// skip |= validate_flags("vkBeginCommandBuffer", "pBeginInfo->pInheritanceInfo->queryFlags",
// "VkQueryControlFlagBits", AllVkQueryControlFlagBits, pBeginInfo->pInheritanceInfo->queryFlags, false);
// TODO: This must be 0 if the pipeline statistics queries feature is not enabled
skip |= validate_flags("vkBeginCommandBuffer", "pBeginInfo->pInheritanceInfo->pipelineStatistics",
"VkQueryPipelineStatisticFlagBits", AllVkQueryPipelineStatisticFlagBits,
pBeginInfo->pInheritanceInfo->pipelineStatistics, false, false, kVUIDUndefined);
}
if (pInfo != NULL) {
if ((physical_device_features.inheritedQueries == VK_FALSE) && (pInfo->occlusionQueryEnable != VK_FALSE)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-VkCommandBufferInheritanceInfo-occlusionQueryEnable-00056",
"Cannot set inherited occlusionQueryEnable in vkBeginCommandBuffer() when device does not support "
"inheritedQueries.");
}
if ((physical_device_features.inheritedQueries != VK_FALSE) && (pInfo->occlusionQueryEnable != VK_FALSE)) {
skip |= validate_flags("vkBeginCommandBuffer", "pBeginInfo->pInheritanceInfo->queryFlags", "VkQueryControlFlagBits",
AllVkQueryControlFlagBits, pInfo->queryFlags, false, false,
"VUID-VkCommandBufferInheritanceInfo-queryFlags-00057");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdSetViewport(VkCommandBuffer commandBuffer, uint32_t firstViewport,
uint32_t viewportCount, const VkViewport *pViewports) {
bool skip = false;
if (!physical_device_features.multiViewport) {
if (firstViewport != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewport-firstViewport-01224",
"vkCmdSetViewport: The multiViewport feature is disabled, but firstViewport (=%" PRIu32 ") is not 0.",
firstViewport);
}
if (viewportCount > 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewport-viewportCount-01225",
"vkCmdSetViewport: The multiViewport feature is disabled, but viewportCount (=%" PRIu32 ") is not 1.",
viewportCount);
}
} else { // multiViewport enabled
const uint64_t sum = static_cast<uint64_t>(firstViewport) + static_cast<uint64_t>(viewportCount);
if (sum > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewport-firstViewport-01223",
"vkCmdSetViewport: firstViewport + viewportCount (=%" PRIu32 " + %" PRIu32 " = %" PRIu64
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
firstViewport, viewportCount, sum, device_limits.maxViewports);
}
}
if (pViewports) {
for (uint32_t viewport_i = 0; viewport_i < viewportCount; ++viewport_i) {
const auto &viewport = pViewports[viewport_i]; // will crash on invalid ptr
const char fn_name[] = "vkCmdSetViewport";
const std::string param_name = "pViewports[" + std::to_string(viewport_i) + "]";
skip |= manual_PreCallValidateViewport(viewport, fn_name, param_name.c_str(),
VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer));
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdSetScissor(VkCommandBuffer commandBuffer, uint32_t firstScissor,
uint32_t scissorCount, const VkRect2D *pScissors) {
bool skip = false;
if (!physical_device_features.multiViewport) {
if (firstScissor != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-firstScissor-00593",
"vkCmdSetScissor: The multiViewport feature is disabled, but firstScissor (=%" PRIu32 ") is not 0.",
firstScissor);
}
if (scissorCount > 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-scissorCount-00594",
"vkCmdSetScissor: The multiViewport feature is disabled, but scissorCount (=%" PRIu32 ") is not 1.",
scissorCount);
}
} else { // multiViewport enabled
const uint64_t sum = static_cast<uint64_t>(firstScissor) + static_cast<uint64_t>(scissorCount);
if (sum > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-firstScissor-00592",
"vkCmdSetScissor: firstScissor + scissorCount (=%" PRIu32 " + %" PRIu32 " = %" PRIu64
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
firstScissor, scissorCount, sum, device_limits.maxViewports);
}
}
if (pScissors) {
for (uint32_t scissor_i = 0; scissor_i < scissorCount; ++scissor_i) {
const auto &scissor = pScissors[scissor_i]; // will crash on invalid ptr
if (scissor.offset.x < 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-x-00595",
"vkCmdSetScissor: pScissors[%" PRIu32 "].offset.x (=%" PRIi32 ") is negative.", scissor_i,
scissor.offset.x);
}
if (scissor.offset.y < 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-x-00595",
"vkCmdSetScissor: pScissors[%" PRIu32 "].offset.y (=%" PRIi32 ") is negative.", scissor_i,
scissor.offset.y);
}
const int64_t x_sum = static_cast<int64_t>(scissor.offset.x) + static_cast<int64_t>(scissor.extent.width);
if (x_sum > INT32_MAX) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-offset-00596",
"vkCmdSetScissor: offset.x + extent.width (=%" PRIi32 " + %" PRIu32 " = %" PRIi64
") of pScissors[%" PRIu32 "] will overflow int32_t.",
scissor.offset.x, scissor.extent.width, x_sum, scissor_i);
}
const int64_t y_sum = static_cast<int64_t>(scissor.offset.y) + static_cast<int64_t>(scissor.extent.height);
if (y_sum > INT32_MAX) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-offset-00597",
"vkCmdSetScissor: offset.y + extent.height (=%" PRIi32 " + %" PRIu32 " = %" PRIi64
") of pScissors[%" PRIu32 "] will overflow int32_t.",
scissor.offset.y, scissor.extent.height, y_sum, scissor_i);
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdSetLineWidth(VkCommandBuffer commandBuffer, float lineWidth) {
bool skip = false;
if (!physical_device_features.wideLines && (lineWidth != 1.0f)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetLineWidth-lineWidth-00788",
"VkPhysicalDeviceFeatures::wideLines is disabled, but lineWidth (=%f) is not 1.0.", lineWidth);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
uint32_t firstVertex, uint32_t firstInstance) {
bool skip = false;
if (vertexCount == 0) {
// TODO: Verify against Valid Usage section. I don't see a non-zero vertexCount listed, may need to add that and make
// this an error or leave as is.
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_RequiredParameter, "vkCmdDraw parameter, uint32_t vertexCount, is 0");
}
if (instanceCount == 0) {
// TODO: Verify against Valid Usage section. I don't see a non-zero instanceCount listed, may need to add that and make
// this an error or leave as is.
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_RequiredParameter, "vkCmdDraw parameter, uint32_t instanceCount, is 0");
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
uint32_t count, uint32_t stride) {
bool skip = false;
if (!physical_device_features.multiDrawIndirect && ((count > 1))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_DeviceFeature,
"CmdDrawIndirect(): Device feature multiDrawIndirect disabled: count must be 0 or 1 but is %d", count);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer,
VkDeviceSize offset, uint32_t count, uint32_t stride) {
bool skip = false;
if (!physical_device_features.multiDrawIndirect && ((count > 1))) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_PVError_DeviceFeature,
"CmdDrawIndexedIndirect(): Device feature multiDrawIndirect disabled: count must be 0 or 1 but is %d", count);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage,
VkImageLayout srcImageLayout, VkImage dstImage,
VkImageLayout dstImageLayout, uint32_t regionCount,
const VkImageCopy *pRegions) {
bool skip = false;
VkImageAspectFlags legal_aspect_flags =
VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_METADATA_BIT;
if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
legal_aspect_flags |= (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR | VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
}
if (pRegions != nullptr) {
if ((pRegions->srcSubresource.aspectMask & legal_aspect_flags) == 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageSubresourceLayers-aspectMask-parameter",
"vkCmdCopyImage() parameter, VkImageAspect pRegions->srcSubresource.aspectMask, is an unrecognized enumerator.");
}
if ((pRegions->dstSubresource.aspectMask & legal_aspect_flags) == 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkImageSubresourceLayers-aspectMask-parameter",
"vkCmdCopyImage() parameter, VkImageAspect pRegions->dstSubresource.aspectMask, is an unrecognized enumerator.");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage,
VkImageLayout srcImageLayout, VkImage dstImage,
VkImageLayout dstImageLayout, uint32_t regionCount,
const VkImageBlit *pRegions, VkFilter filter) {
bool skip = false;
VkImageAspectFlags legal_aspect_flags =
VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_METADATA_BIT;
if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
legal_aspect_flags |= (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR | VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
}
if (pRegions != nullptr) {
if ((pRegions->srcSubresource.aspectMask & legal_aspect_flags) == 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_UnrecognizedValue,
"vkCmdBlitImage() parameter, VkImageAspect pRegions->srcSubresource.aspectMask, is an unrecognized enumerator");
}
if ((pRegions->dstSubresource.aspectMask & legal_aspect_flags) == 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_UnrecognizedValue,
"vkCmdBlitImage() parameter, VkImageAspect pRegions->dstSubresource.aspectMask, is an unrecognized enumerator");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer,
VkImage dstImage, VkImageLayout dstImageLayout,
uint32_t regionCount, const VkBufferImageCopy *pRegions) {
bool skip = false;
VkImageAspectFlags legal_aspect_flags =
VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_METADATA_BIT;
if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
legal_aspect_flags |= (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR | VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
}
if (pRegions != nullptr) {
if ((pRegions->imageSubresource.aspectMask & legal_aspect_flags) == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_UnrecognizedValue,
"vkCmdCopyBufferToImage() parameter, VkImageAspect pRegions->imageSubresource.aspectMask, is an "
"unrecognized enumerator");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
VkImageLayout srcImageLayout, VkBuffer dstBuffer,
uint32_t regionCount, const VkBufferImageCopy *pRegions) {
bool skip = false;
VkImageAspectFlags legal_aspect_flags =
VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_METADATA_BIT;
if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
legal_aspect_flags |= (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR | VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
}
if (pRegions != nullptr) {
if ((pRegions->imageSubresource.aspectMask & legal_aspect_flags) == 0) {
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_UnrecognizedValue,
"vkCmdCopyImageToBuffer parameter, VkImageAspect pRegions->imageSubresource.aspectMask, is an unrecognized "
"enumerator");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer,
VkDeviceSize dstOffset, VkDeviceSize dataSize, const void *pData) {
bool skip = false;
if (dstOffset & 3) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdUpdateBuffer-dstOffset-00036",
"vkCmdUpdateBuffer() parameter, VkDeviceSize dstOffset (0x%" PRIxLEAST64 "), is not a multiple of 4.",
dstOffset);
}
if ((dataSize <= 0) || (dataSize > 65536)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdUpdateBuffer-dataSize-00037",
"vkCmdUpdateBuffer() parameter, VkDeviceSize dataSize (0x%" PRIxLEAST64
"), must be greater than zero and less than or equal to 65536.",
dataSize);
} else if (dataSize & 3) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdUpdateBuffer-dataSize-00038",
"vkCmdUpdateBuffer() parameter, VkDeviceSize dataSize (0x%" PRIxLEAST64 "), is not a multiple of 4.", dataSize);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer,
VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data) {
bool skip = false;
if (dstOffset & 3) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdFillBuffer-dstOffset-00025",
"vkCmdFillBuffer() parameter, VkDeviceSize dstOffset (0x%" PRIxLEAST64 "), is not a multiple of 4.", dstOffset);
}
if (size != VK_WHOLE_SIZE) {
if (size <= 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdFillBuffer-size-00026",
"vkCmdFillBuffer() parameter, VkDeviceSize size (0x%" PRIxLEAST64 "), must be greater than zero.", size);
} else if (size & 3) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdFillBuffer-size-00028",
"vkCmdFillBuffer() parameter, VkDeviceSize size (0x%" PRIxLEAST64 "), is not a multiple of 4.", size);
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkSwapchainKHR *pSwapchain) {
bool skip = false;
const LogMiscParams log_misc{VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, VK_NULL_HANDLE, "vkCreateSwapchainKHR"};
if (pCreateInfo != nullptr) {
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if (pCreateInfo->imageSharingMode == VK_SHARING_MODE_CONCURRENT) {
// If imageSharingMode is VK_SHARING_MODE_CONCURRENT, queueFamilyIndexCount must be greater than 1
if (pCreateInfo->queueFamilyIndexCount <= 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01278",
"vkCreateSwapchainKHR(): if pCreateInfo->imageSharingMode is VK_SHARING_MODE_CONCURRENT, "
"pCreateInfo->queueFamilyIndexCount must be greater than 1.");
}
// If imageSharingMode is VK_SHARING_MODE_CONCURRENT, pQueueFamilyIndices must be a pointer to an array of
// queueFamilyIndexCount uint32_t values
if (pCreateInfo->pQueueFamilyIndices == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01277",
"vkCreateSwapchainKHR(): if pCreateInfo->imageSharingMode is VK_SHARING_MODE_CONCURRENT, "
"pCreateInfo->pQueueFamilyIndices must be a pointer to an array of "
"pCreateInfo->queueFamilyIndexCount uint32_t values.");
} else {
skip |= ValidateQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices,
"vkCreateSwapchainKHR", "pCreateInfo->pQueueFamilyIndices",
kVUID_PVError_InvalidUsage, kVUID_PVError_InvalidUsage, false);
}
}
skip |= ValidateGreaterThanZero(pCreateInfo->imageArrayLayers, "pCreateInfo->imageArrayLayers",
"VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275", log_misc);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) {
bool skip = false;
if (pPresentInfo && pPresentInfo->pNext) {
const auto *present_regions = lvl_find_in_chain<VkPresentRegionsKHR>(pPresentInfo->pNext);
if (present_regions) {
// TODO: This and all other pNext extension dependencies should be added to code-generation
skip |= require_device_extension(device_extensions.vk_khr_incremental_present, "vkQueuePresentKHR",
VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
if (present_regions->swapchainCount != pPresentInfo->swapchainCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_PVError_InvalidUsage,
"QueuePresentKHR(): pPresentInfo->swapchainCount has a value of %i but VkPresentRegionsKHR "
"extension swapchainCount is %i. These values must be equal.",
pPresentInfo->swapchainCount, present_regions->swapchainCount);
}
skip |= validate_struct_pnext("QueuePresentKHR", "pCreateInfo->pNext->pNext", NULL, present_regions->pNext, 0, NULL,
GeneratedVulkanHeaderVersion, "VUID-VkPresentInfoKHR-pNext-pNext");
skip |= validate_array("QueuePresentKHR", "pCreateInfo->pNext->swapchainCount", "pCreateInfo->pNext->pRegions",
present_regions->swapchainCount, &present_regions->pRegions, true, false, kVUIDUndefined,
kVUIDUndefined);
for (uint32_t i = 0; i < present_regions->swapchainCount; ++i) {
skip |= validate_array("QueuePresentKHR", "pCreateInfo->pNext->pRegions[].rectangleCount",
"pCreateInfo->pNext->pRegions[].pRectangles", present_regions->pRegions[i].rectangleCount,
&present_regions->pRegions[i].pRectangles, true, false, kVUIDUndefined, kVUIDUndefined);
}
}
}
return skip;
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool StatelessValidation::manual_PreCallValidateCreateWin32SurfaceKHR(VkInstance instance,
const VkWin32SurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkSurfaceKHR *pSurface) {
bool skip = false;
if (pCreateInfo->hwnd == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkWin32SurfaceCreateInfoKHR-hwnd-01308",
"vkCreateWin32SurfaceKHR(): hwnd must be a valid Win32 HWND but hwnd is NULL.");
}
return skip;
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool StatelessValidation::manual_PreCallValidateDebugMarkerSetObjectNameEXT(VkDevice device,
const VkDebugMarkerObjectNameInfoEXT *pNameInfo) {
if (pNameInfo->pObjectName) {
report_data->debugObjectNameMap->insert(
std::make_pair<uint64_t, std::string>((uint64_t &&) pNameInfo->object, pNameInfo->pObjectName));
} else {
report_data->debugObjectNameMap->erase(pNameInfo->object);
}
return false;
}
bool StatelessValidation::manual_PreCallValidateCreateDescriptorPool(VkDevice device, const VkDescriptorPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorPool *pDescriptorPool) {
bool skip = false;
if (pCreateInfo) {
if (pCreateInfo->maxSets <= 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
VK_NULL_HANDLE, "VUID-VkDescriptorPoolCreateInfo-maxSets-00301",
"vkCreateDescriptorPool(): pCreateInfo->maxSets is not greater than 0.");
}
if (pCreateInfo->pPoolSizes) {
for (uint32_t i = 0; i < pCreateInfo->poolSizeCount; ++i) {
if (pCreateInfo->pPoolSizes[i].descriptorCount <= 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, VK_NULL_HANDLE,
"VUID-VkDescriptorPoolSize-descriptorCount-00302",
"vkCreateDescriptorPool(): pCreateInfo->pPoolSizes[%" PRIu32 "].descriptorCount is not greater than 0.", i);
}
if (pCreateInfo->pPoolSizes[i].type == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT &&
(pCreateInfo->pPoolSizes[i].descriptorCount % 4) != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
VK_NULL_HANDLE, "VUID-VkDescriptorPoolSize-type-02218",
"vkCreateDescriptorPool(): pCreateInfo->pPoolSizes[%" PRIu32
"].type is VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT "
" and pCreateInfo->pPoolSizes[%" PRIu32 "].descriptorCount is not a multiple of 4.",
i, i);
}
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX,
uint32_t groupCountY, uint32_t groupCountZ) {
bool skip = false;
if (groupCountX > device_limits.maxComputeWorkGroupCount[0]) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatch-groupCountX-00386",
"vkCmdDispatch(): groupCountX (%" PRIu32 ") exceeds device limit maxComputeWorkGroupCount[0] (%" PRIu32 ").",
groupCountX, device_limits.maxComputeWorkGroupCount[0]);
}
if (groupCountY > device_limits.maxComputeWorkGroupCount[1]) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatch-groupCountY-00387",
"vkCmdDispatch(): groupCountY (%" PRIu32 ") exceeds device limit maxComputeWorkGroupCount[1] (%" PRIu32 ").",
groupCountY, device_limits.maxComputeWorkGroupCount[1]);
}
if (groupCountZ > device_limits.maxComputeWorkGroupCount[2]) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatch-groupCountZ-00388",
"vkCmdDispatch(): groupCountZ (%" PRIu32 ") exceeds device limit maxComputeWorkGroupCount[2] (%" PRIu32 ").",
groupCountZ, device_limits.maxComputeWorkGroupCount[2]);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer,
VkDeviceSize offset) {
bool skip = false;
if ((offset % 4) != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchIndirect-offset-00406",
"vkCmdDispatchIndirect(): offset (%" PRIu64 ") must be a multiple of 4.", offset);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDispatchBaseKHR(VkCommandBuffer commandBuffer, uint32_t baseGroupX,
uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX,
uint32_t groupCountY, uint32_t groupCountZ) {
bool skip = false;
// Paired if {} else if {} tests used to avoid any possible uint underflow
uint32_t limit = device_limits.maxComputeWorkGroupCount[0];
if (baseGroupX >= limit) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchBase-baseGroupX-00421",
"vkCmdDispatch(): baseGroupX (%" PRIu32
") equals or exceeds device limit maxComputeWorkGroupCount[0] (%" PRIu32 ").",
baseGroupX, limit);
} else if (groupCountX > (limit - baseGroupX)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchBase-groupCountX-00424",
"vkCmdDispatchBaseKHR(): baseGroupX (%" PRIu32 ") + groupCountX (%" PRIu32
") exceeds device limit maxComputeWorkGroupCount[0] (%" PRIu32 ").",
baseGroupX, groupCountX, limit);
}
limit = device_limits.maxComputeWorkGroupCount[1];
if (baseGroupY >= limit) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchBase-baseGroupX-00422",
"vkCmdDispatch(): baseGroupY (%" PRIu32
") equals or exceeds device limit maxComputeWorkGroupCount[1] (%" PRIu32 ").",
baseGroupY, limit);
} else if (groupCountY > (limit - baseGroupY)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchBase-groupCountY-00425",
"vkCmdDispatchBaseKHR(): baseGroupY (%" PRIu32 ") + groupCountY (%" PRIu32
") exceeds device limit maxComputeWorkGroupCount[1] (%" PRIu32 ").",
baseGroupY, groupCountY, limit);
}
limit = device_limits.maxComputeWorkGroupCount[2];
if (baseGroupZ >= limit) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchBase-baseGroupZ-00423",
"vkCmdDispatch(): baseGroupZ (%" PRIu32
") equals or exceeds device limit maxComputeWorkGroupCount[2] (%" PRIu32 ").",
baseGroupZ, limit);
} else if (groupCountZ > (limit - baseGroupZ)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDispatchBase-groupCountZ-00426",
"vkCmdDispatchBaseKHR(): baseGroupZ (%" PRIu32 ") + groupCountZ (%" PRIu32
") exceeds device limit maxComputeWorkGroupCount[2] (%" PRIu32 ").",
baseGroupZ, groupCountZ, limit);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdSetExclusiveScissorNV(VkCommandBuffer commandBuffer,
uint32_t firstExclusiveScissor,
uint32_t exclusiveScissorCount,
const VkRect2D *pExclusiveScissors) {
bool skip = false;
if (!physical_device_features.multiViewport) {
if (firstExclusiveScissor != 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-firstExclusiveScissor-02035",
"vkCmdSetExclusiveScissorNV: The multiViewport feature is disabled, but firstExclusiveScissor (=%" PRIu32
") is not 0.",
firstExclusiveScissor);
}
if (exclusiveScissorCount > 1) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-exclusiveScissorCount-02036",
"vkCmdSetExclusiveScissorNV: The multiViewport feature is disabled, but exclusiveScissorCount (=%" PRIu32
") is not 1.",
exclusiveScissorCount);
}
} else { // multiViewport enabled
const uint64_t sum = static_cast<uint64_t>(firstExclusiveScissor) + static_cast<uint64_t>(exclusiveScissorCount);
if (sum > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-firstExclusiveScissor-02034",
"vkCmdSetExclusiveScissorNV: firstExclusiveScissor + exclusiveScissorCount (=%" PRIu32 " + %" PRIu32
" = %" PRIu64 ") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
firstExclusiveScissor, exclusiveScissorCount, sum, device_limits.maxViewports);
}
}
if (firstExclusiveScissor >= device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-firstExclusiveScissor-02033",
"vkCmdSetExclusiveScissorNV: firstExclusiveScissor (=%" PRIu32 ") must be less than maxViewports (=%" PRIu32
").",
firstExclusiveScissor, device_limits.maxViewports);
}
if (pExclusiveScissors) {
for (uint32_t scissor_i = 0; scissor_i < exclusiveScissorCount; ++scissor_i) {
const auto &scissor = pExclusiveScissors[scissor_i]; // will crash on invalid ptr
if (scissor.offset.x < 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-x-02037",
"vkCmdSetExclusiveScissorNV: pScissors[%" PRIu32 "].offset.x (=%" PRIi32 ") is negative.",
scissor_i, scissor.offset.x);
}
if (scissor.offset.y < 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-x-02037",
"vkCmdSetExclusiveScissorNV: pScissors[%" PRIu32 "].offset.y (=%" PRIi32 ") is negative.",
scissor_i, scissor.offset.y);
}
const int64_t x_sum = static_cast<int64_t>(scissor.offset.x) + static_cast<int64_t>(scissor.extent.width);
if (x_sum > INT32_MAX) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-offset-02038",
"vkCmdSetExclusiveScissorNV: offset.x + extent.width (=%" PRIi32 " + %" PRIu32 " = %" PRIi64
") of pScissors[%" PRIu32 "] will overflow int32_t.",
scissor.offset.x, scissor.extent.width, x_sum, scissor_i);
}
const int64_t y_sum = static_cast<int64_t>(scissor.offset.y) + static_cast<int64_t>(scissor.extent.height);
if (y_sum > INT32_MAX) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-offset-02039",
"vkCmdSetExclusiveScissorNV: offset.y + extent.height (=%" PRIi32 " + %" PRIu32 " = %" PRIi64
") of pScissors[%" PRIu32 "] will overflow int32_t.",
scissor.offset.y, scissor.extent.height, y_sum, scissor_i);
}
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdSetViewportShadingRatePaletteNV(
VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount,
const VkShadingRatePaletteNV *pShadingRatePalettes) {
bool skip = false;
if (!physical_device_features.multiViewport) {
if (firstViewport != 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02068",
"vkCmdSetViewportShadingRatePaletteNV: The multiViewport feature is disabled, but firstViewport (=%" PRIu32
") is not 0.",
firstViewport);
}
if (viewportCount > 1) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-viewportCount-02069",
"vkCmdSetViewportShadingRatePaletteNV: The multiViewport feature is disabled, but viewportCount (=%" PRIu32
") is not 1.",
viewportCount);
}
}
if (firstViewport >= device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02066",
"vkCmdSetViewportShadingRatePaletteNV: firstViewport (=%" PRIu32
") must be less than maxViewports (=%" PRIu32 ").",
firstViewport, device_limits.maxViewports);
}
const uint64_t sum = static_cast<uint64_t>(firstViewport) + static_cast<uint64_t>(viewportCount);
if (sum > device_limits.maxViewports) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02067",
"vkCmdSetViewportShadingRatePaletteNV: firstViewport + viewportCount (=%" PRIu32 " + %" PRIu32 " = %" PRIu64
") is greater than VkPhysicalDeviceLimits::maxViewports (=%" PRIu32 ").",
firstViewport, viewportCount, sum, device_limits.maxViewports);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdSetCoarseSampleOrderNV(VkCommandBuffer commandBuffer,
VkCoarseSampleOrderTypeNV sampleOrderType,
uint32_t customSampleOrderCount,
const VkCoarseSampleOrderCustomNV *pCustomSampleOrders) {
bool skip = false;
if (sampleOrderType != VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV && customSampleOrderCount != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetCoarseSampleOrderNV-sampleOrderType-02081",
"vkCmdSetCoarseSampleOrderNV: If sampleOrderType is not VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV, "
"customSampleOrderCount must be 0.");
}
for (uint32_t order_i = 0; order_i < customSampleOrderCount; ++order_i) {
skip |= ValidateCoarseSampleOrderCustomNV(&pCustomSampleOrders[order_i]);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount,
uint32_t firstTask) {
bool skip = false;
if (taskCount > phys_dev_ext_props.mesh_shader_props.maxDrawMeshTasksCount) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksNV-taskCount-02119",
"vkCmdDrawMeshTasksNV() parameter, uint32_t taskCount (0x%" PRIxLEAST32
"), must be less than or equal to VkPhysicalDeviceMeshShaderPropertiesNV::maxDrawMeshTasksCount (0x%" PRIxLEAST32 ").",
taskCount, phys_dev_ext_props.mesh_shader_props.maxDrawMeshTasksCount);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
VkDeviceSize offset, uint32_t drawCount,
uint32_t stride) {
bool skip = false;
if (offset & 3) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksIndirectNV-offset-02145",
"vkCmdDrawMeshTasksIndirectNV() parameter, VkDeviceSize offset (0x%" PRIxLEAST64 "), is not a multiple of 4.", offset);
}
if (drawCount > 1 && ((stride & 3) || stride < sizeof(VkDrawMeshTasksIndirectCommandNV))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksIndirectNV-drawCount-02146",
"vkCmdDrawMeshTasksIndirectNV() parameter, uint32_t stride (0x%" PRIxLEAST32
"), is not a multiple of 4 or smaller than sizeof (VkDrawMeshTasksIndirectCommandNV).",
stride);
}
if (!physical_device_features.multiDrawIndirect && ((drawCount > 1))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksIndirectNV-drawCount-02147",
"vkCmdDrawMeshTasksIndirectNV(): Device feature multiDrawIndirect disabled: count must be 0 or 1 but is %d",
drawCount);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
VkDeviceSize offset, VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount, uint32_t stride) {
bool skip = false;
if (offset & 3) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksIndirectCountNV-offset-02180",
"vkCmdDrawMeshTasksIndirectCountNV() parameter, VkDeviceSize offset (0x%" PRIxLEAST64
"), is not a multiple of 4.",
offset);
}
if (countBufferOffset & 3) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksIndirectCountNV-countBufferOffset-02181",
"vkCmdDrawMeshTasksIndirectCountNV() parameter, VkDeviceSize countBufferOffset (0x%" PRIxLEAST64
"), is not a multiple of 4.",
countBufferOffset);
}
if ((stride & 3) || stride < sizeof(VkDrawMeshTasksIndirectCommandNV)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdDrawMeshTasksIndirectCountNV-stride-02182",
"vkCmdDrawMeshTasksIndirectCountNV() parameter, uint32_t stride (0x%" PRIxLEAST32
"), is not a multiple of 4 or smaller than sizeof (VkDrawMeshTasksIndirectCommandNV).",
stride);
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkCommandPool *pCommandPool) {
return ValidateDeviceQueueFamily(pCreateInfo->queueFamilyIndex, "vkCreateCommandPool", "pCreateInfo->queueFamilyIndex",
"VUID-vkCreateCommandPool-queueFamilyIndex-01937");
}
bool StatelessValidation::manual_PreCallValidateCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool) {
bool skip = false;
// Validation for parameters excluded from the generated validation code due to a 'noautovalidity' tag in vk.xml
if (pCreateInfo != nullptr) {
// If queryType is VK_QUERY_TYPE_PIPELINE_STATISTICS, pipelineStatistics must be a valid combination of
// VkQueryPipelineStatisticFlagBits values
if ((pCreateInfo->queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS) && (pCreateInfo->pipelineStatistics != 0) &&
((pCreateInfo->pipelineStatistics & (~AllVkQueryPipelineStatisticFlagBits)) != 0)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkQueryPoolCreateInfo-queryType-00792",
"vkCreateQueryPool(): if pCreateInfo->queryType is VK_QUERY_TYPE_PIPELINE_STATISTICS, "
"pCreateInfo->pipelineStatistics must be a valid combination of VkQueryPipelineStatisticFlagBits "
"values.");
}
}
return skip;
}
bool StatelessValidation::manual_PreCallValidateEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
const char *pLayerName, uint32_t *pPropertyCount,
VkExtensionProperties *pProperties) {
return validate_array("vkEnumerateDeviceExtensionProperties", "pPropertyCount", "pProperties", pPropertyCount, &pProperties,
true, false, false, kVUIDUndefined, "VUID-vkEnumerateDeviceExtensionProperties-pProperties-parameter");
}
void StatelessValidation::PostCallRecordCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass,
VkResult result) {
if (result != VK_SUCCESS) return;
RecordRenderPass(*pRenderPass, pCreateInfo);
}
void StatelessValidation::PostCallRecordCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2KHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass,
VkResult result) {
// Track the state necessary for checking vkCreateGraphicsPipeline (subpass usage of depth and color attachments)
if (result != VK_SUCCESS) return;
RecordRenderPass(*pRenderPass, pCreateInfo);
}
void StatelessValidation::PostCallRecordDestroyRenderPass(VkDevice device, VkRenderPass renderPass,
const VkAllocationCallbacks *pAllocator) {
// Track the state necessary for checking vkCreateGraphicsPipeline (subpass usage of depth and color attachments)
renderpasses_states.erase(renderPass);
}
bool StatelessValidation::manual_PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
bool skip = false;
if (pAllocateInfo) {
auto chained_prio_struct = lvl_find_in_chain<VkMemoryPriorityAllocateInfoEXT>(pAllocateInfo->pNext);
if (chained_prio_struct && (chained_prio_struct->priority < 0.0f || chained_prio_struct->priority > 1.0f)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkMemoryPriorityAllocateInfoEXT-priority-02602",
"priority (=%f) must be between `0` and `1`, inclusive.", chained_prio_struct->priority);
}
}
return skip;
}
| 1 | 9,947 | This should not be needed. 1) all 1.1 promoted extensions are marked as enabled when a 1.1 device is created (which happens iff both physical device support and apiVersion are set to 1.1) 2) The KHR and non-KHR versions of the bits are aliases of each other, so no different set is required. | KhronosGroup-Vulkan-ValidationLayers | cpp |
@@ -656,7 +656,11 @@ static void makeflow_node_complete(struct dag *d, struct dag_node *n, struct bat
struct list *outputs = makeflow_generate_output_files(n, wrapper, monitor);
- if(info->exited_normally && info->exit_code == 0) {
+
+ if(getenv("CCTOOLS_LOOP_DEV_FULL")) {
+ job_failed = 1;
+ }
+ else if(info->exited_normally && info->exit_code == 0) {
list_first_item(outputs);
while((f = list_next_item(outputs))) {
if(!makeflow_node_check_file_was_created(n, f)) | 1 | /*
Copyright (C) 2008- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/
#include "auth_all.h"
#include "auth_ticket.h"
#include "batch_job.h"
#include "cctools.h"
#include "copy_stream.h"
#include "debug.h"
#include "getopt_aux.h"
#include "hash_table.h"
#include "int_sizes.h"
#include "itable.h"
#include "link.h"
#include "list.h"
#include "load_average.h"
#include "macros.h"
#include "path.h"
#include "random.h"
#include "rmonitor.h"
#include "stringtools.h"
#include "work_queue.h"
#include "work_queue_catalog.h"
#include "xxmalloc.h"
#include "jx.h"
#include "jx_print.h"
#include "jx_parse.h"
#include "dag.h"
#include "dag_visitors.h"
#include "makeflow_summary.h"
#include "makeflow_gc.h"
#include "makeflow_log.h"
#include "makeflow_wrapper.h"
#include "makeflow_wrapper_docker.h"
#include "makeflow_wrapper_monitor.h"
#include "parser.h"
#include "parser_jx.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
Code organization notes:
- The modules dag/dag_node/dag_file etc contain the data structures that
represent the dag structure by itself. Functions named dag_*() create
and manipulate those data structures, but do not execute the dag itself.
These are shared between makeflow and other tools that read and manipulate
the dag, like makeflow_viz, makeflow_linker, and so forth.
- The modules makeflow/makeflow_log/makeflow_gc etc contain the functions
that execute the dag by invoking batch operations, processing the log, etc.
These are all functions named makeflow_*() to distinguish them from dag_*().
- The separation between dag structure and execution state is imperfect,
because some of the execution state (note states, node counts, etc)
is stored in struct dag and struct dag_node. Perhaps this can be improved.
- All operations on files should use the batch_fs_*() functions, rather
than invoking Unix I/O directly. This is because some batch systems
(Hadoop, Confuga, etc) also include the storage where the files to be
accessed are located.
- APIs like work_queue_* should be indirectly accessed by setting options
in Batch Job using batch_queue_set_option. See batch_job_work_queue.c for
an example.
*/
#define MAX_REMOTE_JOBS_DEFAULT 100
static sig_atomic_t makeflow_abort_flag = 0;
static int makeflow_failed_flag = 0;
static int makeflow_submit_timeout = 3600;
static int makeflow_retry_flag = 0;
static int makeflow_retry_max = MAX_REMOTE_JOBS_DEFAULT;
/* makeflow_gc_method indicates the type of garbage collection
* indicated by the user. Refer to makeflow_gc.h for specifics */
static makeflow_gc_method_t makeflow_gc_method = MAKEFLOW_GC_NONE;
/* Disk size at which point GC is run */
static uint64_t makeflow_gc_size = 0;
/* # of files after which GC is run */
static int makeflow_gc_count = -1;
/* Iterations of wait loop prior ot GC check */
static int makeflow_gc_barrier = 1;
/* Determines next gc_barrier to make checks less frequent with
* large number of tasks */
static double makeflow_gc_task_ratio = 0.05;
static batch_queue_type_t batch_queue_type = BATCH_QUEUE_TYPE_LOCAL;
static struct batch_queue *local_queue = 0;
static struct batch_queue *remote_queue = 0;
static int local_jobs_max = 1;
static int remote_jobs_max = 100;
static char *project = NULL;
static int port = 0;
static int output_len_check = 0;
static int skip_file_check = 0;
static int cache_mode = 1;
static int json_input = 0;
static container_mode_t container_mode = CONTAINER_MODE_NONE;
static char *container_image = NULL;
static char *image_tar = NULL;
/* wait upto this many seconds for an output file of a succesfull task
* to appear on the local filesystem (e.g, to deal with NFS
* semantics. . */
static int file_creation_patience_wait_time = 0;
/* Write a verbose transaction log with SYMBOL tags.
* SYMBOLs are category labels (SYMBOLs should be deprecated
* once weaver/pbui tools are updated.) */
static int log_verbose_mode = 0;
/* Wrapper control functions for wrapping command and adding input/output
* * files. */
static struct makeflow_wrapper *wrapper = 0;
static struct makeflow_monitor *monitor = 0;
/* Generates file list for node based on node files, wrapper
* * input files, and monitor input files. Relies on %% nodeid
* * replacement for monitor file names. */
static struct list *makeflow_generate_input_files( struct dag_node *n, struct makeflow_wrapper *w, struct makeflow_monitor *m )
{
struct list *result = list_duplicate(n->source_files);
if(w){
result = makeflow_wrapper_generate_files(result, w->input_files, n, w);
}
if(m){
result = makeflow_wrapper_generate_files(result, m->wrapper->input_files, n, m->wrapper);
}
return result;
}
static struct list *makeflow_generate_output_files( struct dag_node *n, struct makeflow_wrapper *w, struct makeflow_monitor *m )
{
struct list *result = list_duplicate(n->target_files);
if(w){
result = makeflow_wrapper_generate_files(result, w->output_files, n, w);
}
if(m){
result = makeflow_wrapper_generate_files(result, m->wrapper->output_files, n, m->wrapper);
}
return result;
}
/*
Abort the dag by removing all batch jobs from all queues.
*/
static void makeflow_abort_all(struct dag *d)
{
UINT64_T jobid;
struct dag_node *n;
struct dag_file *f;
printf("got abort signal...\n");
itable_firstkey(d->local_job_table);
while(itable_nextkey(d->local_job_table, &jobid, (void **) &n)) {
printf("aborting local job %" PRIu64 "\n", jobid);
batch_job_remove(local_queue, jobid);
makeflow_log_state_change(d, n, DAG_NODE_STATE_ABORTED);
struct list *outputs = makeflow_generate_output_files(n, wrapper, monitor);
list_first_item(outputs);
while((f = list_next_item(outputs)))
makeflow_clean_file(d, local_queue, f, 0);
makeflow_clean_node(d, local_queue, n, 1);
}
itable_firstkey(d->remote_job_table);
while(itable_nextkey(d->remote_job_table, &jobid, (void **) &n)) {
printf("aborting remote job %" PRIu64 "\n", jobid);
batch_job_remove(remote_queue, jobid);
makeflow_log_state_change(d, n, DAG_NODE_STATE_ABORTED);
struct list *outputs = makeflow_generate_output_files(n, wrapper, monitor);
list_first_item(outputs);
while((f = list_next_item(outputs)))
makeflow_clean_file(d, remote_queue, f, 0);
makeflow_clean_node(d, remote_queue, n, 1);
}
}
static void makeflow_node_force_rerun(struct itable *rerun_table, struct dag *d, struct dag_node *n);
/*
Decide whether to rerun a node based on batch and file system status. The silent
option was added for to prevent confusing debug output when in clean mode. When
clean_mode is not NONE we silence the node reseting output.
*/
void makeflow_node_decide_rerun(struct itable *rerun_table, struct dag *d, struct dag_node *n, int silent)
{
struct dag_file *f;
if(itable_lookup(rerun_table, n->nodeid))
return;
// Below are a bunch of situations when a node has to be rerun.
// If a job was submitted to Condor, then just reconnect to it.
if(n->state == DAG_NODE_STATE_RUNNING && !(n->local_job && local_queue) && batch_queue_type == BATCH_QUEUE_TYPE_CONDOR) {
// Reconnect the Condor jobs
if(!silent) fprintf(stderr, "rule still running: %s\n", n->command);
itable_insert(d->remote_job_table, n->jobid, n);
// Otherwise, we cannot reconnect to the job, so rerun it
} else if(n->state == DAG_NODE_STATE_RUNNING || n->state == DAG_NODE_STATE_FAILED || n->state == DAG_NODE_STATE_ABORTED) {
if(!silent) fprintf(stderr, "will retry failed rule: %s\n", n->command);
goto rerun;
}
// Rerun if an input file has been updated since the last execution.
list_first_item(n->source_files);
while((f = list_next_item(n->source_files))) {
if(dag_file_should_exist(f)) {
continue;
} else {
if(!f->created_by) {
if(!silent) fprintf(stderr, "makeflow: input file %s does not exist and is not created by any rule.\n", f->filename);
exit(1);
} else {
/* If input file is missing, but node completed and file was garbage, then avoid rerunning. */
if(n->state == DAG_NODE_STATE_COMPLETE && f->state == DAG_FILE_STATE_DELETE) {
continue;
}
goto rerun;
}
}
}
// Rerun if an output file is missing.
list_first_item(n->target_files);
while((f = list_next_item(n->target_files))) {
if(dag_file_should_exist(f))
continue;
/* If output file is missing, but node completed and file was gc'ed, then avoid rerunning. */
if(n->state == DAG_NODE_STATE_COMPLETE && f->state == DAG_FILE_STATE_DELETE)
continue;
goto rerun;
}
// Do not rerun this node
return;
rerun:
makeflow_node_force_rerun(rerun_table, d, n);
}
/*
Reset all state to cause a node to be re-run.
*/
void makeflow_node_force_rerun(struct itable *rerun_table, struct dag *d, struct dag_node *n)
{
struct dag_node *p;
struct dag_file *f1;
struct dag_file *f2;
int child_node_found;
if(itable_lookup(rerun_table, n->nodeid))
return;
// Mark this node as having been rerun already
itable_insert(rerun_table, n->nodeid, n);
// Remove running batch jobs
if(n->state == DAG_NODE_STATE_RUNNING) {
if(n->local_job && local_queue) {
batch_job_remove(local_queue, n->jobid);
itable_remove(d->local_job_table, n->jobid);
} else {
batch_job_remove(remote_queue, n->jobid);
itable_remove(d->remote_job_table, n->jobid);
}
}
// Clean up things associated with this node
struct list *outputs = makeflow_generate_output_files(n, wrapper, monitor);
list_first_item(outputs);
while((f1 = list_next_item(outputs)))
makeflow_clean_file(d, remote_queue, f1, 0);
makeflow_clean_node(d, remote_queue, n, 0);
makeflow_log_state_change(d, n, DAG_NODE_STATE_WAITING);
// For each parent node, rerun it if input file was garbage collected
list_first_item(n->source_files);
while((f1 = list_next_item(n->source_files))) {
if(dag_file_should_exist(f1))
continue;
p = f1->created_by;
if(p) {
makeflow_node_force_rerun(rerun_table, d, p);
f1->ref_count += 1;
}
}
// For each child node, rerun it
list_first_item(n->target_files);
while((f1 = list_next_item(n->target_files))) {
for(p = d->nodes; p; p = p->next) {
child_node_found = 0;
list_first_item(p->source_files);
while((f2 = list_next_item(n->source_files))) {
if(!strcmp(f1->filename, f2->filename)) {
child_node_found = 1;
break;
}
}
if(child_node_found) {
makeflow_node_force_rerun(rerun_table, d, p);
}
}
}
}
static void makeflow_prepare_nested_jobs(struct dag *d)
{
/* Update nested jobs with appropriate number of local jobs (total
* local jobs max / maximum number of concurrent nests). */
int dag_nested_width = dag_width(d, 1);
int update_dag_nests = 1;
char *s = getenv("MAKEFLOW_UPDATE_NESTED_JOBS");
if(s)
update_dag_nests = atoi(s);
if(dag_nested_width > 0 && update_dag_nests) {
dag_nested_width = MIN(dag_nested_width, local_jobs_max);
struct dag_node *n;
for(n = d->nodes; n; n = n->next) {
if(n->nested_job && ((n->local_job && local_queue) || batch_queue_type == BATCH_QUEUE_TYPE_LOCAL)) {
char *command = xxmalloc(strlen(n->command) + 20);
sprintf(command, "%s -j %d", n->command, local_jobs_max / dag_nested_width);
free((char *) n->command);
n->command = command;
}
}
}
}
/*
Given a file, return the string that identifies it appropriately
for the given batch system, combining the local and remote name
and making substitutions according to the node.
*/
static char * makeflow_file_format( struct dag_node *n, struct dag_file *f, struct batch_queue *queue, struct makeflow_wrapper *w, struct makeflow_monitor *m)
{
const char *remotename = dag_node_get_remote_name(n, f->filename);
if(!remotename && w) remotename = makeflow_wrapper_get_remote_name(w, n->d, f->filename);
if(!remotename && m) remotename = makeflow_wrapper_get_remote_name(m->wrapper, n->d, f->filename);
if(!remotename) remotename = f->filename;
switch (batch_queue_get_type(queue)) {
case BATCH_QUEUE_TYPE_WORK_QUEUE:
return string_format("%s=%s,", f->filename, remotename);
default:
return string_format("%s,", f->filename);
}
}
/*
Given a list of files, set theses files' states to EXPECT.
*/
void makeflow_log_file_expectation( struct dag *d, struct list *file_list )
{
struct dag_file *f;
if(!file_list) return ;
list_first_item(file_list);
while((f=list_next_item(file_list))) {
makeflow_log_file_state_change(d, f, DAG_FILE_STATE_EXPECT);
}
}
/*
Given a list of files, add the files to the given string.
Returns the original string, realloced if necessary
*/
static char * makeflow_file_list_format( struct dag_node *node, char *file_str, struct list *file_list, struct batch_queue *queue, struct makeflow_wrapper *w, struct makeflow_monitor *m )
{
struct dag_file *file;
if(!file_str) file_str = strdup("");
if(!file_list) return file_str;
list_first_item(file_list);
while((file=list_next_item(file_list))) {
char *f = makeflow_file_format(node,file,queue,w,m);
file_str = string_combine(file_str,f);
free(f);
}
return file_str;
}
/*
Submit one fully formed job, retrying failures up to the makeflow_submit_timeout.
This is necessary because busy batch systems occasionally do not accept a job submission.
*/
static batch_job_id_t makeflow_node_submit_retry( struct batch_queue *queue, const char *command, const char *input_files, const char *output_files, struct jx *envlist, const struct rmsummary *resources)
{
time_t stoptime = time(0) + makeflow_submit_timeout;
int waittime = 1;
batch_job_id_t jobid = 0;
/* Display the fully elaborated command, just like Make does. */
printf("submitting job: %s\n", command);
while(1) {
jobid = batch_job_submit(queue, command, input_files, output_files, envlist, resources);
if(jobid >= 0) {
printf("submitted job %"PRIbjid"\n", jobid);
return jobid;
}
fprintf(stderr, "couldn't submit batch job, still trying...\n");
if(makeflow_abort_flag) break;
if(time(0) > stoptime) {
fprintf(stderr, "unable to submit job after %d seconds!\n", makeflow_submit_timeout);
break;
}
sleep(waittime);
waittime *= 2;
if(waittime > 60) waittime = 60;
}
return 0;
}
/*
Submit a node to the appropriate batch system, after materializing
the necessary list of input and output files, and applying all
wrappers and options.
*/
static void makeflow_node_submit(struct dag *d, struct dag_node *n)
{
struct batch_queue *queue;
if(n->local_job && local_queue) {
queue = local_queue;
} else {
queue = remote_queue;
}
struct list *input_list = makeflow_generate_input_files(n, wrapper, monitor);
struct list *output_list = makeflow_generate_output_files(n, wrapper, monitor);
/* Create strings for all the files mentioned by this node. */
char *input_files = makeflow_file_list_format(n, 0, input_list, queue, wrapper, monitor);
char *output_files = makeflow_file_list_format(n, 0, output_list, queue, wrapper, monitor);
/* Apply the wrapper(s) to the command, if it is (they are) enabled. */
char *command = strdup(n->command);
command = makeflow_wrap_wrapper(command, n, wrapper);
command = makeflow_wrap_monitor(command, n, monitor);
/* Before setting the batch job options (stored in the "BATCH_OPTIONS"
* variable), we must save the previous global queue value, and then
* restore it after we submit. */
struct dag_variable_lookup_set s = { d, n->category, n, NULL };
char *batch_options = dag_variable_lookup_string("BATCH_OPTIONS", &s);
char *previous_batch_options = NULL;
if(batch_queue_get_option(queue, "batch-options"))
previous_batch_options = xxstrdup(batch_queue_get_option(queue, "batch-options"));
if(batch_options) {
debug(D_MAKEFLOW_RUN, "Batch options: %s\n", batch_options);
batch_queue_set_option(queue, "batch-options", batch_options);
free(batch_options);
}
/* Generate the environment vars specific to this node. */
struct jx *envlist = dag_node_env_create(d,n);
/* Logs the creation of output files. */
makeflow_log_file_expectation(d, output_list);
/* Now submit the actual job, retrying failures as needed. */
n->jobid = makeflow_node_submit_retry(queue,command,input_files,output_files,envlist, dag_node_dynamic_label(n));
/* Restore old batch job options. */
if(previous_batch_options) {
batch_queue_set_option(queue, "batch-options", previous_batch_options);
free(previous_batch_options);
}
/* Update all of the necessary data structures. */
if(n->jobid >= 0) {
makeflow_log_state_change(d, n, DAG_NODE_STATE_RUNNING);
if(n->local_job && local_queue) {
itable_insert(d->local_job_table, n->jobid, n);
} else {
itable_insert(d->remote_job_table, n->jobid, n);
}
} else {
makeflow_log_state_change(d, n, DAG_NODE_STATE_FAILED);
makeflow_failed_flag = 1;
}
free(command);
free(input_list);
free(output_list);
free(input_files);
free(output_files);
jx_delete(envlist);
}
static int makeflow_node_ready(struct dag *d, struct dag_node *n)
{
struct dag_file *f;
if(n->state != DAG_NODE_STATE_WAITING)
return 0;
if(n->local_job && local_queue) {
if(dag_local_jobs_running(d) >= local_jobs_max)
return 0;
} else {
if(dag_remote_jobs_running(d) >= remote_jobs_max)
return 0;
}
list_first_item(n->source_files);
while((f = list_next_item(n->source_files))) {
if(dag_file_should_exist(f)) {
continue;
} else {
return 0;
}
}
return 1;
}
/*
Find all jobs ready to be run, then submit them.
*/
static void makeflow_dispatch_ready_jobs(struct dag *d)
{
struct dag_node *n;
for(n = d->nodes; n; n = n->next) {
if(dag_remote_jobs_running(d) >= remote_jobs_max && dag_local_jobs_running(d) >= local_jobs_max)
break;
if(makeflow_node_ready(d, n)) {
makeflow_node_submit(d, n);
}
}
}
/*
Check the the indicated file was created and log, error, or retry as appropriate.
*/
int makeflow_node_check_file_was_created(struct dag_node *n, struct dag_file *f)
{
struct stat buf;
int file_created = 0;
int64_t start_check = time(0);
while(!file_created) {
if(batch_fs_stat(remote_queue, f->filename, &buf) < 0) {
fprintf(stderr, "%s did not create file %s\n", n->command, f->filename);
}
else if(output_len_check && buf.st_size <= 0) {
debug(D_MAKEFLOW_RUN, "%s created a file of length %ld\n", n->command, (long) buf.st_size);
}
else {
/* File was created and has length larger than zero. */
debug(D_MAKEFLOW_RUN, "File %s created by rule %d.\n", f->filename, n->nodeid);
makeflow_log_file_state_change(n->d, f, DAG_FILE_STATE_EXISTS);
file_created = 1;
break;
}
if(file_creation_patience_wait_time > 0 && time(0) - start_check < file_creation_patience_wait_time) {
/* Failed to see the file. Sleep and try again. */
debug(D_MAKEFLOW_RUN, "Checking again for file %s.\n", f->filename);
sleep(1);
} else {
/* Failed was not seen by makeflow in the aloted tries. */
debug(D_MAKEFLOW_RUN, "File %s was not created by rule %d.\n", f->filename, n->nodeid);
file_created = 0;
break;
}
}
return file_created;
}
/*
Mark the given task as completing, using the batch_job_info completion structure provided by batch_job.
*/
static void makeflow_node_complete(struct dag *d, struct dag_node *n, struct batch_job_info *info)
{
struct dag_file *f;
int job_failed = 0;
int monitor_retried = 0;
if(n->state != DAG_NODE_STATE_RUNNING)
return;
if(monitor) {
char *nodeid = string_format("%d",n->nodeid);
char *log_name_prefix = string_replace_percents(monitor->log_prefix, nodeid);
char *summary_name = string_format("%s.summary", log_name_prefix);
if(n->resources_measured)
rmsummary_delete(n->resources_measured);
n->resources_measured = rmsummary_parse_file_single(summary_name);
category_accumulate_summary(n->category, n->resources_measured, NULL);
free(nodeid);
free(log_name_prefix);
free(summary_name);
}
struct list *outputs = makeflow_generate_output_files(n, wrapper, monitor);
if(info->exited_normally && info->exit_code == 0) {
list_first_item(outputs);
while((f = list_next_item(outputs))) {
if(!makeflow_node_check_file_was_created(n, f))
{
job_failed = 1;
}
}
} else {
if(info->exited_normally) {
fprintf(stderr, "%s failed with exit code %d\n", n->command, info->exit_code);
} else {
fprintf(stderr, "%s crashed with signal %d (%s)\n", n->command, info->exit_signal, strsignal(info->exit_signal));
}
job_failed = 1;
}
if(job_failed) {
makeflow_log_state_change(d, n, DAG_NODE_STATE_FAILED);
/* Clean files created in node. Clean existing and expected and record deletion. */
list_first_item(outputs);
while((f = list_next_item(outputs))) {
if(f->state == DAG_FILE_STATE_EXPECT) {
makeflow_clean_file(d, remote_queue, f, 1);
} else {
makeflow_clean_file(d, remote_queue, f, 0);
}
}
if(monitor && info->exit_code == RM_OVERFLOW)
{
debug(D_MAKEFLOW_RUN, "rule %d failed because it exceeded the resources limits.\n", n->nodeid);
if(n->resources_measured && n->resources_measured->limits_exceeded)
{
char *str = rmsummary_print_string(n->resources_measured->limits_exceeded, 1);
debug(D_MAKEFLOW_RUN, "%s", str);
free(str);
}
category_allocation_t next = category_next_label(n->category, n->resource_request, /* resource overflow */ 1, n->resources_requested, n->resources_measured);
if(next != CATEGORY_ALLOCATION_ERROR) {
debug(D_MAKEFLOW_RUN, "Rule %d resubmitted using new resource allocation.\n", n->nodeid);
n->resource_request = next;
makeflow_log_state_change(d, n, DAG_NODE_STATE_WAITING);
monitor_retried = 1;
}
}
if(!monitor_retried) {
if(makeflow_retry_flag || info->exit_code == 101) {
n->failure_count++;
if(n->failure_count > makeflow_retry_max) {
notice(D_MAKEFLOW_RUN, "job %s failed too many times.", n->command);
makeflow_failed_flag = 1;
} else {
notice(D_MAKEFLOW_RUN, "will retry failed job %s", n->command);
makeflow_log_state_change(d, n, DAG_NODE_STATE_WAITING);
}
}
else
{
makeflow_failed_flag = 1;
}
}
} else {
/* Mark source files that have been used by this node */
list_first_item(n->source_files);
while((f = list_next_item(n->source_files))) {
f->ref_count+= -1;
if(f->ref_count == 0 && f->state == DAG_FILE_STATE_EXISTS)
makeflow_log_file_state_change(d, f, DAG_FILE_STATE_COMPLETE);
}
makeflow_log_state_change(d, n, DAG_NODE_STATE_COMPLETE);
}
}
/*
Check the dag for consistency, and emit errors if input dependencies, etc are missing.
*/
static int makeflow_check(struct dag *d)
{
struct stat buf;
struct dag_node *n;
struct dag_file *f;
int error = 0;
debug(D_MAKEFLOW_RUN, "checking rules for consistency...\n");
for(n = d->nodes; n; n = n->next) {
list_first_item(n->source_files);
while((f = list_next_item(n->source_files))) {
if(f->created_by) {
continue;
}
if(skip_file_check || batch_fs_stat(remote_queue, f->filename, &buf) >= 0) {
continue;
}
fprintf(stderr, "makeflow: %s does not exist, and is not created by any rule.\n", f->filename);
error++;
}
}
if(error) {
fprintf(stderr, "makeflow: found %d errors during consistency check.\n", error);
return 0;
} else {
return 1;
}
}
/*
Used to check that features used are supported by the batch system.
This would be where we added checking of selected options to verify they
are supported by the batch system, such as work_queue specific options.
*/
static int makeflow_check_batch_consistency(struct dag *d)
{
struct dag_node *n;
int error = 0;
debug(D_MAKEFLOW_RUN, "checking for consistency of batch system support...\n");
for(n = d->nodes; n; n = n->next) {
if(itable_size(n->remote_names) > 0 || (wrapper && wrapper->uses_remote_rename)){
if(n->local_job) {
debug(D_ERROR, "remote renaming is not supported on locally. Rule %d.\n", n->nodeid);
error = 1;
break;
} else if (!batch_queue_supports_feature(remote_queue, "remote_rename")) {
debug(D_ERROR, "remote renaming is not supported on selected batch system. Rule %d.\n", n->nodeid);
error = 1;
break;
}
}
}
if(error) {
return 0;
} else {
return 1;
}
}
/*
Main loop for running a makeflow: submit jobs, wait for completion, keep going until everything done.
*/
static void makeflow_run( struct dag *d )
{
struct dag_node *n;
batch_job_id_t jobid;
struct batch_job_info info;
while(!makeflow_abort_flag) {
makeflow_dispatch_ready_jobs(d);
if(dag_local_jobs_running(d)==0 && dag_remote_jobs_running(d)==0 )
break;
if(dag_remote_jobs_running(d)) {
int tmp_timeout = 5;
jobid = batch_job_wait_timeout(remote_queue, &info, time(0) + tmp_timeout);
if(jobid > 0) {
printf("job %"PRIbjid" completed\n",jobid);
debug(D_MAKEFLOW_RUN, "Job %" PRIbjid " has returned.\n", jobid);
n = itable_remove(d->remote_job_table, jobid);
if(n)
makeflow_node_complete(d, n, &info);
}
}
if(dag_local_jobs_running(d)) {
time_t stoptime;
int tmp_timeout = 5;
if(dag_remote_jobs_running(d)) {
stoptime = time(0);
} else {
stoptime = time(0) + tmp_timeout;
}
jobid = batch_job_wait_timeout(local_queue, &info, stoptime);
if(jobid > 0) {
debug(D_MAKEFLOW_RUN, "Job %" PRIbjid " has returned.\n", jobid);
n = itable_remove(d->local_job_table, jobid);
if(n)
makeflow_node_complete(d, n, &info);
}
}
/* Rather than try to garbage collect after each time in this
* wait loop, perform garbage collection after a proportional
* amount of tasks have passed. */
makeflow_gc_barrier--;
if(makeflow_gc_method != MAKEFLOW_GC_NONE && makeflow_gc_barrier == 0) {
makeflow_gc(d, remote_queue, makeflow_gc_method, makeflow_gc_size, makeflow_gc_count);
makeflow_gc_barrier = MAX(d->nodeid_counter * makeflow_gc_task_ratio, 1);
}
}
if(makeflow_abort_flag) {
makeflow_abort_all(d);
} else {
if(!makeflow_failed_flag && makeflow_gc_method != MAKEFLOW_GC_NONE) {
makeflow_gc(d,remote_queue,MAKEFLOW_GC_ALL,0,0);
}
}
}
/*
Signal handler to catch abort signals. Note that permissible actions in signal handlers are very limited, so we emit a message to the terminal and update a global variable noticed by makeflow_run.
*/
static void handle_abort(int sig)
{
static int abort_count_to_exit = 5;
abort_count_to_exit -= 1;
int fd = open("/dev/tty", O_WRONLY);
if (fd >= 0) {
char buf[256];
snprintf(buf, sizeof(buf), "Received signal %d, will try to clean up remote resources. Send signal %d more times to force exit.\n", sig, abort_count_to_exit);
write(fd, buf, strlen(buf));
close(fd);
}
if (abort_count_to_exit == 1)
signal(sig, SIG_DFL);
makeflow_abort_flag = 1;
}
static void show_help_run(const char *cmd)
{
printf("Use: %s [options] <dagfile>\n", cmd);
printf("Frequently used options:\n\n");
printf(" %-30s Clean up: remove logfile and all targets. Optional specification [intermediates, outputs] removes only the indicated files.\n", "-c,--clean=<type>");
printf(" %-30s Batch system type: (default is local)\n", "-T,--batch-type=<type>");
printf(" %-30s %s\n\n", "", batch_queue_type_string());
printf("Other options are:\n");
printf(" %-30s Advertise the master information to a catalog server.\n", "-a,--advertise");
printf(" %-30s Specify path to Amazon credentials (for use with -T amazon)\n", "--amazon-credentials");
printf(" %-30s Specify amazon-ami (for use with -T amazon)\n", "--amazon-ami");
printf(" %-30s Disable the check for AFS. (experts only.)\n", "-A,--disable-afs-check");
printf(" %-30s Add these options to all batch submit files.\n", "-B,--batch-options=<options>");
printf(" %-30s Set catalog server to <catalog>. Format: HOSTNAME:PORT \n", "-C,--catalog-server=<catalog>");
printf(" %-30s Enable debugging for this subsystem\n", "-d,--debug=<subsystem>");
printf(" %-30s Write summary of workflow to this file upon success or failure.\n", "-f,--summary-log=<file>");
printf(" %-30s Work Queue fast abort multiplier. (default is deactivated)\n", "-F,--wq-fast-abort=<#>");
printf(" %-30s Show this help screen.\n", "-h,--help");
printf(" %-30s Max number of local jobs to run at once. (default is # of cores)\n", "-j,--max-local=<#>");
printf(" %-30s Max number of remote jobs to run at once.\n", "-J,--max-remote=<#>");
printf(" (default %d for -Twq, %d otherwise.)\n", 10*MAX_REMOTE_JOBS_DEFAULT, MAX_REMOTE_JOBS_DEFAULT );
printf(" %-30s Use this file for the makeflow log. (default is X.makeflowlog)\n", "-l,--makeflow-log=<logfile>");
printf(" %-30s Use this file for the batch system log. (default is X.<type>log)\n", "-L,--batch-log=<logfile>");
printf(" %-30s Send summary of workflow to this email address upon success or failure.\n", "-m,--email=<email>");
printf(" %-30s Set the project name to <project>\n", "-N,--project-name=<project>");
printf(" %-30s Send debugging to this file. (can also be :stderr, :stdout, :syslog, or :journal)\n", "-o,--debug-file=<file>");
printf(" %-30s Rotate debug file once it reaches this size.\n", " --debug-rotate-max=<bytes>");
printf(" %-30s Password file for authenticating workers.\n", " --password");
printf(" %-30s Port number to use with Work Queue. (default is %d, 0=arbitrary)\n", "-p,--port=<port>", WORK_QUEUE_DEFAULT_PORT);
printf(" %-30s Priority. Higher the value, higher the priority.\n", "-P,--priority=<integer>");
printf(" %-30s Automatically retry failed batch jobs up to %d times.\n", "-R,--retry", makeflow_retry_max);
printf(" %-30s Automatically retry failed batch jobs up to n times.\n", "-r,--retry-count=<n>");
printf(" %-30s Wait for output files to be created upto n seconds (e.g., to deal with NFS semantics).\n", " --wait-for-files-upto=<n>");
printf(" %-30s Time to retry failed batch job submission. (default is %ds)\n", "-S,--submission-timeout=<#>", makeflow_submit_timeout);
printf(" %-30s Work Queue keepalive timeout. (default is %ds)\n", "-t,--wq-keepalive-timeout=<#>", WORK_QUEUE_DEFAULT_KEEPALIVE_TIMEOUT);
printf(" %-30s Work Queue keepalive interval. (default is %ds)\n", "-u,--wq-keepalive-interval=<#>", WORK_QUEUE_DEFAULT_KEEPALIVE_INTERVAL);
printf(" %-30s Show version string\n", "-v,--version");
printf(" %-30s Work Queue scheduling algorithm. (time|files|fcfs)\n", "-W,--wq-schedule=<mode>");
printf(" %-30s Working directory for the batch system.\n", " --working-dir=<dir|url>");
printf(" %-30s Wrap all commands with this prefix.\n", " --wrapper=<cmd>");
printf(" %-30s Wrapper command requires this input file.\n", " --wrapper-input=<cmd>");
printf(" %-30s Wrapper command produces this output file.\n", " --wrapper-output=<cmd>");
printf(" %-30s Change directory: chdir to enable executing the Makefile in other directory.\n", "-X,--change-directory");
printf(" %-30s Force failure on zero-length output files \n", "-z,--zero-length-error");
printf(" %-30s Select port at random and write it to this file.\n", "-Z,--port-file=<file>");
printf(" %-30s Disable Work Queue caching. (default is false)\n", " --disable-wq-cache");
printf(" %-30s Add node id symbol tags in the makeflow log. (default is false)\n", " --log-verbose");
printf(" %-30s Run each task with a container based on this docker image.\n", "--docker=<image>");
printf(" %-30s Load docker image from the tar file.\n", "--docker-tar=<tar file>");
printf(" %-30s Indicate user trusts inputs exist.\n", "--skip-file-check");
printf(" %-30s Indicate preferred master connection. Choose one of by_ip or by_hostname. (default is by_ip)\n", "--work-queue-preferred-connection");
printf(" %-30s Use JSON format rather than Make-style format for the input file.\n", "--json");
printf("\n*Monitor Options:\n\n");
printf(" %-30s Enable the resource monitor, and write the monitor logs to <dir>.\n", "--monitor=<dir>");
printf(" %-30s Set monitor interval to <#> seconds. (default is 1 second)\n", " --monitor-interval=<#>");
printf(" %-30s Enable monitor time series. (default is disabled)\n", " --monitor-with-time-series");
printf(" %-30s Enable monitoring of openened files. (default is disabled)\n", " --monitor-with-opened-files");
printf(" %-30s Format for monitor logs. (default %s)\n", " --monitor-log-fmt=<fmt>", DEFAULT_MONITOR_LOG_FORMAT);
}
int main(int argc, char *argv[])
{
int c;
const char *dagfile;
char *change_dir = NULL;
char *batchlogfilename = NULL;
const char *batch_submit_options = getenv("BATCH_OPTIONS");
makeflow_clean_depth clean_mode = MAKEFLOW_CLEAN_NONE;
char *email_summary_to = NULL;
int explicit_remote_jobs_max = 0;
int explicit_local_jobs_max = 0;
char *logfilename = NULL;
int port_set = 0;
timestamp_t runtime = 0;
int skip_afs_check = 0;
timestamp_t time_completed = 0;
const char *work_queue_keepalive_interval = NULL;
const char *work_queue_keepalive_timeout = NULL;
const char *work_queue_master_mode = "standalone";
const char *work_queue_port_file = NULL;
double wq_option_fast_abort_multiplier = -1.0;
const char *amazon_credentials = NULL;
const char *amazon_ami = NULL;
const char *priority = NULL;
char *work_queue_password = NULL;
char *wq_wait_queue_size = 0;
int did_explicit_auth = 0;
char *chirp_tickets = NULL;
char *working_dir = NULL;
char *work_queue_preferred_connection = NULL;
char *write_summary_to = NULL;
char *s;
char *log_dir = NULL;
char *log_format = NULL;
category_mode_t allocation_mode = CATEGORY_ALLOCATION_MODE_FIXED;
random_init();
debug_config(argv[0]);
s = getenv("MAKEFLOW_BATCH_QUEUE_TYPE");
if(s) {
batch_queue_type = batch_queue_type_from_string(s);
if(batch_queue_type == BATCH_QUEUE_TYPE_UNKNOWN) {
fprintf(stderr, "makeflow: unknown batch queue type: %s (from $MAKEFLOW_BATCH_QUEUE_TYPE)\n", s);
return 1;
}
}
s = getenv("WORK_QUEUE_MASTER_MODE");
if(s) {
work_queue_master_mode = s;
}
s = getenv("WORK_QUEUE_NAME");
if(s) {
project = xxstrdup(s);
}
s = getenv("WORK_QUEUE_FAST_ABORT_MULTIPLIER");
if(s) {
wq_option_fast_abort_multiplier = atof(s);
}
enum {
LONG_OPT_AUTH = UCHAR_MAX+1,
LONG_OPT_DEBUG_ROTATE_MAX,
LONG_OPT_DISABLE_BATCH_CACHE,
LONG_OPT_DOT_CONDENSE,
LONG_OPT_FILE_CREATION_PATIENCE_WAIT_TIME,
LONG_OPT_GC_SIZE,
LONG_OPT_MONITOR,
LONG_OPT_MONITOR_INTERVAL,
LONG_OPT_MONITOR_LOG_NAME,
LONG_OPT_MONITOR_OPENED_FILES,
LONG_OPT_MONITOR_TIME_SERIES,
LONG_OPT_PASSWORD,
LONG_OPT_TICKETS,
LONG_OPT_VERBOSE_PARSING,
LONG_OPT_LOG_VERBOSE_MODE,
LONG_OPT_WORKING_DIR,
LONG_OPT_PREFERRED_CONNECTION,
LONG_OPT_WQ_WAIT_FOR_WORKERS,
LONG_OPT_WRAPPER,
LONG_OPT_WRAPPER_INPUT,
LONG_OPT_WRAPPER_OUTPUT,
LONG_OPT_DOCKER,
LONG_OPT_DOCKER_TAR,
LONG_OPT_AMAZON_CREDENTIALS,
LONG_OPT_AMAZON_AMI,
LONG_OPT_JSON,
LONG_OPT_SKIP_FILE_CHECK,
LONG_OPT_ALLOCATION_MODE
};
static const struct option long_options_run[] = {
{"advertise", no_argument, 0, 'a'},
{"allocation", required_argument, 0, LONG_OPT_ALLOCATION_MODE},
{"auth", required_argument, 0, LONG_OPT_AUTH},
{"batch-log", required_argument, 0, 'L'},
{"batch-options", required_argument, 0, 'B'},
{"batch-type", required_argument, 0, 'T'},
{"catalog-server", required_argument, 0, 'C'},
{"clean", optional_argument, 0, 'c'},
{"debug", required_argument, 0, 'd'},
{"debug-file", required_argument, 0, 'o'},
{"debug-rotate-max", required_argument, 0, LONG_OPT_DEBUG_ROTATE_MAX},
{"disable-afs-check", no_argument, 0, 'A'},
{"disable-cache", no_argument, 0, LONG_OPT_DISABLE_BATCH_CACHE},
{"email", required_argument, 0, 'm'},
{"wait-for-files-upto", required_argument, 0, LONG_OPT_FILE_CREATION_PATIENCE_WAIT_TIME},
{"gc", required_argument, 0, 'g'},
{"gc-size", required_argument, 0, LONG_OPT_GC_SIZE},
{"gc-count", required_argument, 0, 'G'},
{"wait-for-files-upto", required_argument, 0, LONG_OPT_FILE_CREATION_PATIENCE_WAIT_TIME},
{"help", no_argument, 0, 'h'},
{"makeflow-log", required_argument, 0, 'l'},
{"max-local", required_argument, 0, 'j'},
{"max-remote", required_argument, 0, 'J'},
{"monitor", required_argument, 0, LONG_OPT_MONITOR},
{"monitor-interval", required_argument, 0, LONG_OPT_MONITOR_INTERVAL},
{"monitor-log-name", required_argument, 0, LONG_OPT_MONITOR_LOG_NAME},
{"monitor-with-opened-files", no_argument, 0, LONG_OPT_MONITOR_OPENED_FILES},
{"monitor-with-time-series", no_argument, 0, LONG_OPT_MONITOR_TIME_SERIES},
{"password", required_argument, 0, LONG_OPT_PASSWORD},
{"port", required_argument, 0, 'p'},
{"port-file", required_argument, 0, 'Z'},
{"priority", required_argument, 0, 'P'},
{"project-name", required_argument, 0, 'N'},
{"retry", no_argument, 0, 'R'},
{"retry-count", required_argument, 0, 'r'},
{"show-output", no_argument, 0, 'O'},
{"submission-timeout", required_argument, 0, 'S'},
{"summary-log", required_argument, 0, 'f'},
{"tickets", required_argument, 0, LONG_OPT_TICKETS},
{"version", no_argument, 0, 'v'},
{"log-verbose", no_argument, 0, LONG_OPT_LOG_VERBOSE_MODE},
{"working-dir", required_argument, 0, LONG_OPT_WORKING_DIR},
{"skip-file-check", no_argument, 0, LONG_OPT_SKIP_FILE_CHECK},
{"work-queue-preferred-connection", required_argument, 0, LONG_OPT_PREFERRED_CONNECTION},
{"wq-estimate-capacity", no_argument, 0, 'E'},
{"wq-fast-abort", required_argument, 0, 'F'},
{"wq-keepalive-interval", required_argument, 0, 'u'},
{"wq-keepalive-timeout", required_argument, 0, 't'},
{"wq-schedule", required_argument, 0, 'W'},
{"wq-wait-queue-size", required_argument, 0, LONG_OPT_WQ_WAIT_FOR_WORKERS},
{"wrapper", required_argument, 0, LONG_OPT_WRAPPER},
{"wrapper-input", required_argument, 0, LONG_OPT_WRAPPER_INPUT},
{"wrapper-output", required_argument, 0, LONG_OPT_WRAPPER_OUTPUT},
{"zero-length-error", no_argument, 0, 'z'},
{"change-directory", required_argument, 0, 'X'},
{"docker", required_argument, 0, LONG_OPT_DOCKER},
{"docker-tar", required_argument, 0, LONG_OPT_DOCKER_TAR},
{"amazon-credentials", required_argument, 0, LONG_OPT_AMAZON_CREDENTIALS},
{"amazon-ami", required_argument, 0, LONG_OPT_AMAZON_AMI},
{"json", no_argument, 0, LONG_OPT_JSON},
{0, 0, 0, 0}
};
static const char option_string_run[] = "aAB:c::C:d:Ef:F:g:G:hj:J:l:L:m:M:N:o:Op:P:r:RS:t:T:u:vW:X:zZ:";
while((c = getopt_long(argc, argv, option_string_run, long_options_run, NULL)) >= 0) {
switch (c) {
case 'a':
work_queue_master_mode = "catalog";
break;
case 'A':
skip_afs_check = 1;
break;
case 'B':
batch_submit_options = optarg;
break;
case 'c':
clean_mode = MAKEFLOW_CLEAN_ALL;
if(optarg){
if(strcasecmp(optarg, "intermediates") == 0){
clean_mode = MAKEFLOW_CLEAN_INTERMEDIATES;
} else if(strcasecmp(optarg, "outputs") == 0){
clean_mode = MAKEFLOW_CLEAN_OUTPUTS;
} else if(strcasecmp(optarg, "all") != 0){
fprintf(stderr, "makeflow: unknown clean option %s", optarg);
exit(1);
}
}
break;
case 'C':
setenv("CATALOG_HOST", optarg, 1);
break;
case 'd':
debug_flags_set(optarg);
break;
case 'E':
// This option is deprecated. Capacity estimation is now on by default.
break;
case LONG_OPT_AUTH:
if (!auth_register_byname(optarg))
fatal("could not register authentication method `%s': %s", optarg, strerror(errno));
did_explicit_auth = 1;
break;
case LONG_OPT_TICKETS:
chirp_tickets = strdup(optarg);
break;
case 'f':
write_summary_to = xxstrdup(optarg);
break;
case 'F':
wq_option_fast_abort_multiplier = atof(optarg);
break;
case 'g':
if(strcasecmp(optarg, "none") == 0) {
makeflow_gc_method = MAKEFLOW_GC_NONE;
} else if(strcasecmp(optarg, "ref_count") == 0) {
makeflow_gc_method = MAKEFLOW_GC_COUNT;
if(makeflow_gc_count < 0)
makeflow_gc_count = 16; /* Try to collect at most 16 files. */
} else if(strcasecmp(optarg, "on_demand") == 0) {
makeflow_gc_method = MAKEFLOW_GC_ON_DEMAND;
if(makeflow_gc_count < 0)
makeflow_gc_count = 16; /* Try to collect at most 16 files. */
} else if(strcasecmp(optarg, "all") == 0) {
makeflow_gc_method = MAKEFLOW_GC_ALL;
if(makeflow_gc_count < 0)
makeflow_gc_count = 1 << 14; /* Inode threshold of 2^14. */
} else {
fprintf(stderr, "makeflow: invalid garbage collection method: %s\n", optarg);
exit(1);
}
break;
case LONG_OPT_GC_SIZE:
makeflow_gc_size = string_metric_parse(optarg);
break;
case 'G':
makeflow_gc_count = atoi(optarg);
break;
case LONG_OPT_FILE_CREATION_PATIENCE_WAIT_TIME:
file_creation_patience_wait_time = MAX(0,atoi(optarg));
break;
case 'h':
show_help_run(argv[0]);
return 0;
case 'j':
explicit_local_jobs_max = atoi(optarg);
break;
case 'J':
explicit_remote_jobs_max = atoi(optarg);
break;
case 'l':
logfilename = xxstrdup(optarg);
break;
case 'L':
batchlogfilename = xxstrdup(optarg);
break;
case 'm':
email_summary_to = xxstrdup(optarg);
break;
case LONG_OPT_MONITOR:
if (!monitor) monitor = makeflow_monitor_create();
if(log_dir) free(log_dir);
log_dir = xxstrdup(optarg);
break;
case LONG_OPT_MONITOR_INTERVAL:
if (!monitor) monitor = makeflow_monitor_create();
monitor->interval = atoi(optarg);
break;
case LONG_OPT_MONITOR_TIME_SERIES:
if (!monitor) monitor = makeflow_monitor_create();
monitor->enable_time_series = 1;
break;
case LONG_OPT_MONITOR_OPENED_FILES:
if (!monitor) monitor = makeflow_monitor_create();
monitor->enable_list_files = 1;
break;
case LONG_OPT_MONITOR_LOG_NAME:
if (!monitor) monitor = makeflow_monitor_create();
if(log_format) free(log_format);
log_format = xxstrdup(optarg);
break;
case LONG_OPT_AMAZON_CREDENTIALS:
amazon_credentials = xxstrdup(optarg);
break;
case LONG_OPT_AMAZON_AMI:
amazon_ami = xxstrdup(optarg);
break;
case 'M':
case 'N':
free(project);
project = xxstrdup(optarg);
work_queue_master_mode = "catalog";
break;
case 'o':
debug_config_file(optarg);
break;
case 'p':
port_set = 1;
port = atoi(optarg);
break;
case 'P':
priority = optarg;
break;
case 'r':
makeflow_retry_flag = 1;
makeflow_retry_max = atoi(optarg);
break;
case 'R':
makeflow_retry_flag = 1;
break;
case 'S':
makeflow_submit_timeout = atoi(optarg);
break;
case 't':
work_queue_keepalive_timeout = optarg;
break;
case 'T':
batch_queue_type = batch_queue_type_from_string(optarg);
if(batch_queue_type == BATCH_QUEUE_TYPE_UNKNOWN) {
fprintf(stderr, "makeflow: unknown batch queue type: %s\n", optarg);
return 1;
}
break;
case 'u':
work_queue_keepalive_interval = optarg;
break;
case 'v':
cctools_version_print(stdout, argv[0]);
return 0;
case 'W':
if(!strcmp(optarg, "files")) {
wq_option_scheduler = WORK_QUEUE_SCHEDULE_FILES;
} else if(!strcmp(optarg, "time")) {
wq_option_scheduler = WORK_QUEUE_SCHEDULE_TIME;
} else if(!strcmp(optarg, "fcfs")) {
wq_option_scheduler = WORK_QUEUE_SCHEDULE_FCFS;
} else {
fprintf(stderr, "makeflow: unknown scheduling mode %s\n", optarg);
return 1;
}
break;
case 'z':
output_len_check = 1;
break;
case 'Z':
work_queue_port_file = optarg;
port = 0;
port_set = 1; //WQ is going to set the port, so we continue as if already set.
break;
case LONG_OPT_PASSWORD:
if(copy_file_to_buffer(optarg, &work_queue_password, NULL) < 0) {
fprintf(stderr, "makeflow: couldn't open %s: %s\n", optarg, strerror(errno));
return 1;
}
break;
case LONG_OPT_DISABLE_BATCH_CACHE:
cache_mode = 0;
break;
case LONG_OPT_WQ_WAIT_FOR_WORKERS:
wq_wait_queue_size = optarg;
break;
case LONG_OPT_WORKING_DIR:
free(working_dir);
working_dir = xxstrdup(optarg);
break;
case LONG_OPT_PREFERRED_CONNECTION:
free(work_queue_preferred_connection);
work_queue_preferred_connection = xxstrdup(optarg);
break;
case LONG_OPT_DEBUG_ROTATE_MAX:
debug_config_file_size(string_metric_parse(optarg));
break;
case LONG_OPT_LOG_VERBOSE_MODE:
log_verbose_mode = 1;
break;
case LONG_OPT_WRAPPER:
if(!wrapper) wrapper = makeflow_wrapper_create();
makeflow_wrapper_add_command(wrapper, optarg);
break;
case LONG_OPT_WRAPPER_INPUT:
if(!wrapper) wrapper = makeflow_wrapper_create();
makeflow_wrapper_add_input_file(wrapper, optarg);
break;
case LONG_OPT_WRAPPER_OUTPUT:
if(!wrapper) wrapper = makeflow_wrapper_create();
makeflow_wrapper_add_output_file(wrapper, optarg);
break;
case LONG_OPT_DOCKER:
if(!wrapper) wrapper = makeflow_wrapper_create();
container_mode = CONTAINER_MODE_DOCKER;
container_image = xxstrdup(optarg);
break;
case LONG_OPT_SKIP_FILE_CHECK:
skip_file_check = 1;
break;
case LONG_OPT_DOCKER_TAR:
image_tar = xxstrdup(optarg);
break;
case LONG_OPT_ALLOCATION_MODE:
if(!strcmp(optarg, "throughput")) {
allocation_mode = CATEGORY_ALLOCATION_MODE_MAX_THROUGHPUT;
} else if(!strcmp(optarg, "waste")) {
allocation_mode = CATEGORY_ALLOCATION_MODE_MIN_WASTE;
} else if(!strcmp(optarg, "fixed")) {
allocation_mode = CATEGORY_ALLOCATION_MODE_FIXED;
} else {
fatal("Allocation mode '%s' is not valid. Use one of: throughput waste fixed");
}
case LONG_OPT_JSON:
json_input = 1;
break;
default:
show_help_run(argv[0]);
return 1;
case 'X':
change_dir = optarg;
break;
}
}
cctools_version_debug(D_MAKEFLOW_RUN, argv[0]);
if(!did_explicit_auth)
auth_register_all();
if(chirp_tickets) {
auth_ticket_load(chirp_tickets);
free(chirp_tickets);
} else {
auth_ticket_load(NULL);
}
if((argc - optind) != 1) {
int rv = access("./Makeflow", R_OK);
if(rv < 0) {
fprintf(stderr, "makeflow: No makeflow specified and file \"./Makeflow\" could not be found.\n");
fprintf(stderr, "makeflow: Run \"%s -h\" for help with options.\n", argv[0]);
return 1;
}
dagfile = "./Makeflow";
} else {
dagfile = argv[optind];
}
if(batch_queue_type == BATCH_QUEUE_TYPE_WORK_QUEUE) {
if(strcmp(work_queue_master_mode, "catalog") == 0 && project == NULL) {
fprintf(stderr, "makeflow: Makeflow running in catalog mode. Please use '-N' option to specify the name of this project.\n");
fprintf(stderr, "makeflow: Run \"makeflow -h\" for help with options.\n");
return 1;
}
// Use Work Queue default port in standalone mode when port is not
// specified with -p option. In Work Queue catalog mode, Work Queue
// would choose an arbitrary port when port is not explicitly specified.
if(!port_set && strcmp(work_queue_master_mode, "standalone") == 0) {
port_set = 1;
port = WORK_QUEUE_DEFAULT_PORT;
}
if(port_set) {
char *value;
value = string_format("%d", port);
setenv("WORK_QUEUE_PORT", value, 1);
free(value);
}
}
if(!logfilename)
logfilename = string_format("%s.makeflowlog", dagfile);
printf("parsing %s...\n",dagfile);
struct dag *d;
if (json_input) {
struct jx *j = jx_parse_file(dagfile);
d = dag_from_jx(j);
jx_delete(j);
} else {
d = dag_from_file(dagfile);
}
if(!d) {
fatal("makeflow: couldn't load %s: %s\n", dagfile, strerror(errno));
}
d->allocation_mode = allocation_mode;
// Makeflows running LOCAL batch type have only one queue that behaves as if remote
// This forces -J vs -j to behave correctly
if(batch_queue_type == BATCH_QUEUE_TYPE_LOCAL) {
explicit_remote_jobs_max = explicit_local_jobs_max;
}
if(explicit_local_jobs_max) {
local_jobs_max = explicit_local_jobs_max;
} else {
local_jobs_max = load_average_get_cpus();
}
if(explicit_remote_jobs_max) {
remote_jobs_max = explicit_remote_jobs_max;
} else {
if(batch_queue_type == BATCH_QUEUE_TYPE_LOCAL) {
remote_jobs_max = load_average_get_cpus();
} else if(batch_queue_type == BATCH_QUEUE_TYPE_WORK_QUEUE) {
remote_jobs_max = 10 * MAX_REMOTE_JOBS_DEFAULT;
} else {
remote_jobs_max = MAX_REMOTE_JOBS_DEFAULT;
}
}
s = getenv("MAKEFLOW_MAX_REMOTE_JOBS");
if(s) {
remote_jobs_max = MIN(remote_jobs_max, atoi(s));
}
s = getenv("MAKEFLOW_MAX_LOCAL_JOBS");
if(s) {
int n = atoi(s);
local_jobs_max = MIN(local_jobs_max, n);
if(batch_queue_type == BATCH_QUEUE_TYPE_LOCAL) {
remote_jobs_max = MIN(local_jobs_max, n);
}
}
remote_queue = batch_queue_create(batch_queue_type);
if(!remote_queue) {
fprintf(stderr, "makeflow: couldn't create batch queue.\n");
if(port != 0)
fprintf(stderr, "makeflow: perhaps port %d is already in use?\n", port);
exit(EXIT_FAILURE);
}
if(!batchlogfilename) {
if(batch_queue_supports_feature(remote_queue, "batch_log_name")){
batchlogfilename = string_format(batch_queue_supports_feature(remote_queue, "batch_log_name"), dagfile);
} else {
batchlogfilename = string_format("%s.batchlog", dagfile);
}
}
if(batch_queue_type == BATCH_QUEUE_TYPE_DRYRUN) {
FILE *file = fopen(batchlogfilename,"w");
if(!file) fatal("unable to open log file %s: %s\n", batchlogfilename, strerror(errno));
fprintf(file, "#!/bin/sh\n");
fprintf(file, "set -x\n");
fprintf(file, "set -e\n");
fprintf(file, "\n# %s version %s (released %s)\n\n", argv[0], CCTOOLS_VERSION, CCTOOLS_RELEASE_DATE);
fclose(file);
}
batch_queue_set_logfile(remote_queue, batchlogfilename);
batch_queue_set_option(remote_queue, "batch-options", batch_submit_options);
batch_queue_set_option(remote_queue, "skip-afs-check", skip_afs_check ? "yes" : "no");
batch_queue_set_option(remote_queue, "password", work_queue_password);
batch_queue_set_option(remote_queue, "master-mode", work_queue_master_mode);
batch_queue_set_option(remote_queue, "name", project);
batch_queue_set_option(remote_queue, "priority", priority);
batch_queue_set_option(remote_queue, "keepalive-interval", work_queue_keepalive_interval);
batch_queue_set_option(remote_queue, "keepalive-timeout", work_queue_keepalive_timeout);
batch_queue_set_option(remote_queue, "caching", cache_mode ? "yes" : "no");
batch_queue_set_option(remote_queue, "wait-queue-size", wq_wait_queue_size);
batch_queue_set_option(remote_queue, "amazon-credentials", amazon_credentials);
batch_queue_set_option(remote_queue, "amazon-ami", amazon_ami);
batch_queue_set_option(remote_queue, "working-dir", working_dir);
batch_queue_set_option(remote_queue, "master-preferred-connection", work_queue_preferred_connection);
char *fa_multiplier = string_format("%f", wq_option_fast_abort_multiplier);
batch_queue_set_option(remote_queue, "fast-abort", fa_multiplier);
free(fa_multiplier);
/* Do not create a local queue for systems where local and remote are the same. */
if(!batch_queue_supports_feature(remote_queue, "local_job_queue")) {
local_queue = 0;
} else {
local_queue = batch_queue_create(BATCH_QUEUE_TYPE_LOCAL);
if(!local_queue) {
fatal("couldn't create local job queue.");
}
}
/* Remote storage modes do not (yet) support measuring storage for garbage collection. */
if(makeflow_gc_method == MAKEFLOW_GC_SIZE && !batch_queue_supports_feature(remote_queue, "gc_size")) {
makeflow_gc_method = MAKEFLOW_GC_ALL;
}
if(monitor) {
if(!log_dir)
fatal("Monitor mode was enabled, but a log output directory was not specified (use --monitor=<dir>)");
if(!log_format)
log_format = xxstrdup(DEFAULT_MONITOR_LOG_FORMAT);
if(monitor->interval < 1)
fatal("Monitoring interval should be positive.");
makeflow_prepare_for_monitoring(monitor, remote_queue, log_dir, log_format);
free(log_dir);
free(log_format);
}
makeflow_parse_input_outputs(d);
makeflow_prepare_nested_jobs(d);
if (change_dir)
chdir(change_dir);
printf("checking %s for consistency...\n",dagfile);
if(!makeflow_check(d)) {
exit(EXIT_FAILURE);
}
if(!makeflow_check_batch_consistency(d) && clean_mode == MAKEFLOW_CLEAN_NONE) {
exit(EXIT_FAILURE);
}
printf("%s has %d rules.\n",dagfile,d->nodeid_counter);
setlinebuf(stdout);
setlinebuf(stderr);
makeflow_log_recover(d, logfilename, log_verbose_mode, remote_queue, clean_mode, skip_file_check );
struct dag_file *f = dag_file_lookup_or_create(d, batchlogfilename);
makeflow_log_file_state_change(d, f, DAG_FILE_STATE_EXPECT);
if(clean_mode != MAKEFLOW_CLEAN_NONE) {
printf("cleaning filesystem...\n");
makeflow_clean(d, remote_queue, clean_mode);
if(clean_mode == MAKEFLOW_CLEAN_ALL) {
unlink(logfilename);
}
exit(0);
}
printf("starting workflow....\n");
port = batch_queue_port(remote_queue);
if(work_queue_port_file)
opts_write_port_file(work_queue_port_file, port);
if(port > 0)
printf("listening for workers on port %d.\n", port);
signal(SIGINT, handle_abort);
signal(SIGQUIT, handle_abort);
signal(SIGTERM, handle_abort);
makeflow_log_started_event(d);
runtime = timestamp_get();
if (container_mode == CONTAINER_MODE_DOCKER) {
makeflow_wrapper_docker_init(wrapper, container_image, image_tar);
}
makeflow_run(d);
time_completed = timestamp_get();
runtime = time_completed - runtime;
if(local_queue)
batch_queue_delete(local_queue);
batch_queue_delete(remote_queue);
if(write_summary_to || email_summary_to)
makeflow_summary_create(d, write_summary_to, email_summary_to, runtime, time_completed, argc, argv, dagfile, remote_queue, makeflow_abort_flag, makeflow_failed_flag );
/* XXX better to write created files to log, then delete those listed in log. */
if (container_mode == CONTAINER_MODE_DOCKER) {
char *cmd = string_format("rm %s", CONTAINER_SH);
system(cmd);
free(cmd);
}
if(makeflow_abort_flag) {
makeflow_log_aborted_event(d);
fprintf(stderr, "workflow was aborted.\n");
exit(EXIT_FAILURE);
} else if(makeflow_failed_flag) {
makeflow_log_failed_event(d);
fprintf(stderr, "workflow failed.\n");
exit(EXIT_FAILURE);
} else {
makeflow_log_completed_event(d);
printf("nothing left to do.\n");
exit(EXIT_SUCCESS);
}
return 0;
}
/* vim: set noexpandtab tabstop=4: */
| 1 | 12,829 | I can see why you did it this way, but let's not get into the habit of passing information back via an environment variable. Add an element to `batch_job_info` instead, which is where we send back detailed info about jobs. | cooperative-computing-lab-cctools | c |
@@ -438,7 +438,11 @@ function diffElementNodes(
if (
'value' in newProps &&
(i = newProps.value) !== undefined &&
- i !== dom.value
+ // #2756 For the <progress>-element the initial value is 0,
+ // despite the attribute not being present. When the attribute
+ // is missing the progress bar is treated as indeterminate.
+ // To fix that we'll always update it when it is 0 for progress elements
+ (i !== dom.value || (newVNode.type === 'progress' && !i))
) {
setProperty(dom, 'value', i, oldProps.value, false);
} | 1 | import { EMPTY_OBJ, EMPTY_ARR } from '../constants';
import { Component } from '../component';
import { Fragment } from '../create-element';
import { diffChildren, placeChild } from './children';
import { diffProps, setProperty } from './props';
import { assign, removeNode } from '../util';
import options from '../options';
function reorderChildren(newVNode, oldDom, parentDom) {
for (let tmp = 0; tmp < newVNode._children.length; tmp++) {
const vnode = newVNode._children[tmp];
if (vnode) {
vnode._parent = newVNode;
if (vnode._dom) {
if (typeof vnode.type == 'function' && vnode._children.length > 1) {
reorderChildren(vnode, oldDom, parentDom);
}
oldDom = placeChild(
parentDom,
vnode,
vnode,
newVNode._children,
null,
vnode._dom,
oldDom
);
if (typeof newVNode.type == 'function') {
newVNode._nextDom = oldDom;
}
}
}
}
}
/**
* Diff two virtual nodes and apply proper changes to the DOM
* @param {import('../internal').PreactElement} parentDom The parent of the DOM element
* @param {import('../internal').VNode} newVNode The new virtual node
* @param {import('../internal').VNode} oldVNode The old virtual node
* @param {object} globalContext The current context object. Modified by getChildContext
* @param {boolean} isSvg Whether or not this element is an SVG node
* @param {Array<import('../internal').PreactElement>} excessDomChildren
* @param {Array<import('../internal').Component>} commitQueue List of components
* which have callbacks to invoke in commitRoot
* @param {Element | Text} oldDom The current attached DOM
* element any new dom elements should be placed around. Likely `null` on first
* render (except when hydrating). Can be a sibling DOM element when diffing
* Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.
* @param {boolean} [isHydrating] Whether or not we are in hydration
*/
export function diff(
parentDom,
newVNode,
oldVNode,
globalContext,
isSvg,
excessDomChildren,
commitQueue,
oldDom,
isHydrating
) {
let tmp,
newType = newVNode.type;
// When passing through createElement it assigns the object
// constructor as undefined. This to prevent JSON-injection.
if (newVNode.constructor !== undefined) return null;
// If the previous diff bailed out, resume creating/hydrating.
if (oldVNode._hydrating != null) {
isHydrating = oldVNode._hydrating;
oldDom = newVNode._dom = oldVNode._dom;
// if we resume, we want the tree to be "unlocked"
newVNode._hydrating = null;
excessDomChildren = [oldDom];
}
if ((tmp = options._diff)) tmp(newVNode);
try {
outer: if (typeof newType == 'function') {
let c, isNew, oldProps, oldState, snapshot, clearProcessingException;
let newProps = newVNode.props;
// Necessary for createContext api. Setting this property will pass
// the context value as `this.context` just for this component.
tmp = newType.contextType;
let provider = tmp && globalContext[tmp._id];
let componentContext = tmp
? provider
? provider.props.value
: tmp._defaultValue
: globalContext;
// Get component and set it to `c`
if (oldVNode._component) {
c = newVNode._component = oldVNode._component;
clearProcessingException = c._processingException = c._pendingError;
} else {
// Instantiate the new component
if ('prototype' in newType && newType.prototype.render) {
newVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap
} else {
newVNode._component = c = new Component(newProps, componentContext);
c.constructor = newType;
c.render = doRender;
}
if (provider) provider.sub(c);
c.props = newProps;
if (!c.state) c.state = {};
c.context = componentContext;
c._globalContext = globalContext;
isNew = c._dirty = true;
c._renderCallbacks = [];
}
// Invoke getDerivedStateFromProps
if (c._nextState == null) {
c._nextState = c.state;
}
if (newType.getDerivedStateFromProps != null) {
if (c._nextState == c.state) {
c._nextState = assign({}, c._nextState);
}
assign(
c._nextState,
newType.getDerivedStateFromProps(newProps, c._nextState)
);
}
oldProps = c.props;
oldState = c.state;
// Invoke pre-render lifecycle methods
if (isNew) {
if (
newType.getDerivedStateFromProps == null &&
c.componentWillMount != null
) {
c.componentWillMount();
}
if (c.componentDidMount != null) {
c._renderCallbacks.push(c.componentDidMount);
}
} else {
if (
newType.getDerivedStateFromProps == null &&
newProps !== oldProps &&
c.componentWillReceiveProps != null
) {
c.componentWillReceiveProps(newProps, componentContext);
}
if (
(!c._force &&
c.shouldComponentUpdate != null &&
c.shouldComponentUpdate(
newProps,
c._nextState,
componentContext
) === false) ||
newVNode._original === oldVNode._original
) {
c.props = newProps;
c.state = c._nextState;
// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8
if (newVNode._original !== oldVNode._original) c._dirty = false;
c._vnode = newVNode;
newVNode._dom = oldVNode._dom;
newVNode._children = oldVNode._children;
if (c._renderCallbacks.length) {
commitQueue.push(c);
}
reorderChildren(newVNode, oldDom, parentDom);
break outer;
}
if (c.componentWillUpdate != null) {
c.componentWillUpdate(newProps, c._nextState, componentContext);
}
if (c.componentDidUpdate != null) {
c._renderCallbacks.push(() => {
c.componentDidUpdate(oldProps, oldState, snapshot);
});
}
}
c.context = componentContext;
c.props = newProps;
c.state = c._nextState;
if ((tmp = options._render)) tmp(newVNode);
c._dirty = false;
c._vnode = newVNode;
c._parentDom = parentDom;
tmp = c.render(c.props, c.state, c.context);
// Handle setState called in render, see #2553
c.state = c._nextState;
if (c.getChildContext != null) {
globalContext = assign(assign({}, globalContext), c.getChildContext());
}
if (!isNew && c.getSnapshotBeforeUpdate != null) {
snapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);
}
let isTopLevelFragment =
tmp != null && tmp.type == Fragment && tmp.key == null;
let renderResult = isTopLevelFragment ? tmp.props.children : tmp;
diffChildren(
parentDom,
Array.isArray(renderResult) ? renderResult : [renderResult],
newVNode,
oldVNode,
globalContext,
isSvg,
excessDomChildren,
commitQueue,
oldDom,
isHydrating
);
c.base = newVNode._dom;
// We successfully rendered this VNode, unset any stored hydration/bailout state:
newVNode._hydrating = null;
if (c._renderCallbacks.length) {
commitQueue.push(c);
}
if (clearProcessingException) {
c._pendingError = c._processingException = null;
}
c._force = false;
} else if (
excessDomChildren == null &&
newVNode._original === oldVNode._original
) {
newVNode._children = oldVNode._children;
newVNode._dom = oldVNode._dom;
} else {
newVNode._dom = diffElementNodes(
oldVNode._dom,
newVNode,
oldVNode,
globalContext,
isSvg,
excessDomChildren,
commitQueue,
isHydrating
);
}
if ((tmp = options.diffed)) tmp(newVNode);
} catch (e) {
newVNode._original = null;
// if hydrating or creating initial tree, bailout preserves DOM:
if (isHydrating || excessDomChildren != null) {
newVNode._dom = oldDom;
newVNode._hydrating = !!isHydrating;
excessDomChildren[excessDomChildren.indexOf(oldDom)] = null;
// ^ could possibly be simplified to:
// excessDomChildren.length = 0;
}
options._catchError(e, newVNode, oldVNode);
}
return newVNode._dom;
}
/**
* @param {Array<import('../internal').Component>} commitQueue List of components
* which have callbacks to invoke in commitRoot
* @param {import('../internal').VNode} root
*/
export function commitRoot(commitQueue, root) {
if (options._commit) options._commit(root, commitQueue);
commitQueue.some(c => {
try {
commitQueue = c._renderCallbacks;
c._renderCallbacks = [];
commitQueue.some(cb => {
cb.call(c);
});
} catch (e) {
options._catchError(e, c._vnode);
}
});
}
/**
* 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} globalContext The current context object
* @param {boolean} isSvg Whether or not this DOM node is an SVG node
* @param {*} excessDomChildren
* @param {Array<import('../internal').Component>} commitQueue List of components
* which have callbacks to invoke in commitRoot
* @param {boolean} isHydrating Whether or not we are in hydration
* @returns {import('../internal').PreactElement}
*/
function diffElementNodes(
dom,
newVNode,
oldVNode,
globalContext,
isSvg,
excessDomChildren,
commitQueue,
isHydrating
) {
let i;
let oldProps = oldVNode.props;
let newProps = newVNode.props;
// Tracks entering and exiting SVG namespace when descending through the tree.
isSvg = newVNode.type === 'svg' || isSvg;
if (excessDomChildren != null) {
for (i = 0; i < excessDomChildren.length; i++) {
const child = excessDomChildren[i];
// if newVNode matches an element in excessDomChildren or the `dom`
// argument matches an element in excessDomChildren, remove it from
// excessDomChildren so it isn't later removed in diffChildren
if (
child != null &&
((newVNode.type === null
? child.nodeType === 3
: child.localName === newVNode.type) ||
dom == child)
) {
dom = child;
excessDomChildren[i] = null;
break;
}
}
}
if (dom == null) {
if (newVNode.type === null) {
return document.createTextNode(newProps);
}
dom = isSvg
? document.createElementNS('http://www.w3.org/2000/svg', newVNode.type)
: document.createElement(
newVNode.type,
newProps.is && { is: newProps.is }
);
// we created a new parent, so none of the previously attached children can be reused:
excessDomChildren = null;
// we are creating a new node, so we can assume this is a new subtree (in case we are hydrating), this deopts the hydrate
isHydrating = false;
}
if (newVNode.type === null) {
// During hydration, we still have to split merged text from SSR'd HTML.
if (oldProps !== newProps && (!isHydrating || dom.data !== newProps)) {
dom.data = newProps;
}
} else {
if (excessDomChildren != null) {
excessDomChildren = EMPTY_ARR.slice.call(dom.childNodes);
}
oldProps = oldVNode.props || EMPTY_OBJ;
let oldHtml = oldProps.dangerouslySetInnerHTML;
let newHtml = newProps.dangerouslySetInnerHTML;
// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)
// @TODO we should warn in debug mode when props don't match here.
if (!isHydrating) {
// But, if we are in a situation where we are using existing DOM (e.g. replaceNode)
// we should read the existing DOM attributes to diff them
if (excessDomChildren != null) {
oldProps = {};
for (let i = 0; i < dom.attributes.length; i++) {
oldProps[dom.attributes[i].name] = dom.attributes[i].value;
}
}
if (newHtml || oldHtml) {
// Avoid re-applying the same '__html' if it did not changed between re-render
if (
!newHtml ||
((!oldHtml || newHtml.__html != oldHtml.__html) &&
newHtml.__html !== dom.innerHTML)
) {
dom.innerHTML = (newHtml && newHtml.__html) || '';
}
}
}
diffProps(dom, newProps, oldProps, isSvg, isHydrating);
// If the new vnode didn't have dangerouslySetInnerHTML, diff its children
if (newHtml) {
newVNode._children = [];
} else {
i = newVNode.props.children;
diffChildren(
dom,
Array.isArray(i) ? i : [i],
newVNode,
oldVNode,
globalContext,
newVNode.type === 'foreignObject' ? false : isSvg,
excessDomChildren,
commitQueue,
EMPTY_OBJ,
isHydrating
);
}
// (as above, don't diff props during hydration)
if (!isHydrating) {
if (
'value' in newProps &&
(i = newProps.value) !== undefined &&
i !== dom.value
) {
setProperty(dom, 'value', i, oldProps.value, false);
}
if (
'checked' in newProps &&
(i = newProps.checked) !== undefined &&
i !== dom.checked
) {
setProperty(dom, 'checked', i, oldProps.checked, false);
}
}
}
return dom;
}
/**
* Invoke or update a ref, depending on whether it is a function or object ref.
* @param {object|function} ref
* @param {any} value
* @param {import('../internal').VNode} vnode
*/
export function applyRef(ref, value, vnode) {
try {
if (typeof ref == 'function') ref(value);
else ref.current = value;
} catch (e) {
options._catchError(e, vnode);
}
}
/**
* Unmount a virtual node from the tree and apply DOM changes
* @param {import('../internal').VNode} vnode The virtual node to unmount
* @param {import('../internal').VNode} parentVNode The parent of the VNode that
* initiated the unmount
* @param {boolean} [skipRemove] Flag that indicates that a parent node of the
* current element is already detached from the DOM.
*/
export function unmount(vnode, parentVNode, skipRemove) {
let r;
if (options.unmount) options.unmount(vnode);
if ((r = vnode.ref)) {
if (!r.current || r.current === vnode._dom) applyRef(r, null, parentVNode);
}
let dom;
if (!skipRemove && typeof vnode.type != 'function') {
skipRemove = (dom = vnode._dom) != null;
}
// Must be set to `undefined` to properly clean up `_nextDom`
// for which `null` is a valid value. See comment in `create-element.js`
vnode._dom = vnode._nextDom = undefined;
if ((r = vnode._component) != null) {
if (r.componentWillUnmount) {
try {
r.componentWillUnmount();
} catch (e) {
options._catchError(e, parentVNode);
}
}
r.base = r._parentDom = null;
}
if ((r = vnode._children)) {
for (let i = 0; i < r.length; i++) {
if (r[i]) unmount(r[i], parentVNode, skipRemove);
}
}
if (dom != null) removeNode(dom);
}
/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
return this.constructor(props, context);
}
| 1 | 16,163 | Turns out my previous fix of doing `!dom.hasAttribute('value')` is not a good one as it leads to all input values always being updated. The new fix only updates it, despite `dom.value === props.value` when the value is `0` for progress elements. | preactjs-preact | js |
@@ -3,6 +3,7 @@
#include <cmath>
#include <cstdio>
#include <ctime>
+#include <vector>
#include "caffe/common.hpp"
#include "caffe/util/rng.hpp" | 1 | #include <boost/thread.hpp>
#include <glog/logging.h>
#include <cmath>
#include <cstdio>
#include <ctime>
#include "caffe/common.hpp"
#include "caffe/util/rng.hpp"
namespace caffe {
// Make sure each thread can have different values.
static boost::thread_specific_ptr<Caffe> thread_instance_;
Caffe& Caffe::Get() {
if (!thread_instance_.get()) {
thread_instance_.reset(new Caffe());
}
return *(thread_instance_.get());
}
// random seeding
int64_t cluster_seedgen(void) {
int64_t s, seed, pid;
FILE* f = fopen("/dev/urandom", "rb");
if (f && fread(&seed, 1, sizeof(seed), f) == sizeof(seed)) {
fclose(f);
return seed;
}
LOG(INFO) << "System entropy source not available, "
"using fallback algorithm to generate seed instead.";
if (f)
fclose(f);
pid = getpid();
s = time(NULL);
seed = std::abs(((s * 181) * ((pid - 83) * 359)) % 104729);
return seed;
}
void GlobalInit(int* pargc, char*** pargv) {
// Google flags.
::gflags::ParseCommandLineFlags(pargc, pargv, true);
// Google logging.
::google::InitGoogleLogging(*(pargv)[0]);
// Provide a backtrace on segfault.
::google::InstallFailureSignalHandler();
}
#ifdef CPU_ONLY // CPU-only Caffe.
Caffe::Caffe()
: random_generator_(), mode_(Caffe::CPU),
solver_count_(1), root_solver_(true) { }
Caffe::~Caffe() { }
void Caffe::set_random_seed(const unsigned int seed) {
// RNG seed
Get().random_generator_.reset(new RNG(seed));
}
void Caffe::SetDevice(const int device_id) {
NO_GPU;
}
void Caffe::DeviceQuery() {
NO_GPU;
}
bool Caffe::CheckDevice(const int device_id) {
NO_GPU;
return false;
}
int Caffe::FindDevice(const int start_id) {
NO_GPU;
return -1;
}
class Caffe::RNG::Generator {
public:
Generator() : rng_(new caffe::rng_t(cluster_seedgen())) {}
explicit Generator(unsigned int seed) : rng_(new caffe::rng_t(seed)) {}
caffe::rng_t* rng() { return rng_.get(); }
private:
shared_ptr<caffe::rng_t> rng_;
};
Caffe::RNG::RNG() : generator_(new Generator()) { }
Caffe::RNG::RNG(unsigned int seed) : generator_(new Generator(seed)) { }
Caffe::RNG& Caffe::RNG::operator=(const RNG& other) {
generator_ = other.generator_;
return *this;
}
void* Caffe::RNG::generator() {
return static_cast<void*>(generator_->rng());
}
#else // Normal GPU + CPU Caffe.
Caffe::Caffe()
: cublas_handle_(NULL), curand_generator_(NULL), random_generator_(),
mode_(Caffe::CPU), solver_count_(1), root_solver_(true) {
// Try to create a cublas handler, and report an error if failed (but we will
// keep the program running as one might just want to run CPU code).
if (cublasCreate(&cublas_handle_) != CUBLAS_STATUS_SUCCESS) {
LOG(ERROR) << "Cannot create Cublas handle. Cublas won't be available.";
}
// Try to create a curand handler.
if (curandCreateGenerator(&curand_generator_, CURAND_RNG_PSEUDO_DEFAULT)
!= CURAND_STATUS_SUCCESS ||
curandSetPseudoRandomGeneratorSeed(curand_generator_, cluster_seedgen())
!= CURAND_STATUS_SUCCESS) {
LOG(ERROR) << "Cannot create Curand generator. Curand won't be available.";
}
}
Caffe::~Caffe() {
if (cublas_handle_) CUBLAS_CHECK(cublasDestroy(cublas_handle_));
if (curand_generator_) {
CURAND_CHECK(curandDestroyGenerator(curand_generator_));
}
}
void Caffe::set_random_seed(const unsigned int seed) {
// Curand seed
static bool g_curand_availability_logged = false;
if (Get().curand_generator_) {
CURAND_CHECK(curandSetPseudoRandomGeneratorSeed(curand_generator(),
seed));
CURAND_CHECK(curandSetGeneratorOffset(curand_generator(), 0));
} else {
if (!g_curand_availability_logged) {
LOG(ERROR) <<
"Curand not available. Skipping setting the curand seed.";
g_curand_availability_logged = true;
}
}
// RNG seed
Get().random_generator_.reset(new RNG(seed));
}
void Caffe::SetDevice(const int device_id) {
int current_device;
CUDA_CHECK(cudaGetDevice(¤t_device));
if (current_device == device_id) {
return;
}
// The call to cudaSetDevice must come before any calls to Get, which
// may perform initialization using the GPU.
CUDA_CHECK(cudaSetDevice(device_id));
if (Get().cublas_handle_) CUBLAS_CHECK(cublasDestroy(Get().cublas_handle_));
if (Get().curand_generator_) {
CURAND_CHECK(curandDestroyGenerator(Get().curand_generator_));
}
CUBLAS_CHECK(cublasCreate(&Get().cublas_handle_));
CURAND_CHECK(curandCreateGenerator(&Get().curand_generator_,
CURAND_RNG_PSEUDO_DEFAULT));
CURAND_CHECK(curandSetPseudoRandomGeneratorSeed(Get().curand_generator_,
cluster_seedgen()));
}
void Caffe::DeviceQuery() {
cudaDeviceProp prop;
int device;
if (cudaSuccess != cudaGetDevice(&device)) {
printf("No cuda device present.\n");
return;
}
CUDA_CHECK(cudaGetDeviceProperties(&prop, device));
LOG(INFO) << "Device id: " << device;
LOG(INFO) << "Major revision number: " << prop.major;
LOG(INFO) << "Minor revision number: " << prop.minor;
LOG(INFO) << "Name: " << prop.name;
LOG(INFO) << "Total global memory: " << prop.totalGlobalMem;
LOG(INFO) << "Total shared memory per block: " << prop.sharedMemPerBlock;
LOG(INFO) << "Total registers per block: " << prop.regsPerBlock;
LOG(INFO) << "Warp size: " << prop.warpSize;
LOG(INFO) << "Maximum memory pitch: " << prop.memPitch;
LOG(INFO) << "Maximum threads per block: " << prop.maxThreadsPerBlock;
LOG(INFO) << "Maximum dimension of block: "
<< prop.maxThreadsDim[0] << ", " << prop.maxThreadsDim[1] << ", "
<< prop.maxThreadsDim[2];
LOG(INFO) << "Maximum dimension of grid: "
<< prop.maxGridSize[0] << ", " << prop.maxGridSize[1] << ", "
<< prop.maxGridSize[2];
LOG(INFO) << "Clock rate: " << prop.clockRate;
LOG(INFO) << "Total constant memory: " << prop.totalConstMem;
LOG(INFO) << "Texture alignment: " << prop.textureAlignment;
LOG(INFO) << "Concurrent copy and execution: "
<< (prop.deviceOverlap ? "Yes" : "No");
LOG(INFO) << "Number of multiprocessors: " << prop.multiProcessorCount;
LOG(INFO) << "Kernel execution timeout: "
<< (prop.kernelExecTimeoutEnabled ? "Yes" : "No");
return;
}
bool Caffe::CheckDevice(const int device_id) {
// This function checks the availability of GPU #device_id.
// It attempts to create a context on the device by calling cudaFree(0).
// cudaSetDevice() alone is not sufficient to check the availability.
// It lazily records device_id, however, does not initialize a
// context. So it does not know if the host thread has the permission to use
// the device or not.
//
// In a shared environment where the devices are set to EXCLUSIVE_PROCESS
// or EXCLUSIVE_THREAD mode, cudaSetDevice() returns cudaSuccess
// even if the device is exclusively occupied by another process or thread.
// Cuda operations that initialize the context are needed to check
// the permission. cudaFree(0) is one of those with no side effect,
// except the context initialization.
bool r = ((cudaSuccess == cudaSetDevice(device_id)) &&
(cudaSuccess == cudaFree(0)));
// reset any error that may have occurred.
cudaGetLastError();
return r;
}
int Caffe::FindDevice(const int start_id) {
// This function finds the first available device by checking devices with
// ordinal from start_id to the highest available value. In the
// EXCLUSIVE_PROCESS or EXCLUSIVE_THREAD mode, if it succeeds, it also
// claims the device due to the initialization of the context.
int count = 0;
CUDA_CHECK(cudaGetDeviceCount(&count));
for (int i = start_id; i < count; i++) {
if (CheckDevice(i)) return i;
}
return -1;
}
class Caffe::RNG::Generator {
public:
Generator() : rng_(new caffe::rng_t(cluster_seedgen())) {}
explicit Generator(unsigned int seed) : rng_(new caffe::rng_t(seed)) {}
caffe::rng_t* rng() { return rng_.get(); }
private:
shared_ptr<caffe::rng_t> rng_;
};
Caffe::RNG::RNG() : generator_(new Generator()) { }
Caffe::RNG::RNG(unsigned int seed) : generator_(new Generator(seed)) { }
Caffe::RNG& Caffe::RNG::operator=(const RNG& other) {
generator_.reset(other.generator_.get());
return *this;
}
void* Caffe::RNG::generator() {
return static_cast<void*>(generator_->rng());
}
const char* cublasGetErrorString(cublasStatus_t error) {
switch (error) {
case CUBLAS_STATUS_SUCCESS:
return "CUBLAS_STATUS_SUCCESS";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "CUBLAS_STATUS_NOT_INITIALIZED";
case CUBLAS_STATUS_ALLOC_FAILED:
return "CUBLAS_STATUS_ALLOC_FAILED";
case CUBLAS_STATUS_INVALID_VALUE:
return "CUBLAS_STATUS_INVALID_VALUE";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "CUBLAS_STATUS_ARCH_MISMATCH";
case CUBLAS_STATUS_MAPPING_ERROR:
return "CUBLAS_STATUS_MAPPING_ERROR";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "CUBLAS_STATUS_EXECUTION_FAILED";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "CUBLAS_STATUS_INTERNAL_ERROR";
#if CUDA_VERSION >= 6000
case CUBLAS_STATUS_NOT_SUPPORTED:
return "CUBLAS_STATUS_NOT_SUPPORTED";
#endif
#if CUDA_VERSION >= 6050
case CUBLAS_STATUS_LICENSE_ERROR:
return "CUBLAS_STATUS_LICENSE_ERROR";
#endif
}
return "Unknown cublas status";
}
const char* curandGetErrorString(curandStatus_t error) {
switch (error) {
case CURAND_STATUS_SUCCESS:
return "CURAND_STATUS_SUCCESS";
case CURAND_STATUS_VERSION_MISMATCH:
return "CURAND_STATUS_VERSION_MISMATCH";
case CURAND_STATUS_NOT_INITIALIZED:
return "CURAND_STATUS_NOT_INITIALIZED";
case CURAND_STATUS_ALLOCATION_FAILED:
return "CURAND_STATUS_ALLOCATION_FAILED";
case CURAND_STATUS_TYPE_ERROR:
return "CURAND_STATUS_TYPE_ERROR";
case CURAND_STATUS_OUT_OF_RANGE:
return "CURAND_STATUS_OUT_OF_RANGE";
case CURAND_STATUS_LENGTH_NOT_MULTIPLE:
return "CURAND_STATUS_LENGTH_NOT_MULTIPLE";
case CURAND_STATUS_DOUBLE_PRECISION_REQUIRED:
return "CURAND_STATUS_DOUBLE_PRECISION_REQUIRED";
case CURAND_STATUS_LAUNCH_FAILURE:
return "CURAND_STATUS_LAUNCH_FAILURE";
case CURAND_STATUS_PREEXISTING_FAILURE:
return "CURAND_STATUS_PREEXISTING_FAILURE";
case CURAND_STATUS_INITIALIZATION_FAILED:
return "CURAND_STATUS_INITIALIZATION_FAILED";
case CURAND_STATUS_ARCH_MISMATCH:
return "CURAND_STATUS_ARCH_MISMATCH";
case CURAND_STATUS_INTERNAL_ERROR:
return "CURAND_STATUS_INTERNAL_ERROR";
}
return "Unknown curand status";
}
#endif // CPU_ONLY
} // namespace caffe
| 1 | 36,629 | Why is this being added here? Is this relevant to these changes? | BVLC-caffe | cpp |
@@ -74,7 +74,7 @@ public class SeleniumServer extends JettyServer {
getClass().getClassLoader())
.asSubclass(Routable.class);
Constructor<? extends Routable> constructor = rcHandler.getConstructor(ActiveSessions.class);
- LOG.info("Bound legacy RC support");
+ LOG.finest("Bound legacy RC support");
return constructor.newInstance(sessions);
} catch (ReflectiveOperationException e) {
// Do nothing. | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.remote.server;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.openqa.selenium.remote.http.Contents.utf8String;
import static org.openqa.selenium.remote.http.Route.combine;
import com.beust.jcommander.JCommander;
import org.openqa.selenium.grid.config.AnnotatedConfig;
import org.openqa.selenium.jetty.server.JettyServer;
import org.openqa.selenium.grid.server.BaseServerFlags;
import org.openqa.selenium.grid.server.BaseServerOptions;
import org.openqa.selenium.grid.server.HelpFlags;
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.server.jmx.JMXHelper;
import org.openqa.selenium.remote.server.jmx.ManagedService;
import java.io.UncheckedIOException;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.logging.Logger;
import javax.management.ObjectName;
import javax.servlet.Servlet;
/**
* Provides a server that can launch and manage selenium sessions.
*/
@ManagedService(objectName = "org.seleniumhq.server:type=SeleniumServer")
public class SeleniumServer extends JettyServer {
private final static Logger LOG = Logger.getLogger(SeleniumServer.class.getName());
private final BaseServerOptions configuration;
private Map<String, Class<? extends Servlet>> extraServlets;
private ObjectName objectName;
private ActiveSessions allSessions;
public SeleniumServer(BaseServerOptions configuration) {
super(configuration);
this.configuration = configuration;
objectName = new JMXHelper().register(this).getObjectName();
}
private Routable getRcHandler(ActiveSessions sessions) {
try {
Class<? extends Routable> rcHandler = Class.forName(
"com.thoughtworks.selenium.webdriven.WebDriverBackedSeleniumHandler",
false,
getClass().getClassLoader())
.asSubclass(Routable.class);
Constructor<? extends Routable> constructor = rcHandler.getConstructor(ActiveSessions.class);
LOG.info("Bound legacy RC support");
return constructor.newInstance(sessions);
} catch (ReflectiveOperationException e) {
// Do nothing.
}
return new Routable() {
@Override
public boolean matches(HttpRequest req) {
return false;
}
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
return null;
}
};
}
@Override
public JettyServer start() {
long inactiveSessionTimeoutSeconds = Long.MAX_VALUE / 1000;
NewSessionPipeline pipeline = DefaultPipeline.createDefaultPipeline().create();
allSessions = new ActiveSessions(inactiveSessionTimeoutSeconds, SECONDS);
Servlet driverServlet = new WebDriverServlet(allSessions, pipeline);
addServlet(driverServlet, "/wd/hub/*");
addServlet(driverServlet, "/webdriver/*");
Route route = Route.matching(req -> true)
.to(() -> req -> new HttpResponse()
.setStatus(HTTP_NOT_FOUND)
.setContent(utf8String("Not handler found for " + req)));
Routable rcHandler = getRcHandler(allSessions);
if (rcHandler != null) {
route = combine(route, rcHandler);
}
setHandler(route);
super.start();
LOG.info(String.format("Selenium Server is up and running on port %s", configuration.getPort()));
return this;
}
/**
* Stops the Jetty server
*/
@Override
public void stop() {
try {
super.stop();
} finally {
new JMXHelper().unregister(objectName);
stopAllBrowsers();
}
}
private void stopAllBrowsers() {
if (allSessions == null) {
return;
}
allSessions.getAllSessions().parallelStream()
.forEach(session -> {
try {
session.stop();
} catch (Exception ignored) {
// Ignored
}
});
}
public static void main(String[] args) {
HelpFlags helpFlags = new HelpFlags();
BaseServerFlags flags = new BaseServerFlags(4444);
JCommander commands = JCommander.newBuilder().addObject(flags).addObject(helpFlags).build();
commands.parse(args);
if (helpFlags.displayHelp(commands, System.err)) {
return;
}
SeleniumServer server = new SeleniumServer(new BaseServerOptions(new AnnotatedConfig(flags)));
server.start();
}
}
| 1 | 17,125 | This informational message is important to users. Please leave. | SeleniumHQ-selenium | py |
@@ -0,0 +1,4 @@
+All unapproved FY15 credit card funding requests are being cancelled.
+If the need still exists, please submit a new FY16 funding request.
+
+<%= url_for(controller: 'proposals', action: 'show', id: @proposal.id) %> | 1 | 1 | 15,173 | why isn't rubocop failing for single quotes? | 18F-C2 | rb |
|
@@ -36,14 +36,10 @@ class StatusAttributeDataSetQueryBuilder extends AbstractAttributeDataSetBuilder
{
$query->addSelect(sprintf(
'(
- SELECT value FROM product_value pv
- JOIN value_translation vt ON vt.value_id = pv.value_id
- WHERE pv.attribute_id = \'%s\'
- AND pv.product_id = p.id
- AND vt.language IS NULL
+ SELECT status_id FROM product_workflow_status pws
+ WHERE pws.product_id = p.id
LIMIT 1
) AS "%s"',
- $attribute->getId()->getValue(),
$key
));
} | 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\Workflow\Infrastructure\Grid\Builder\Query;
use Ergonode\Attribute\Domain\Entity\AbstractAttribute;
use Ergonode\Product\Infrastructure\Grid\Builder\Query\AbstractAttributeDataSetBuilder;
use Ergonode\Workflow\Domain\Entity\Attribute\StatusSystemAttribute;
use Doctrine\DBAL\Query\QueryBuilder;
use Ergonode\Core\Domain\ValueObject\Language;
/**
*/
class StatusAttributeDataSetQueryBuilder extends AbstractAttributeDataSetBuilder
{
/**
* {@inheritDoc}
*/
public function supports(AbstractAttribute $attribute): bool
{
return $attribute instanceof StatusSystemAttribute;
}
/**
* @param QueryBuilder $query
* @param string $key
* @param AbstractAttribute $attribute
* @param Language $language
*/
public function addSelect(QueryBuilder $query, string $key, AbstractAttribute $attribute, Language $language): void
{
$query->addSelect(sprintf(
'(
SELECT value FROM product_value pv
JOIN value_translation vt ON vt.value_id = pv.value_id
WHERE pv.attribute_id = \'%s\'
AND pv.product_id = p.id
AND vt.language IS NULL
LIMIT 1
) AS "%s"',
$attribute->getId()->getValue(),
$key
));
}
}
| 1 | 8,896 | Is `WHERE` should `Language` param ? | ergonode-backend | php |
@@ -46,6 +46,7 @@ namespace oneapi::dal::basic_statistics::backend {
namespace de = dal::detail;
namespace be = dal::backend;
namespace pr = dal::backend::primitives;
+namespace ps = oneapi::dal::preview::spmd;
using alloc = sycl::usm::alloc;
| 1 | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "oneapi/dal/algo/basic_statistics/backend/gpu/compute_kernel_dense_impl.hpp"
#include "oneapi/dal/backend/common.hpp"
#include "oneapi/dal/detail/common.hpp"
#include "oneapi/dal/backend/primitives/ndarray.hpp"
#include "oneapi/dal/detail/policy.hpp"
#include "oneapi/dal/detail/profiler.hpp"
#ifdef ONEDAL_DATA_PARALLEL
namespace oneapi::dal::basic_statistics::backend {
#define ASSERT_IF(enable_condition, condition) \
do { \
if constexpr (check_mask_flag(enable_condition, List)) { \
ONEDAL_ASSERT(condition); \
} \
} while (0)
#define DECLSET_IF(type, var, cond, value) \
type var = nullptr; \
if constexpr (check_mask_flag(cond, List)) { \
var = value; \
}
#define SET_IF(var, cond, value) \
if constexpr (check_mask_flag(cond, List)) { \
var = value; \
}
namespace de = dal::detail;
namespace be = dal::backend;
namespace pr = dal::backend::primitives;
using alloc = sycl::usm::alloc;
template <typename Data>
using local_accessor_rw_t =
sycl::accessor<Data, 1, sycl::access::mode::read_write, sycl::access::target::local>;
using comm_t = bk::communicator;
using dal::backend::context_gpu;
using method_t = method::dense;
using task_t = task::compute;
using input_t = compute_input<task_t>;
using result_t = compute_result<task_t>;
using descriptor_t = detail::descriptor_base<task_t>;
template <typename Float, bs_list List>
std::int64_t compute_kernel_dense_impl<Float, List>::get_row_block_count(std::int64_t row_count) {
ONEDAL_ASSERT(row_count > 0);
// TODO optimize the approach for row_block_count calculating
std::int64_t row_block_count = 128;
if (row_count < 5000)
row_block_count = 1;
else if (row_count < 10000)
row_block_count = 8;
else if (row_count < 20000)
row_block_count = 16;
else if (row_count < 50000)
row_block_count = 32;
else if (row_count < 100000)
row_block_count = 64;
return row_block_count;
}
template <typename Float, bs_list List>
std::int64_t compute_kernel_dense_impl<Float, List>::get_column_block_count(
std::int64_t column_count) {
ONEDAL_ASSERT(column_count > 0);
std::int64_t max_work_group_size =
q_.get_device().get_info<sycl::info::device::max_work_group_size>();
return (column_count + max_work_group_size - 1) / max_work_group_size;
}
template <typename Float, bs_list List>
result_t compute_kernel_dense_impl<Float, List>::get_result(const descriptor_t& desc,
const local_result<Float, List>& ndres,
std::int64_t column_count,
const bk::event_vector& deps) {
ONEDAL_ASSERT(column_count > 0);
result_t res;
const auto res_op = desc.get_result_options();
res.set_result_options(desc.get_result_options());
if (res_op.test(result_options::min)) {
ONEDAL_ASSERT(ndres.get_min().get_count() == column_count);
res.set_min(homogen_table::wrap(ndres.get_min().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::max)) {
ONEDAL_ASSERT(ndres.get_max().get_count() == column_count);
res.set_max(homogen_table::wrap(ndres.get_max().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::sum)) {
ONEDAL_ASSERT(ndres.get_sum().get_count() == column_count);
res.set_sum(homogen_table::wrap(ndres.get_sum().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::sum_squares)) {
ONEDAL_ASSERT(ndres.get_sum2().get_count() == column_count);
res.set_sum_squares(
homogen_table::wrap(ndres.get_sum2().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::sum_squares_centered)) {
ONEDAL_ASSERT(ndres.get_sum2cent().get_count() == column_count);
res.set_sum_squares_centered(
homogen_table::wrap(ndres.get_sum2cent().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::mean)) {
ONEDAL_ASSERT(ndres.get_mean().get_count() == column_count);
res.set_mean(homogen_table::wrap(ndres.get_mean().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::second_order_raw_moment)) {
ONEDAL_ASSERT(ndres.get_sorm().get_count() == column_count);
res.set_second_order_raw_moment(
homogen_table::wrap(ndres.get_sorm().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::variance)) {
ONEDAL_ASSERT(ndres.get_varc().get_count() == column_count);
res.set_variance(homogen_table::wrap(ndres.get_varc().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::standard_deviation)) {
ONEDAL_ASSERT(ndres.get_stdev().get_count() == column_count);
res.set_standard_deviation(
homogen_table::wrap(ndres.get_stdev().flatten(q_, deps), 1, column_count));
}
if (res_op.test(result_options::variation)) {
ONEDAL_ASSERT(ndres.get_vart().get_count() == column_count);
res.set_variation(homogen_table::wrap(ndres.get_vart().flatten(q_, deps), 1, column_count));
}
return res;
}
/* single pass kernel for device execution */
template <typename Float, bs_list List, bool DefferedFin>
inline void single_pass_block_processor(const Float* data_ptr,
Float* rmin_ptr,
Float* rmax_ptr,
Float* rsum_ptr,
Float* rsum2_ptr,
Float* rsum2cent_ptr,
Float* rmean_ptr,
Float* rsorm_ptr,
Float* rvarc_ptr,
Float* rstdev_ptr,
Float* rvart_ptr,
std::int64_t row_count,
std::int64_t column_count,
std::int64_t col_block_idx,
std::int64_t column_block_count,
std::int64_t tid,
std::int64_t tnum) {
const std::int64_t col_offset = col_block_idx * tnum;
const std::int64_t x = tid + col_offset;
if (x < column_count) {
std::int64_t row_block_size = row_count;
Float min = data_ptr[x];
Float max = data_ptr[x];
Float sum = Float(0);
Float sum2 = Float(0);
Float sum2cent = Float(0);
Float mean = Float(0);
for (std::int64_t row = 0; row < row_block_size; ++row) {
const std::int64_t y = row * column_count;
const Float el = data_ptr[y + x];
Float inv_n = Float(1) / (row + 1);
Float delta = el - mean;
min = sycl::fmin(el, min);
max = sycl::fmax(el, max);
sum += el;
sum2 += el * el;
mean += delta * inv_n;
sum2cent += delta * (el - mean);
}
if constexpr (check_mask_flag(bs_list::min, List)) {
rmin_ptr[x] = min;
}
if constexpr (check_mask_flag(bs_list::max, List)) {
rmax_ptr[x] = max;
}
if constexpr (check_mask_flag(bs_list::sum, List) ||
(DefferedFin && check_mask_flag(bs_list::mean | sum2cent_based_stat, List))) {
rsum_ptr[x] = sum;
}
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
rsum2_ptr[x] = sum2;
}
if constexpr (check_mask_flag(bs_list::sum2cent, List) ||
(DefferedFin &&
check_mask_flag(bs_list::varc | bs_list::stdev | bs_list::vart, List))) {
rsum2cent_ptr[x] = sum2cent;
}
// common vars calculation
Float variance = sum2cent / (row_block_size - Float(1));
Float stdev = (Float)sqrt(variance);
// output assignment
if constexpr (!DefferedFin && check_mask_flag(bs_list::mean, List)) {
rmean_ptr[x] = mean;
}
if constexpr (!DefferedFin && check_mask_flag(bs_list::sorm, List)) {
rsorm_ptr[x] = sum2 / row_block_size;
}
if constexpr (!DefferedFin && check_mask_flag(bs_list::varc, List)) {
rvarc_ptr[x] = variance;
}
if constexpr (!DefferedFin && check_mask_flag(bs_list::stdev, List)) {
rstdev_ptr[x] = stdev;
}
if constexpr (!DefferedFin && check_mask_flag(bs_list::vart, List)) {
rvart_ptr[x] = stdev / mean;
}
}
}
/* block processing kernel for device execution */
template <typename Float, bs_list List>
inline void block_processor(const Float* data_ptr,
std::int64_t* brc_ptr,
Float* bmin_ptr,
Float* bmax_ptr,
Float* bsum_ptr,
Float* bsum2_ptr,
Float* bsum2cent_ptr,
std::int64_t row_count,
std::int64_t row_block_idx,
std::int64_t row_block_count,
std::int64_t column_count,
std::int64_t column_block_idx,
std::int64_t column_block_count,
std::int64_t tid,
std::int64_t tnum) {
const std::int64_t col_offset = column_block_idx * tnum;
const std::int64_t x = tid + col_offset;
if (x < column_count) {
std::int64_t row_block_size = (row_count + row_block_count - 1) / row_block_count;
const std::int64_t row_offset = row_block_size * row_block_idx;
if (row_block_size + row_offset > row_count) {
row_block_size = row_count - row_offset;
}
Float min = data_ptr[row_offset * column_count + x];
Float max = data_ptr[row_offset * column_count + x];
Float sum = Float(0);
Float sum2 = Float(0);
Float sum2cent = Float(0);
Float mean = Float(0);
for (std::int64_t row = 0; row < row_block_size; ++row) {
const std::int64_t y = (row + row_offset) * column_count;
const Float el = data_ptr[y + x];
Float inv_n = Float(1) / (row + 1);
Float delta = el - mean;
min = sycl::fmin(el, min);
max = sycl::fmax(el, max);
sum += el;
sum2 += el * el;
mean += delta * inv_n;
sum2cent += delta * (el - mean);
}
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
brc_ptr[x * row_block_count + row_block_idx] = row_block_size;
}
if constexpr (check_mask_flag(bs_list::min, List)) {
bmin_ptr[x * row_block_count + row_block_idx] = min;
}
if constexpr (check_mask_flag(bs_list::max, List)) {
bmax_ptr[x * row_block_count + row_block_idx] = max;
}
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat, List)) {
bsum_ptr[x * row_block_count + row_block_idx] = sum;
}
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
bsum2_ptr[x * row_block_count + row_block_idx] = sum2;
}
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
bsum2cent_ptr[x * row_block_count + row_block_idx] = sum2cent;
}
}
}
/* block processing kernel for device execution */
template <typename Float, bs_list List, bool DefferedFin>
inline void merge_blocks_kernel(sycl::nd_item<1> item,
const std::int64_t* brc_ptr,
const Float* bmin_ptr,
const Float* bmax_ptr,
const Float* bsum_ptr,
const Float* bsum2_ptr,
const Float* bsum2cent_ptr,
std::int64_t* lrc_ptr,
Float* lmin_ptr,
Float* lmax_ptr,
Float* lsum_ptr,
Float* lsum2_ptr,
Float* lsum2cent_ptr,
Float* lmean_ptr,
Float* rmin_ptr,
Float* rmax_ptr,
Float* rsum_ptr,
Float* rsum2_ptr,
Float* rsum2cent_ptr,
Float* rmean_ptr,
Float* rsorm_ptr,
Float* rvarc_ptr,
Float* rstdev_ptr,
Float* rvart_ptr,
std::int64_t id,
std::int64_t group_id,
std::int64_t local_size,
std::int64_t block_count) {
Float mrgmin = Float(0);
if constexpr (check_mask_flag(bs_list::min, List)) {
mrgmin = bmin_ptr[group_id * block_count + id];
}
Float mrgmax = Float(0);
if constexpr (check_mask_flag(bs_list::max, List)) {
mrgmax = bmax_ptr[group_id * block_count + id];
}
Float mrgsum = Float(0);
Float mrgsum2 = Float(0);
Float mrgvectors = Float(0);
Float mrgsum2cent = Float(0);
Float mrgmean = Float(0);
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
lrc_ptr[id] = 0;
}
for (std::int64_t i = id; i < block_count; i += local_size) {
std::int64_t offset = group_id * block_count + i;
Float min = Float(0);
if constexpr (check_mask_flag(bs_list::min, List)) {
min = bmin_ptr[offset];
}
Float max = Float(0);
if constexpr (check_mask_flag(bs_list::max, List)) {
max = bmax_ptr[offset];
}
Float sum = Float(0);
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat, List)) {
sum = bsum_ptr[offset];
}
Float sum2 = Float(0);
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
sum2 = bsum2_ptr[offset];
}
std::int64_t rcnt = 1;
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
rcnt = brc_ptr[offset];
}
Float sum2cent = Float(0);
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
sum2cent = bsum2cent_ptr[offset];
}
Float mean = sum / static_cast<Float>(rcnt);
const Float sum_n1n2 = mrgvectors + static_cast<Float>(rcnt);
const Float mul_n1n2 = mrgvectors * static_cast<Float>(rcnt);
const Float delta_scale = mul_n1n2 / sum_n1n2;
const Float mean_scale = Float(1) / sum_n1n2;
const Float delta = mean - mrgmean;
mrgmin = sycl::fmin(min, mrgmin);
mrgmax = sycl::fmax(max, mrgmax);
mrgsum += sum;
mrgsum2 += sum2;
mrgsum2cent = mrgsum2cent + sum2cent + delta * delta * delta_scale;
mrgmean = (mrgmean * mrgvectors + mean * static_cast<Float>(rcnt)) * mean_scale;
mrgvectors = sum_n1n2;
if constexpr (check_mask_flag(bs_list::min, List)) {
lmin_ptr[id] = mrgmin;
}
if constexpr (check_mask_flag(bs_list::max, List)) {
lmax_ptr[id] = mrgmax;
}
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat, List)) {
lsum_ptr[id] = mrgsum;
}
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
lsum2_ptr[id] = mrgsum2;
}
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
lrc_ptr[id] += rcnt;
}
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
lsum2cent_ptr[id] = mrgsum2cent;
}
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
lmean_ptr[id] = mrgmean;
}
}
for (std::int64_t stride = sycl::min(local_size, block_count) / 2; stride > 0; stride /= 2) {
item.barrier(sycl::access::fence_space::local_space);
if (stride > id) {
std::int64_t offset = id + stride;
Float min = Float(0);
if constexpr (check_mask_flag(bs_list::min, List)) {
min = lmin_ptr[offset];
}
Float max = Float(0);
if constexpr (check_mask_flag(bs_list::max, List)) {
max = lmax_ptr[offset];
}
Float sum = Float(0);
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat,
List)) {
sum = lsum_ptr[offset];
}
Float sum2 = Float(0);
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
sum2 = lsum2_ptr[offset];
}
std::int64_t rcnt = 1;
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
rcnt = lrc_ptr[offset];
}
Float sum2cent = Float(0);
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
sum2cent = lsum2cent_ptr[offset];
}
Float mean = Float(0);
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
mean = lmean_ptr[offset];
}
const Float sum_n1n2 = mrgvectors + static_cast<Float>(rcnt);
const Float mul_n1n2 = mrgvectors * static_cast<Float>(rcnt);
const Float delta_scale = mul_n1n2 / sum_n1n2;
const Float mean_scale = Float(1) / sum_n1n2;
const Float delta = mean - mrgmean;
mrgmin = sycl::fmin(min, mrgmin);
mrgmax = sycl::fmax(max, mrgmax);
mrgsum += sum;
mrgsum2 += sum2;
mrgsum2cent = mrgsum2cent + sum2cent + delta * delta * delta_scale;
mrgmean = (mrgmean * mrgvectors + mean * static_cast<Float>(rcnt)) * mean_scale;
mrgvectors = sum_n1n2;
// item 0 collects all results in private vars
// but all others need to store it
if (0 < id) {
if constexpr (check_mask_flag(bs_list::min, List)) {
lmin_ptr[id] = mrgmin;
}
if constexpr (check_mask_flag(bs_list::max, List)) {
lmax_ptr[id] = mrgmax;
}
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat,
List)) {
lsum_ptr[id] = mrgsum;
}
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
lsum2_ptr[id] = mrgsum2;
}
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
lrc_ptr[id] += rcnt;
}
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
lsum2cent_ptr[id] = mrgsum2cent;
}
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
lmean_ptr[id] = mrgmean;
}
}
}
}
if (0 == id) {
if constexpr (check_mask_flag(bs_list::min, List)) {
rmin_ptr[group_id] = mrgmin;
}
if constexpr (check_mask_flag(bs_list::max, List)) {
rmax_ptr[group_id] = mrgmax;
}
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat, List)) {
rsum_ptr[group_id] = mrgsum;
}
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
rsum2_ptr[group_id] = mrgsum2;
}
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
rsum2cent_ptr[group_id] = mrgsum2cent;
}
if constexpr (!DefferedFin) {
Float mrgvariance = mrgsum2cent / (mrgvectors - Float(1));
Float mrgstdev = (Float)sqrt(mrgvariance);
if constexpr (check_mask_flag(bs_list::mean, List)) {
rmean_ptr[group_id] = mrgmean;
}
if constexpr (check_mask_flag(bs_list::sorm, List)) {
rsorm_ptr[group_id] = mrgsum2 / mrgvectors;
}
if constexpr (check_mask_flag(bs_list::varc, List)) {
rvarc_ptr[group_id] = mrgvariance;
}
if constexpr (check_mask_flag(bs_list::stdev, List)) {
rstdev_ptr[group_id] = mrgstdev;
}
if constexpr (check_mask_flag(bs_list::vart, List)) {
rvart_ptr[group_id] = mrgstdev / mrgmean;
}
}
}
}
template <typename Float, bs_list List>
std::tuple<local_result<Float, List>, sycl::event>
compute_kernel_dense_impl<Float, List>::merge_blocks(local_buffer_list<Float, List>&& ndbuf,
std::int64_t column_count,
std::int64_t block_count,
const bk::event_vector& deps) {
ONEDAL_PROFILER_TASK(merge_blocks, q_);
ONEDAL_ASSERT(column_count > 0);
ONEDAL_ASSERT(block_count > 0);
const bool distr_mode = comm_.get_rank_count() > 1;
auto ndres = local_result<Float, List>::empty(q_, column_count, distr_mode);
// ndres asserts
ASSERT_IF(bs_list::min, ndres.get_min().get_count() == column_count);
ASSERT_IF(bs_list::max, ndres.get_max().get_count() == column_count);
if (distr_mode) {
ASSERT_IF(bs_list::mean | sum2cent_based_stat, ndres.get_sum().get_count() == column_count);
}
else {
ASSERT_IF(bs_list::sum, ndres.get_sum().get_count() == column_count);
}
ASSERT_IF(bs_list::sum2 | bs_list::sorm, ndres.get_sum2().get_count() == column_count);
if (distr_mode) {
ASSERT_IF(bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_count() == column_count);
}
else {
ASSERT_IF(bs_list::sum2cent, ndres.get_sum2cent().get_count() == column_count);
}
ASSERT_IF(bs_list::mean, ndres.get_mean().get_count() == column_count);
ASSERT_IF(bs_list::sorm, ndres.get_sorm().get_count() == column_count);
ASSERT_IF(bs_list::varc, ndres.get_varc().get_count() == column_count);
ASSERT_IF(bs_list::stdev, ndres.get_stdev().get_count() == column_count);
ASSERT_IF(bs_list::vart, ndres.get_vart().get_count() == column_count);
// ndbuf asserts
ASSERT_IF(bs_list::mean | sum2cent_based_stat,
ndbuf.get_rc_list().get_count() == block_count * column_count);
ASSERT_IF(bs_list::min, ndbuf.get_min().get_count() == block_count * column_count);
ASSERT_IF(bs_list::max, ndbuf.get_max().get_count() == block_count * column_count);
ASSERT_IF(bs_list::sum | bs_list::mean | sum2cent_based_stat,
ndbuf.get_sum().get_count() == block_count * column_count);
ASSERT_IF(bs_list::sum2 | bs_list::sorm,
ndbuf.get_sum2().get_count() == block_count * column_count);
ASSERT_IF(sum2cent_based_stat, ndbuf.get_sum2cent().get_count() == block_count * column_count);
const std::int64_t* brc_ptr = ndbuf.get_rc_list().get_data();
const Float* bmin_ptr = ndbuf.get_min().get_data();
const Float* bmax_ptr = ndbuf.get_max().get_data();
const Float* bsum_ptr = ndbuf.get_sum().get_data();
const Float* bsum2_ptr = ndbuf.get_sum2().get_data();
const Float* bsum2cent_ptr = ndbuf.get_sum2cent().get_data();
DECLSET_IF(Float*, rmin_ptr, bs_list::min, ndres.get_min().get_mutable_data())
DECLSET_IF(Float*, rmax_ptr, bs_list::max, ndres.get_max().get_mutable_data())
DECLSET_IF(Float*,
rsum2_ptr,
bs_list::sum2 | bs_list::sorm,
ndres.get_sum2().get_mutable_data())
Float* rsum_ptr = nullptr;
if (distr_mode) {
SET_IF(rsum_ptr, bs_list::mean | sum2cent_based_stat, ndres.get_sum().get_mutable_data())
}
else {
SET_IF(rsum_ptr, bs_list::sum, ndres.get_sum().get_mutable_data())
}
Float* rsum2cent_ptr = nullptr;
if (distr_mode) {
SET_IF(rsum2cent_ptr,
bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_mutable_data())
}
else {
SET_IF(rsum2cent_ptr, bs_list::sum2cent, ndres.get_sum2cent().get_mutable_data())
}
DECLSET_IF(Float*, rmean_ptr, bs_list::mean, ndres.get_mean().get_mutable_data())
DECLSET_IF(Float*, rsorm_ptr, bs_list::sorm, ndres.get_sorm().get_mutable_data())
DECLSET_IF(Float*, rvarc_ptr, bs_list::varc, ndres.get_varc().get_mutable_data())
DECLSET_IF(Float*, rstdev_ptr, bs_list::stdev, ndres.get_stdev().get_mutable_data())
DECLSET_IF(Float*, rvart_ptr, bs_list::vart, ndres.get_vart().get_mutable_data())
std::int64_t local_size = bk::device_max_sg_size(q_);
auto global_size = de::check_mul_overflow(column_count, local_size);
constexpr bool deffered_fin_true = true;
constexpr bool deffered_fin_false = false;
const sycl::nd_range<1> nd_range = bk::make_multiple_nd_range_1d(global_size, local_size);
std::int64_t local_buffer_size = local_size;
auto last_event = q_.submit([&](cl::sycl::handler& cgh) {
cgh.depends_on(deps);
local_accessor_rw_t<std::int64_t> lrc_buf(local_buffer_size, cgh);
local_accessor_rw_t<Float> lmin_buf(local_buffer_size, cgh);
local_accessor_rw_t<Float> lmax_buf(local_buffer_size, cgh);
local_accessor_rw_t<Float> lsum_buf(local_buffer_size, cgh);
local_accessor_rw_t<Float> lsum2_buf(local_buffer_size, cgh);
local_accessor_rw_t<Float> lsum2cent_buf(local_buffer_size, cgh);
local_accessor_rw_t<Float> lmean_buf(local_buffer_size, cgh);
cgh.parallel_for(nd_range, [=](sycl::nd_item<1> item) {
const std::int64_t local_size = item.get_local_range()[0];
const std::int64_t id = item.get_local_id()[0];
const std::int64_t group_id = item.get_group().get_id(0);
std::int64_t* lrc_ptr = lrc_buf.get_pointer().get();
Float* lmin_ptr = lmin_buf.get_pointer().get();
Float* lmax_ptr = lmax_buf.get_pointer().get();
Float* lsum_ptr = lsum_buf.get_pointer().get();
Float* lsum2_ptr = lsum2_buf.get_pointer().get();
Float* lsum2cent_ptr = lsum2cent_buf.get_pointer().get();
Float* lmean_ptr = lmean_buf.get_pointer().get();
if (distr_mode) {
merge_blocks_kernel<Float, List, deffered_fin_true>(item,
brc_ptr,
bmin_ptr,
bmax_ptr,
bsum_ptr,
bsum2_ptr,
bsum2cent_ptr,
lrc_ptr,
lmin_ptr,
lmax_ptr,
lsum_ptr,
lsum2_ptr,
lsum2cent_ptr,
lmean_ptr,
rmin_ptr,
rmax_ptr,
rsum_ptr,
rsum2_ptr,
rsum2cent_ptr,
rmean_ptr,
rsorm_ptr,
rvarc_ptr,
rstdev_ptr,
rvart_ptr,
id,
group_id,
local_size,
block_count);
}
else {
merge_blocks_kernel<Float, List, deffered_fin_false>(item,
brc_ptr,
bmin_ptr,
bmax_ptr,
bsum_ptr,
bsum2_ptr,
bsum2cent_ptr,
lrc_ptr,
lmin_ptr,
lmax_ptr,
lsum_ptr,
lsum2_ptr,
lsum2cent_ptr,
lmean_ptr,
rmin_ptr,
rmax_ptr,
rsum_ptr,
rsum2_ptr,
rsum2cent_ptr,
rmean_ptr,
rsorm_ptr,
rvarc_ptr,
rstdev_ptr,
rvart_ptr,
id,
group_id,
local_size,
block_count);
}
});
});
last_event.wait_and_throw();
return std::make_tuple(std::move(ndres), std::move(last_event));
}
/* merge distributed blocks kernel */
template <typename Float, bs_list List>
std::tuple<local_result<Float, List>, sycl::event>
compute_kernel_dense_impl<Float, List>::merge_distr_blocks(
const pr::ndarray<std::int64_t, 1>& com_row_count,
const pr::ndarray<Float, 1>& com_sum,
const pr::ndarray<Float, 1>& com_sum2cent,
local_result<Float, List>&& ndres,
std::int64_t block_count,
std::int64_t column_count,
std::int64_t block_stride, // distance between first elemments of blocks',
// it can be > column_count for example in case if alignment is ussed
const bk::event_vector& deps) {
ONEDAL_ASSERT(block_count > 0);
ONEDAL_ASSERT(column_count > 0);
ONEDAL_ASSERT(block_stride > 0);
// ndres asserts
ASSERT_IF(bs_list::mean | sum2cent_based_stat, ndres.get_sum().get_count() == column_count);
ASSERT_IF(bs_list::sum2 | bs_list::sorm, ndres.get_sum2().get_count() == column_count);
ASSERT_IF(bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_count() == column_count);
ASSERT_IF(bs_list::mean, ndres.get_mean().get_count() == column_count);
ASSERT_IF(bs_list::sorm, ndres.get_sorm().get_count() == column_count);
ASSERT_IF(bs_list::varc, ndres.get_varc().get_count() == column_count);
ASSERT_IF(bs_list::stdev, ndres.get_stdev().get_count() == column_count);
ASSERT_IF(bs_list::vart, ndres.get_vart().get_count() == column_count);
ASSERT_IF(bs_list::mean | sum2cent_based_stat,
com_row_count.get_count() == comm_.get_rank_count());
ASSERT_IF(bs_list::mean | sum2cent_based_stat,
com_sum.get_count() == comm_.get_rank_count() * column_count);
ASSERT_IF(sum2cent_based_stat,
com_sum2cent.get_count() == comm_.get_rank_count() * column_count);
DECLSET_IF(Float*,
rsum_ptr,
bs_list::mean | sum2cent_based_stat,
ndres.get_sum().get_mutable_data())
DECLSET_IF(Float*,
rsum2cent_ptr,
bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_mutable_data())
DECLSET_IF(Float*, rmean_ptr, bs_list::mean, ndres.get_mean().get_mutable_data())
DECLSET_IF(Float*, rsorm_ptr, bs_list::sorm, ndres.get_sorm().get_mutable_data())
DECLSET_IF(Float*, rvarc_ptr, bs_list::varc, ndres.get_varc().get_mutable_data())
DECLSET_IF(Float*, rstdev_ptr, bs_list::stdev, ndres.get_stdev().get_mutable_data())
DECLSET_IF(Float*, rvart_ptr, bs_list::vart, ndres.get_vart().get_mutable_data())
const Float* rsum2_ptr = ndres.get_sum2().get_data();
const std::int64_t* brc_ptr = com_row_count.get_data();
const Float* bsum_ptr = com_sum.get_data();
const Float* bsum2cent_ptr = com_sum2cent.get_data();
const sycl::range<1> range{ de::integral_cast<size_t>(column_count) };
auto last_event = q_.submit([&](cl::sycl::handler& cgh) {
cgh.depends_on(deps);
cgh.parallel_for(range, [=](sycl::id<1> id) {
Float mrgsum = Float(0);
Float mrgvectors = Float(0);
Float mrgsum2cent = Float(0);
Float mrgmean = Float(0);
for (std::int64_t i = 0; i < block_count; ++i) {
std::int64_t offset = id + i * block_stride;
Float sum = Float(0);
if constexpr (check_mask_flag(bs_list::sum | bs_list::mean | sum2cent_based_stat,
List)) {
sum = bsum_ptr[offset];
}
Float rcnt = static_cast<Float>(brc_ptr[i]);
Float sum2cent = Float(0);
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
sum2cent = bsum2cent_ptr[offset];
}
Float mean = sum / rcnt;
Float sum_n1n2 = mrgvectors + rcnt;
Float mul_n1n2 = mrgvectors * rcnt;
Float delta_scale = mul_n1n2 / sum_n1n2;
Float mean_scale = Float(1) / sum_n1n2;
Float delta = mean - mrgmean;
mrgsum += sum;
mrgsum2cent = mrgsum2cent + sum2cent + delta * delta * delta_scale;
mrgmean = (mrgmean * mrgvectors + mean * rcnt) * mean_scale;
mrgvectors = sum_n1n2;
}
if constexpr (check_mask_flag(bs_list::sum, List)) {
rsum_ptr[id] = mrgsum;
}
if constexpr (check_mask_flag(bs_list::sum2cent, List)) {
rsum2cent_ptr[id] = mrgsum2cent;
}
if constexpr (check_mask_flag(bs_list::mean, List)) {
rmean_ptr[id] = mrgmean;
}
if constexpr (check_mask_flag(bs_list::sorm, List)) {
rsorm_ptr[id] = rsum2_ptr[id] / mrgvectors;
}
Float mrgvariance = mrgsum2cent / (mrgvectors - Float(1));
Float mrgstdev = sycl::sqrt(mrgvariance);
if constexpr (check_mask_flag(bs_list::varc, List)) {
rvarc_ptr[id] = mrgvariance;
}
if constexpr (check_mask_flag(bs_list::stdev, List)) {
rstdev_ptr[id] = mrgstdev;
}
if constexpr (check_mask_flag(bs_list::vart, List)) {
rvart_ptr[id] = mrgstdev / mrgmean;
}
});
});
last_event.wait_and_throw();
return std::make_tuple(std::forward<local_result_t>(ndres), last_event);
}
template <typename Float, bs_list List>
std::tuple<local_result<Float, List>, sycl::event>
compute_kernel_dense_impl<Float, List>::compute_single_pass(const pr::ndarray<Float, 2> data) {
ONEDAL_PROFILER_TASK(process_single_block, q_);
ONEDAL_ASSERT(data.has_data());
constexpr bool deffered_fin_true = true;
constexpr bool deffered_fin_false = false;
std::int64_t row_count = data.get_dimension(0);
std::int64_t column_count = data.get_dimension(1);
const bool distr_mode = comm_.get_rank_count() > 1;
auto ndres = local_result<Float, List>::empty(q_, column_count, distr_mode);
ASSERT_IF(bs_list::min, ndres.get_min().get_count() == column_count);
ASSERT_IF(bs_list::max, ndres.get_max().get_count() == column_count);
if (distr_mode) {
ASSERT_IF(bs_list::mean | sum2cent_based_stat, ndres.get_sum().get_count() == column_count);
}
else {
ASSERT_IF(bs_list::sum, ndres.get_sum().get_count() == column_count);
}
ASSERT_IF(bs_list::sum2 | bs_list::sorm, ndres.get_sum2().get_count() == column_count);
if (distr_mode) {
ASSERT_IF(bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_count() == column_count);
}
else {
ASSERT_IF(bs_list::sum2cent, ndres.get_sum2cent().get_count() == column_count);
}
ASSERT_IF(bs_list::mean, ndres.get_mean().get_count() == column_count);
ASSERT_IF(bs_list::sorm, ndres.get_sorm().get_count() == column_count);
ASSERT_IF(bs_list::varc, ndres.get_varc().get_count() == column_count);
ASSERT_IF(bs_list::stdev, ndres.get_stdev().get_count() == column_count);
ASSERT_IF(bs_list::vart, ndres.get_vart().get_count() == column_count);
const auto column_block_count = get_column_block_count(column_count);
auto data_ptr = data.get_data();
DECLSET_IF(Float*, rmin_ptr, bs_list::min, ndres.get_min().get_mutable_data())
DECLSET_IF(Float*, rmax_ptr, bs_list::max, ndres.get_max().get_mutable_data())
DECLSET_IF(Float*,
rsum2_ptr,
bs_list::sum2 | bs_list::sorm,
ndres.get_sum2().get_mutable_data())
Float* rsum_ptr = nullptr;
if (distr_mode) {
SET_IF(rsum_ptr, bs_list::mean | sum2cent_based_stat, ndres.get_sum().get_mutable_data())
}
else {
SET_IF(rsum_ptr, bs_list::sum, ndres.get_sum().get_mutable_data())
}
Float* rsum2cent_ptr = nullptr;
if (distr_mode) {
SET_IF(rsum2cent_ptr,
bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_mutable_data())
}
else {
SET_IF(rsum2cent_ptr, bs_list::sum2cent, ndres.get_sum2cent().get_mutable_data())
}
DECLSET_IF(Float*, rmean_ptr, bs_list::mean, ndres.get_mean().get_mutable_data())
DECLSET_IF(Float*, rsorm_ptr, bs_list::sorm, ndres.get_sorm().get_mutable_data())
DECLSET_IF(Float*, rvarc_ptr, bs_list::varc, ndres.get_varc().get_mutable_data())
DECLSET_IF(Float*, rstdev_ptr, bs_list::stdev, ndres.get_stdev().get_mutable_data())
DECLSET_IF(Float*, rvart_ptr, bs_list::vart, ndres.get_vart().get_mutable_data())
std::int64_t max_work_group_size =
q_.get_device().get_info<sycl::info::device::max_work_group_size>();
auto local_size = (max_work_group_size < column_count) ? max_work_group_size : column_count;
auto global_size = de::check_mul_overflow(column_block_count, local_size);
const sycl::nd_range<1> nd_range = bk::make_multiple_nd_range_1d(global_size, local_size);
auto last_event = q_.submit([&](sycl::handler& cgh) {
cgh.parallel_for(nd_range, [=](sycl::nd_item<1> item) {
const std::int64_t tid = item.get_local_id()[0];
const std::int64_t tnum = item.get_local_range()[0];
const std::int64_t gid = item.get_group().get_id(0);
const std::int64_t row_block_idx = gid / column_block_count;
const std::int64_t col_block_idx = gid - row_block_idx * column_block_count;
if (distr_mode) {
single_pass_block_processor<Float, List, deffered_fin_true>(data_ptr,
rmin_ptr,
rmax_ptr,
rsum_ptr,
rsum2_ptr,
rsum2cent_ptr,
rmean_ptr,
rsorm_ptr,
rvarc_ptr,
rstdev_ptr,
rvart_ptr,
row_count,
column_count,
col_block_idx,
column_block_count,
tid,
tnum);
}
else {
single_pass_block_processor<Float, List, deffered_fin_false>(data_ptr,
rmin_ptr,
rmax_ptr,
rsum_ptr,
rsum2_ptr,
rsum2cent_ptr,
rmean_ptr,
rsorm_ptr,
rvarc_ptr,
rstdev_ptr,
rvart_ptr,
row_count,
column_count,
col_block_idx,
column_block_count,
tid,
tnum);
}
});
});
return std::make_tuple(std::move(ndres), last_event);
}
template <typename Float, bs_list List>
std::tuple<local_result<Float, List>, sycl::event>
compute_kernel_dense_impl<Float, List>::compute_by_blocks(const pr::ndarray<Float, 2> data,
std::int64_t row_block_count) {
ONEDAL_ASSERT(data.has_data());
std::int64_t row_count = data.get_dimension(0);
std::int64_t column_count = data.get_dimension(1);
const auto column_block_count = get_column_block_count(column_count);
const auto aux_buf_size = de::check_mul_overflow(row_block_count, column_count);
auto ndbuf = local_buffer_list<Float, List>::empty(q_, aux_buf_size);
// ndbuf asserts
ASSERT_IF(bs_list::mean | sum2cent_based_stat, ndbuf.get_rc_list().get_count() == aux_buf_size);
ASSERT_IF(bs_list::min, ndbuf.get_min().get_count() == aux_buf_size);
ASSERT_IF(bs_list::max, ndbuf.get_max().get_count() == aux_buf_size);
ASSERT_IF(bs_list::sum | bs_list::mean | sum2cent_based_stat,
ndbuf.get_sum().get_count() == aux_buf_size);
ASSERT_IF(bs_list::sum2 | bs_list::sorm, ndbuf.get_sum2().get_count() == aux_buf_size);
ASSERT_IF(sum2cent_based_stat, ndbuf.get_sum2cent().get_count() == aux_buf_size);
DECLSET_IF(std::int64_t*,
ablock_rc_ptr,
bs_list::mean | sum2cent_based_stat,
ndbuf.get_rc_list().get_mutable_data())
DECLSET_IF(Float*, amin_ptr, bs_list::min, ndbuf.get_min().get_mutable_data())
DECLSET_IF(Float*, amax_ptr, bs_list::max, ndbuf.get_max().get_mutable_data())
DECLSET_IF(Float*,
asum_ptr,
bs_list::sum | bs_list::mean | sum2cent_based_stat,
ndbuf.get_sum().get_mutable_data())
DECLSET_IF(Float*,
asum2_ptr,
bs_list::sum2 | bs_list::sorm,
ndbuf.get_sum2().get_mutable_data())
DECLSET_IF(Float*, asum2cent_ptr, sum2cent_based_stat, ndbuf.get_sum2cent().get_mutable_data())
auto data_ptr = data.get_data();
std::int64_t max_work_group_size =
q_.get_device().get_info<sycl::info::device::max_work_group_size>();
auto local_size = (max_work_group_size < column_count) ? max_work_group_size : column_count;
auto global_size = de::check_mul_overflow(row_block_count * column_block_count, local_size);
const sycl::nd_range<1> nd_range = bk::make_multiple_nd_range_1d(global_size, local_size);
sycl::event last_event;
{
ONEDAL_PROFILER_TASK(process_blocks, q_);
last_event = q_.submit([&](sycl::handler& cgh) {
cgh.parallel_for(nd_range, [=](sycl::nd_item<1> item) {
const std::int64_t tid = item.get_local_id()[0];
const std::int64_t tnum = item.get_local_range()[0];
const std::int64_t gid = item.get_group().get_id(0);
const std::int64_t row_block_idx = gid / column_block_count;
const std::int64_t col_block_idx = gid - row_block_idx * column_block_count;
block_processor<Float, List>(data_ptr,
ablock_rc_ptr,
amin_ptr,
amax_ptr,
asum_ptr,
asum2_ptr,
asum2cent_ptr,
row_count,
row_block_idx,
row_block_count,
column_count,
col_block_idx,
column_block_count,
tid,
tnum);
});
});
}
auto [ndres, merge_event] =
merge_blocks(std::move(ndbuf), column_count, row_block_count, { last_event });
return std::make_tuple(std::move(ndres), merge_event);
}
template <typename Float, bs_list List>
std::tuple<local_result<Float, List>, sycl::event> compute_kernel_dense_impl<Float, List>::finalize(
local_result_t&& ndres,
std::int64_t row_count,
std::int64_t column_count,
const bk::event_vector& deps) {
ONEDAL_PROFILER_TASK(finalize, q_);
const bool distr_mode = comm_.get_rank_count() > 1;
// ndres asserts
ASSERT_IF(bs_list::min, ndres.get_min().get_count() == column_count);
ASSERT_IF(bs_list::max, ndres.get_max().get_count() == column_count);
if (distr_mode) {
ASSERT_IF(bs_list::mean | sum2cent_based_stat, ndres.get_sum().get_count() == column_count);
}
else {
ASSERT_IF(bs_list::sum, ndres.get_sum().get_count() == column_count);
}
ASSERT_IF(bs_list::sum2 | bs_list::sorm, ndres.get_sum2().get_count() == column_count);
if (distr_mode) {
ASSERT_IF(bs_list::varc | bs_list::stdev | bs_list::vart,
ndres.get_sum2cent().get_count() == column_count);
}
else {
ASSERT_IF(bs_list::sum2cent, ndres.get_sum2cent().get_count() == column_count);
}
sycl::event last_event;
if (distr_mode) {
if constexpr (check_mask_flag(bs_list::min, List)) {
comm_
.allreduce(q_,
ndres.get_min().get_data(),
ndres.get_min().get_mutable_data(),
ndres.get_min().get_count(),
de::v1::spmd_reduce_op::min,
deps)
.wait();
}
if constexpr (check_mask_flag(bs_list::max, List)) {
comm_
.allreduce(q_,
ndres.get_max().get_data(),
ndres.get_max().get_mutable_data(),
ndres.get_max().get_count(),
de::v1::spmd_reduce_op::max,
deps)
.wait();
}
if constexpr (check_mask_flag(bs_list::sum2 | bs_list::sorm, List)) {
comm_
.allreduce(q_,
ndres.get_sum2().get_data(),
ndres.get_sum2().get_mutable_data(),
ndres.get_sum2().get_count(),
de::v1::spmd_reduce_op::sum,
deps)
.wait();
}
pr::ndarray<std::int64_t, 1> com_row_count;
pr::ndarray<Float, 1> com_sum;
pr::ndarray<Float, 1> com_sum2cent;
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
auto com_row_count_host =
pr::ndarray<std::int64_t, 1>::empty({ comm_.get_rank_count() });
comm_.allgather(&row_count, 1, com_row_count_host.get_mutable_data(), 1).wait();
com_row_count = com_row_count_host.to_device(q_);
de::check_mul_overflow(comm_.get_rank_count(), column_count);
// sum is required for computing derived statistics, therefore it is suitable to get it by blocks instead of reducing
com_sum = pr::ndarray<Float, 1>::empty(q_,
{ comm_.get_rank_count() * column_count },
alloc::device);
comm_
.allgather(q_,
ndres.get_sum().get_data(),
column_count,
com_sum.get_mutable_data(),
column_count)
.wait();
}
else if constexpr (check_mask_flag(bs_list::sum, List)) {
comm_
.allreduce(q_,
ndres.get_sum().get_data(),
ndres.get_sum().get_mutable_data(),
ndres.get_sum().get_count(),
de::v1::spmd_reduce_op::sum,
deps)
.wait();
}
if constexpr (check_mask_flag(sum2cent_based_stat, List)) {
com_sum2cent = pr::ndarray<Float, 1>::empty(q_,
{ comm_.get_rank_count() * column_count },
alloc::device);
comm_
.allgather(q_,
ndres.get_sum2cent().get_data(),
column_count,
com_sum2cent.get_mutable_data(),
column_count)
.wait();
}
if constexpr (check_mask_flag(bs_list::mean | sum2cent_based_stat, List)) {
auto [merge_res, merge_event] = merge_distr_blocks(com_row_count,
com_sum,
com_sum2cent,
std::forward<local_result_t>(ndres),
comm_.get_rank_count(),
column_count,
column_count);
ndres = std::move(merge_res);
last_event = std::move(merge_event);
}
}
else {
sycl::event::wait_and_throw(deps);
}
return std::make_tuple(std::forward<local_result_t>(ndres), std::move(last_event));
}
template <typename Float, bs_list List>
result_t compute_kernel_dense_impl<Float, List>::operator()(const descriptor_t& desc,
const input_t& input) {
const auto data = input.get_data();
std::int64_t row_count = data.get_row_count();
std::int64_t column_count = data.get_column_count();
const auto data_nd = pr::table2ndarray<Float>(q_, data, alloc::device);
const auto row_block_count = get_row_block_count(row_count);
auto [ndres, last_event] = (row_block_count > 1) ? compute_by_blocks(data_nd, row_block_count)
: compute_single_pass(data_nd);
std::tie(ndres, last_event) =
finalize(std::move(ndres), row_count, column_count, { last_event });
return get_result(desc, std::move(ndres), column_count, { last_event })
.set_result_options(desc.get_result_options());
}
#define INSTANTIATE(LIST) \
template class compute_kernel_dense_impl<float, LIST>; \
template class compute_kernel_dense_impl<double, LIST>;
INSTANTIATE(bs_mode_min_max);
INSTANTIATE(bs_mode_mean_variance);
INSTANTIATE(bs_mode_all);
} // namespace oneapi::dal::basic_statistics::backend
#endif // ONEDAL_DATA_PARALLEL
| 1 | 32,424 | ps - first letter from preview, when we move it into public it will not be relevant. my suggestion is spmd or ds(distributed) | oneapi-src-oneDAL | cpp |
@@ -1757,7 +1757,18 @@ class Frame(object, metaclass=ABCMeta):
2 6 30 30
3 7 40 50
"""
- return self._apply_series_op(lambda kser: kser._with_new_scol(F.abs(kser.spark.column)))
+
+ def abs(kser):
+ if isinstance(kser.spark.data_type, BooleanType):
+ return kser
+ elif isinstance(kser.spark.data_type, NumericType):
+ return kser.spark.transform(F.abs)
+ else:
+ raise TypeError(
+ "bad operand type for abs(): {}".format(kser.spark.data_type.simpleString())
+ )
+
+ return self._apply_series_op(abs)
# TODO: by argument only support the grouping name and as_index only for now. Documentation
# should be updated when it's supported. | 1 | #
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
A base class of DataFrame/Column to behave similar to pandas DataFrame/Series.
"""
from abc import ABCMeta, abstractmethod
from collections import Counter
from collections.abc import Iterable
from distutils.version import LooseVersion
from functools import reduce
from typing import Any, List, Optional, Tuple, Union, TYPE_CHECKING, cast
import warnings
import numpy as np # noqa: F401
import pandas as pd
from pandas.api.types import is_list_like
import pyspark
from pyspark.sql import functions as F
from pyspark.sql.types import BooleanType, DoubleType, FloatType, LongType, NumericType
from databricks import koalas as ks # For running doctests and reference resolution in PyCharm.
from databricks.koalas.indexing import AtIndexer, iAtIndexer, iLocIndexer, LocIndexer
from databricks.koalas.internal import InternalFrame
from databricks.koalas.spark import functions as SF
from databricks.koalas.typedef import Scalar
from databricks.koalas.utils import (
is_name_like_tuple,
is_name_like_value,
name_like_string,
scol_for,
validate_arguments_and_invoke_function,
validate_axis,
)
from databricks.koalas.window import Rolling, Expanding
if TYPE_CHECKING:
from databricks.koalas.frame import DataFrame
from databricks.koalas.groupby import DataFrameGroupBy, SeriesGroupBy
from databricks.koalas.series import Series
class Frame(object, metaclass=ABCMeta):
"""
The base class for both DataFrame and Series.
"""
@abstractmethod
def __getitem__(self, key):
pass
@property
@abstractmethod
def _internal(self) -> InternalFrame:
pass
@abstractmethod
def _apply_series_op(self, op, should_resolve: bool = False):
pass
@abstractmethod
def _reduce_for_stat_function(self, sfun, name, axis=None, numeric_only=True, min_count=0):
pass
@property
@abstractmethod
def dtypes(self):
pass
@abstractmethod
def to_pandas(self):
pass
@property
@abstractmethod
def index(self):
pass
@abstractmethod
def copy(self):
pass
@abstractmethod
def _to_internal_pandas(self):
pass
@abstractmethod
def head(self, n: int = 5):
pass
# TODO: add 'axis' parameter
def cummin(self, skipna: bool = True) -> Union["Series", "DataFrame"]:
"""
Return cumulative minimum over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative minimum.
.. note:: the current implementation of cummin uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
skipna : boolean, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.
Returns
-------
DataFrame or Series
See Also
--------
DataFrame.min : Return the minimum over DataFrame axis.
DataFrame.cummax : Return cumulative maximum over DataFrame axis.
DataFrame.cummin : Return cumulative minimum over DataFrame axis.
DataFrame.cumsum : Return cumulative sum over DataFrame axis.
Series.min : Return the minimum over Series axis.
Series.cummax : Return cumulative maximum over Series axis.
Series.cummin : Return cumulative minimum over Series axis.
Series.cumsum : Return cumulative sum over Series axis.
Series.cumprod : Return cumulative product over Series axis.
Examples
--------
>>> df = ks.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the minimum in each column.
>>> df.cummin()
A B
0 2.0 1.0
1 2.0 NaN
2 1.0 0.0
It works identically in Series.
>>> df.A.cummin()
0 2.0
1 2.0
2 1.0
Name: A, dtype: float64
"""
return self._apply_series_op(
lambda kser: kser._cum(F.min, skipna), should_resolve=True
) # type: ignore
# TODO: add 'axis' parameter
def cummax(self, skipna: bool = True) -> Union["Series", "DataFrame"]:
"""
Return cumulative maximum over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative maximum.
.. note:: the current implementation of cummax uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
skipna : boolean, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.
Returns
-------
DataFrame or Series
See Also
--------
DataFrame.max : Return the maximum over DataFrame axis.
DataFrame.cummax : Return cumulative maximum over DataFrame axis.
DataFrame.cummin : Return cumulative minimum over DataFrame axis.
DataFrame.cumsum : Return cumulative sum over DataFrame axis.
DataFrame.cumprod : Return cumulative product over DataFrame axis.
Series.max : Return the maximum over Series axis.
Series.cummax : Return cumulative maximum over Series axis.
Series.cummin : Return cumulative minimum over Series axis.
Series.cumsum : Return cumulative sum over Series axis.
Series.cumprod : Return cumulative product over Series axis.
Examples
--------
>>> df = ks.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the maximum in each column.
>>> df.cummax()
A B
0 2.0 1.0
1 3.0 NaN
2 3.0 1.0
It works identically in Series.
>>> df.B.cummax()
0 1.0
1 NaN
2 1.0
Name: B, dtype: float64
"""
return self._apply_series_op(
lambda kser: kser._cum(F.max, skipna), should_resolve=True
) # type: ignore
# TODO: add 'axis' parameter
def cumsum(self, skipna: bool = True) -> Union["Series", "DataFrame"]:
"""
Return cumulative sum over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative sum.
.. note:: the current implementation of cumsum uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
skipna : boolean, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.
Returns
-------
DataFrame or Series
See Also
--------
DataFrame.sum : Return the sum over DataFrame axis.
DataFrame.cummax : Return cumulative maximum over DataFrame axis.
DataFrame.cummin : Return cumulative minimum over DataFrame axis.
DataFrame.cumsum : Return cumulative sum over DataFrame axis.
DataFrame.cumprod : Return cumulative product over DataFrame axis.
Series.sum : Return the sum over Series axis.
Series.cummax : Return cumulative maximum over Series axis.
Series.cummin : Return cumulative minimum over Series axis.
Series.cumsum : Return cumulative sum over Series axis.
Series.cumprod : Return cumulative product over Series axis.
Examples
--------
>>> df = ks.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the sum in each column.
>>> df.cumsum()
A B
0 2.0 1.0
1 5.0 NaN
2 6.0 1.0
It works identically in Series.
>>> df.A.cumsum()
0 2.0
1 5.0
2 6.0
Name: A, dtype: float64
"""
return self._apply_series_op(
lambda kser: kser._cum(F.sum, skipna), should_resolve=True
) # type: ignore
# TODO: add 'axis' parameter
# TODO: use pandas_udf to support negative values and other options later
# other window except unbounded ones is supported as of Spark 3.0.
def cumprod(self, skipna: bool = True) -> Union["Series", "DataFrame"]:
"""
Return cumulative product over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative product.
.. note:: the current implementation of cumprod uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
.. note:: unlike pandas', Koalas' emulates cumulative product by ``exp(sum(log(...)))``
trick. Therefore, it only works for positive numbers.
Parameters
----------
skipna : boolean, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.
Returns
-------
DataFrame or Series
See Also
--------
DataFrame.cummax : Return cumulative maximum over DataFrame axis.
DataFrame.cummin : Return cumulative minimum over DataFrame axis.
DataFrame.cumsum : Return cumulative sum over DataFrame axis.
DataFrame.cumprod : Return cumulative product over DataFrame axis.
Series.cummax : Return cumulative maximum over Series axis.
Series.cummin : Return cumulative minimum over Series axis.
Series.cumsum : Return cumulative sum over Series axis.
Series.cumprod : Return cumulative product over Series axis.
Raises
------
Exception : If the values is equal to or lower than 0.
Examples
--------
>>> df = ks.DataFrame([[2.0, 1.0], [3.0, None], [4.0, 10.0]], columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 4.0 10.0
By default, iterates over rows and finds the sum in each column.
>>> df.cumprod()
A B
0 2.0 1.0
1 6.0 NaN
2 24.0 10.0
It works identically in Series.
>>> df.A.cumprod()
0 2.0
1 6.0
2 24.0
Name: A, dtype: float64
"""
return self._apply_series_op(
lambda kser: kser._cumprod(skipna), should_resolve=True
) # type: ignore
# TODO: Although this has removed pandas >= 1.0.0, but we're keeping this as deprecated
# since we're using this for `DataFrame.info` internally.
# We can drop it once our minimal pandas version becomes 1.0.0.
def get_dtype_counts(self) -> pd.Series:
"""
Return counts of unique dtypes in this object.
.. deprecated:: 0.14.0
Returns
-------
dtype : pd.Series
Series with the count of columns with each dtype.
See Also
--------
dtypes : Return the dtypes in this object.
Examples
--------
>>> a = [['a', 1, 1], ['b', 2, 2], ['c', 3, 3]]
>>> df = ks.DataFrame(a, columns=['str', 'int1', 'int2'])
>>> df
str int1 int2
0 a 1 1
1 b 2 2
2 c 3 3
>>> df.get_dtype_counts().sort_values()
object 1
int64 2
dtype: int64
>>> df.str.get_dtype_counts().sort_values()
object 1
dtype: int64
"""
warnings.warn(
"`get_dtype_counts` has been deprecated and will be "
"removed in a future version. For DataFrames use "
"`.dtypes.value_counts()",
FutureWarning,
)
if not isinstance(self.dtypes, Iterable):
dtypes = [self.dtypes]
else:
dtypes = list(self.dtypes)
return pd.Series(dict(Counter([d.name for d in dtypes])))
def pipe(self, func, *args, **kwargs) -> Any:
r"""
Apply func(self, \*args, \*\*kwargs).
Parameters
----------
func : function
function to apply to the DataFrame.
``args``, and ``kwargs`` are passed into ``func``.
Alternatively a ``(callable, data_keyword)`` tuple where
``data_keyword`` is a string indicating the keyword of
``callable`` that expects the DataFrames.
args : iterable, optional
positional arguments passed into ``func``.
kwargs : mapping, optional
a dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``.
Notes
-----
Use ``.pipe`` when chaining together functions that expect
Series, DataFrames or GroupBy objects. For example, given
>>> df = ks.DataFrame({'category': ['A', 'A', 'B'],
... 'col1': [1, 2, 3],
... 'col2': [4, 5, 6]},
... columns=['category', 'col1', 'col2'])
>>> def keep_category_a(df):
... return df[df['category'] == 'A']
>>> def add_one(df, column):
... return df.assign(col3=df[column] + 1)
>>> def multiply(df, column1, column2):
... return df.assign(col4=df[column1] * df[column2])
instead of writing
>>> multiply(add_one(keep_category_a(df), column="col1"), column1="col2", column2="col3")
category col1 col2 col3 col4
0 A 1 4 2 8
1 A 2 5 3 15
You can write
>>> (df.pipe(keep_category_a)
... .pipe(add_one, column="col1")
... .pipe(multiply, column1="col2", column2="col3")
... )
category col1 col2 col3 col4
0 A 1 4 2 8
1 A 2 5 3 15
If you have a function that takes the data as (say) the second
argument, pass a tuple indicating which keyword expects the
data. For example, suppose ``f`` takes its data as ``df``:
>>> def multiply_2(column1, df, column2):
... return df.assign(col4=df[column1] * df[column2])
Then you can write
>>> (df.pipe(keep_category_a)
... .pipe(add_one, column="col1")
... .pipe((multiply_2, 'df'), column1="col2", column2="col3")
... )
category col1 col2 col3 col4
0 A 1 4 2 8
1 A 2 5 3 15
You can use lambda as wel
>>> ks.Series([1, 2, 3]).pipe(lambda x: (x + 1).rename("value"))
0 2
1 3
2 4
Name: value, dtype: int64
"""
if isinstance(func, tuple):
func, target = func
if target in kwargs:
raise ValueError("%s is both the pipe target and a keyword " "argument" % target)
kwargs[target] = self
return func(*args, **kwargs)
else:
return func(self, *args, **kwargs)
def to_numpy(self) -> np.ndarray:
"""
A NumPy ndarray representing the values in this DataFrame or Series.
.. note:: This method should only be used if the resulting NumPy ndarray is expected
to be small, as all the data is loaded into the driver's memory.
Returns
-------
numpy.ndarray
Examples
--------
>>> ks.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy()
array([[1, 3],
[2, 4]])
With heterogeneous data, the lowest common type will have to be used.
>>> ks.DataFrame({"A": [1, 2], "B": [3.0, 4.5]}).to_numpy()
array([[1. , 3. ],
[2. , 4.5]])
For a mix of numeric and non-numeric types, the output array will have object dtype.
>>> df = ks.DataFrame({"A": [1, 2], "B": [3.0, 4.5], "C": pd.date_range('2000', periods=2)})
>>> df.to_numpy()
array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],
[2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)
For Series,
>>> ks.Series(['a', 'b', 'a']).to_numpy()
array(['a', 'b', 'a'], dtype=object)
"""
return self.to_pandas().values
@property
def values(self) -> np.ndarray:
"""
Return a Numpy representation of the DataFrame or the Series.
.. warning:: We recommend using `DataFrame.to_numpy()` or `Series.to_numpy()` instead.
.. note:: This method should only be used if the resulting NumPy ndarray is expected
to be small, as all the data is loaded into the driver's memory.
Returns
-------
numpy.ndarray
Examples
--------
A DataFrame where all columns are the same type (e.g., int64) results in an array of
the same type.
>>> df = ks.DataFrame({'age': [ 3, 29],
... 'height': [94, 170],
... 'weight': [31, 115]})
>>> df
age height weight
0 3 94 31
1 29 170 115
>>> df.dtypes
age int64
height int64
weight int64
dtype: object
>>> df.values
array([[ 3, 94, 31],
[ 29, 170, 115]])
A DataFrame with mixed type columns(e.g., str/object, int64, float32) results in an ndarray
of the broadest type that accommodates these mixed types (e.g., object).
>>> df2 = ks.DataFrame([('parrot', 24.0, 'second'),
... ('lion', 80.5, 'first'),
... ('monkey', np.nan, None)],
... columns=('name', 'max_speed', 'rank'))
>>> df2.dtypes
name object
max_speed float64
rank object
dtype: object
>>> df2.values
array([['parrot', 24.0, 'second'],
['lion', 80.5, 'first'],
['monkey', nan, None]], dtype=object)
For Series,
>>> ks.Series([1, 2, 3]).values
array([1, 2, 3])
>>> ks.Series(list('aabc')).values
array(['a', 'a', 'b', 'c'], dtype=object)
"""
warnings.warn("We recommend using `{}.to_numpy()` instead.".format(type(self).__name__))
return self.to_numpy()
def to_csv(
self,
path=None,
sep=",",
na_rep="",
columns=None,
header=True,
quotechar='"',
date_format=None,
escapechar=None,
num_files=None,
mode: str = "overwrite",
partition_cols: Optional[Union[str, List[str]]] = None,
index_col: Optional[Union[str, List[str]]] = None,
**options
) -> Optional[str]:
r"""
Write object to a comma-separated values (csv) file.
.. note:: Koalas `to_csv` writes files to a path or URI. Unlike pandas', Koalas
respects HDFS's property such as 'fs.default.name'.
.. note:: Koalas writes CSV files into the directory, `path`, and writes
multiple `part-...` files in the directory when `path` is specified.
This behaviour was inherited from Apache Spark. The number of files can
be controlled by `num_files`.
Parameters
----------
path : str, default None
File path. If None is provided the result is returned as a string.
sep : str, default ','
String of length 1. Field delimiter for the output file.
na_rep : str, default ''
Missing data representation.
columns : sequence, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of strings is given it is
assumed to be aliases for the column names.
quotechar : str, default '\"'
String of length 1. Character used to quote fields.
date_format : str, default None
Format string for datetime objects.
escapechar : str, default None
String of length 1. Character used to escape `sep` and `quotechar`
when appropriate.
num_files : the number of files to be written in `path` directory when
this is a path.
mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'},
default 'overwrite'. Specifies the behavior of the save operation when the
destination exists already.
- 'append': Append the new data to existing data.
- 'overwrite': Overwrite existing data.
- 'ignore': Silently ignore this operation if data already exists.
- 'error' or 'errorifexists': Throw an exception if data already exists.
partition_cols : str or list of str, optional, default None
Names of partitioning columns
index_col: str or list of str, optional, default: None
Column names to be used in Spark to represent Koalas' index. The index name
in Koalas is ignored. By default, the index is always lost.
options: keyword arguments for additional options specific to PySpark.
This kwargs are specific to PySpark's CSV options to pass. Check
the options in PySpark's API documentation for spark.write.csv(...).
It has higher priority and overwrites all other options.
This parameter only works when `path` is specified.
Returns
-------
str or None
See Also
--------
read_csv
DataFrame.to_delta
DataFrame.to_table
DataFrame.to_parquet
DataFrame.to_spark_io
Examples
--------
>>> df = ks.DataFrame(dict(
... date=list(pd.date_range('2012-1-1 12:00:00', periods=3, freq='M')),
... country=['KR', 'US', 'JP'],
... code=[1, 2 ,3]), columns=['date', 'country', 'code'])
>>> df.sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
date country code
... 2012-01-31 12:00:00 KR 1
... 2012-02-29 12:00:00 US 2
... 2012-03-31 12:00:00 JP 3
>>> print(df.to_csv()) # doctest: +NORMALIZE_WHITESPACE
date,country,code
2012-01-31 12:00:00,KR,1
2012-02-29 12:00:00,US,2
2012-03-31 12:00:00,JP,3
>>> df.cummax().to_csv(path=r'%s/to_csv/foo.csv' % path, num_files=1)
>>> ks.read_csv(
... path=r'%s/to_csv/foo.csv' % path
... ).sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
date country code
... 2012-01-31 12:00:00 KR 1
... 2012-02-29 12:00:00 US 2
... 2012-03-31 12:00:00 US 3
In case of Series,
>>> print(df.date.to_csv()) # doctest: +NORMALIZE_WHITESPACE
date
2012-01-31 12:00:00
2012-02-29 12:00:00
2012-03-31 12:00:00
>>> df.date.to_csv(path=r'%s/to_csv/foo.csv' % path, num_files=1)
>>> ks.read_csv(
... path=r'%s/to_csv/foo.csv' % path
... ).sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
date
... 2012-01-31 12:00:00
... 2012-02-29 12:00:00
... 2012-03-31 12:00:00
You can preserve the index in the roundtrip as below.
>>> df.set_index("country", append=True, inplace=True)
>>> df.date.to_csv(
... path=r'%s/to_csv/bar.csv' % path,
... num_files=1,
... index_col=["index1", "index2"])
>>> ks.read_csv(
... path=r'%s/to_csv/bar.csv' % path, index_col=["index1", "index2"]
... ).sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
date
index1 index2
... ... 2012-01-31 12:00:00
... ... 2012-02-29 12:00:00
... ... 2012-03-31 12:00:00
"""
if "options" in options and isinstance(options.get("options"), dict) and len(options) == 1:
options = options.get("options") # type: ignore
if path is None:
# If path is none, just collect and use pandas's to_csv.
kdf_or_ser = self
if (LooseVersion("0.24") > LooseVersion(pd.__version__)) and isinstance(
self, ks.Series
):
# 0.23 seems not having 'columns' parameter in Series' to_csv.
return kdf_or_ser.to_pandas().to_csv( # type: ignore
None,
sep=sep,
na_rep=na_rep,
header=header,
date_format=date_format,
index=False,
)
else:
return kdf_or_ser.to_pandas().to_csv( # type: ignore
None,
sep=sep,
na_rep=na_rep,
columns=columns,
header=header,
quotechar=quotechar,
date_format=date_format,
escapechar=escapechar,
index=False,
)
kdf = self
if isinstance(self, ks.Series):
kdf = self.to_frame()
if columns is None:
column_labels = kdf._internal.column_labels
else:
column_labels = []
for label in columns:
if not is_name_like_tuple(label):
label = (label,)
if label not in kdf._internal.column_labels:
raise KeyError(name_like_string(label))
column_labels.append(label)
if isinstance(index_col, str):
index_cols = [index_col]
elif index_col is None:
index_cols = []
else:
index_cols = index_col
if header is True and kdf._internal.column_labels_level > 1:
raise ValueError("to_csv only support one-level index column now")
elif isinstance(header, list):
sdf = kdf.to_spark(index_col) # type: ignore
sdf = sdf.select(
[scol_for(sdf, name_like_string(label)) for label in index_cols]
+ [
scol_for(sdf, str(i) if label is None else name_like_string(label)).alias(
new_name
)
for i, (label, new_name) in enumerate(zip(column_labels, header))
]
)
header = True
else:
sdf = kdf.to_spark(index_col) # type: ignore
sdf = sdf.select(
[scol_for(sdf, name_like_string(label)) for label in index_cols]
+ [
scol_for(sdf, str(i) if label is None else name_like_string(label))
for i, label in enumerate(column_labels)
]
)
if num_files is not None:
sdf = sdf.repartition(num_files)
builder = sdf.write.mode(mode)
if partition_cols is not None:
builder.partitionBy(partition_cols)
builder._set_opts(
sep=sep,
nullValue=na_rep,
header=header,
quote=quotechar,
dateFormat=date_format,
charToEscapeQuoteEscaping=escapechar,
)
builder.options(**options).format("csv").save(path)
return None
def to_json(
self,
path=None,
compression="uncompressed",
num_files=None,
mode: str = "overwrite",
partition_cols: Optional[Union[str, List[str]]] = None,
index_col: Optional[Union[str, List[str]]] = None,
**options
) -> Optional[str]:
"""
Convert the object to a JSON string.
.. note:: Koalas `to_json` writes files to a path or URI. Unlike pandas', Koalas
respects HDFS's property such as 'fs.default.name'.
.. note:: Koalas writes JSON files into the directory, `path`, and writes
multiple `part-...` files in the directory when `path` is specified.
This behaviour was inherited from Apache Spark. The number of files can
be controlled by `num_files`.
.. note:: output JSON format is different from pandas'. It always use `orient='records'`
for its output. This behaviour might have to change in the near future.
Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.
Parameters
----------
path : string, optional
File path. If not specified, the result is returned as
a string.
compression : {'gzip', 'bz2', 'xz', None}
A string representing the compression to use in the output file,
only used when the first argument is a filename. By default, the
compression is inferred from the filename.
num_files : the number of files to be written in `path` directory when
this is a path.
mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'},
default 'overwrite'. Specifies the behavior of the save operation when the
destination exists already.
- 'append': Append the new data to existing data.
- 'overwrite': Overwrite existing data.
- 'ignore': Silently ignore this operation if data already exists.
- 'error' or 'errorifexists': Throw an exception if data already exists.
partition_cols : str or list of str, optional, default None
Names of partitioning columns
index_col: str or list of str, optional, default: None
Column names to be used in Spark to represent Koalas' index. The index name
in Koalas is ignored. By default, the index is always lost.
options: keyword arguments for additional options specific to PySpark.
It is specific to PySpark's JSON options to pass. Check
the options in PySpark's API documentation for `spark.write.json(...)`.
It has a higher priority and overwrites all other options.
This parameter only works when `path` is specified.
Returns
--------
str or None
Examples
--------
>>> df = ks.DataFrame([['a', 'b'], ['c', 'd']],
... columns=['col 1', 'col 2'])
>>> df.to_json()
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
>>> df['col 1'].to_json()
'[{"col 1":"a"},{"col 1":"c"}]'
>>> df.to_json(path=r'%s/to_json/foo.json' % path, num_files=1)
>>> ks.read_json(
... path=r'%s/to_json/foo.json' % path
... ).sort_values(by="col 1")
col 1 col 2
0 a b
1 c d
>>> df['col 1'].to_json(path=r'%s/to_json/foo.json' % path, num_files=1, index_col="index")
>>> ks.read_json(
... path=r'%s/to_json/foo.json' % path, index_col="index"
... ).sort_values(by="col 1") # doctest: +NORMALIZE_WHITESPACE
col 1
index
0 a
1 c
"""
if "options" in options and isinstance(options.get("options"), dict) and len(options) == 1:
options = options.get("options") # type: ignore
if path is None:
# If path is none, just collect and use pandas's to_json.
kdf_or_ser = self
pdf = kdf_or_ser.to_pandas() # type: ignore
if isinstance(self, ks.Series):
pdf = pdf.to_frame()
# To make the format consistent and readable by `read_json`, convert it to pandas' and
# use 'records' orient for now.
return pdf.to_json(orient="records")
kdf = self
if isinstance(self, ks.Series):
kdf = self.to_frame()
sdf = kdf.to_spark(index_col=index_col) # type: ignore
if num_files is not None:
sdf = sdf.repartition(num_files)
builder = sdf.write.mode(mode)
if partition_cols is not None:
builder.partitionBy(partition_cols)
builder._set_opts(compression=compression)
builder.options(**options).format("json").save(path)
return None
def to_excel(
self,
excel_writer,
sheet_name="Sheet1",
na_rep="",
float_format=None,
columns=None,
header=True,
index=True,
index_label=None,
startrow=0,
startcol=0,
engine=None,
merge_cells=True,
encoding=None,
inf_rep="inf",
verbose=True,
freeze_panes=None,
) -> None:
"""
Write object to an Excel sheet.
.. note:: This method should only be used if the resulting DataFrame is expected
to be small, as all the data is loaded into the driver's memory.
To write a single object to an Excel .xlsx file it is only necessary to
specify a target file name. To write to multiple sheets it is necessary to
create an `ExcelWriter` object with a target file name, and specify a sheet
in the file to write to.
Multiple sheets may be written to by specifying unique `sheet_name`.
With all data written to the file it is necessary to save the changes.
Note that creating an `ExcelWriter` object with a file name that already
exists will result in the contents of the existing file being erased.
Parameters
----------
excel_writer : str or ExcelWriter object
File path or existing ExcelWriter.
sheet_name : str, default 'Sheet1'
Name of sheet which will contain DataFrame.
na_rep : str, default ''
Missing data representation.
float_format : str, optional
Format string for floating point numbers. For example
``float_format="%%.2f"`` will format 0.1234 to 0.12.
columns : sequence or list of str, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of string is given it is
assumed to be aliases for the column names.
index : bool, default True
Write row names (index).
index_label : str or sequence, optional
Column label for index column(s) if desired. If not specified, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the DataFrame uses MultiIndex.
startrow : int, default 0
Upper left cell row to dump data frame.
startcol : int, default 0
Upper left cell column to dump data frame.
engine : str, optional
Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this
via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
``io.excel.xlsm.writer``.
merge_cells : bool, default True
Write MultiIndex and Hierarchical Rows as merged cells.
encoding : str, optional
Encoding of the resulting excel file. Only necessary for xlwt,
other writers support unicode natively.
inf_rep : str, default 'inf'
Representation for infinity (there is no native representation for
infinity in Excel).
verbose : bool, default True
Display more information in the error logs.
freeze_panes : tuple of int (length 2), optional
Specifies the one-based bottommost row and rightmost column that
is to be frozen.
Notes
-----
Once a workbook has been saved it is not possible write further data
without rewriting the whole workbook.
See Also
--------
read_excel : Read Excel file.
Examples
--------
Create, write to and save a workbook:
>>> df1 = ks.DataFrame([['a', 'b'], ['c', 'd']],
... index=['row 1', 'row 2'],
... columns=['col 1', 'col 2'])
>>> df1.to_excel("output.xlsx") # doctest: +SKIP
To specify the sheet name:
>>> df1.to_excel("output.xlsx") # doctest: +SKIP
>>> df1.to_excel("output.xlsx",
... sheet_name='Sheet_name_1') # doctest: +SKIP
If you wish to write to more than one sheet in the workbook, it is
necessary to specify an ExcelWriter object:
>>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP
... df1.to_excel(writer, sheet_name='Sheet_name_1')
... df2.to_excel(writer, sheet_name='Sheet_name_2')
To set the library that is used to write the Excel file,
you can pass the `engine` keyword (the default engine is
automatically chosen depending on the file extension):
>>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP
"""
# Make sure locals() call is at the top of the function so we don't capture local variables.
args = locals()
kdf = self
if isinstance(self, ks.DataFrame):
f = pd.DataFrame.to_excel
elif isinstance(self, ks.Series):
f = pd.Series.to_excel
else:
raise TypeError(
"Constructor expects DataFrame or Series; however, " "got [%s]" % (self,)
)
return validate_arguments_and_invoke_function(
kdf._to_internal_pandas(), self.to_excel, f, args
)
def mean(
self, axis: Union[int, str] = None, numeric_only: bool = True
) -> Union[Scalar, "Series"]:
"""
Return the mean of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
mean : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.mean()
a 2.0
b 0.2
dtype: float64
>>> df.mean(axis=1)
0 0.55
1 1.10
2 1.65
3 NaN
dtype: float64
On a Series:
>>> df['a'].mean()
2.0
"""
def mean(spark_column, spark_type):
if isinstance(spark_type, BooleanType):
spark_column = spark_column.cast(LongType())
elif not isinstance(spark_type, NumericType):
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return F.mean(spark_column)
return self._reduce_for_stat_function(
mean, name="mean", axis=axis, numeric_only=numeric_only
)
def sum(
self, axis: Union[int, str] = None, numeric_only: bool = True, min_count: int = 0
) -> Union[Scalar, "Series"]:
"""
Return the sum of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
min_count : int, default 0
The required number of valid values to perform the operation. If fewer than
``min_count`` non-NA values are present the result will be NA.
Returns
-------
sum : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, np.nan, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.sum()
a 6.0
b 0.4
dtype: float64
>>> df.sum(axis=1)
0 1.1
1 2.0
2 3.3
3 0.0
dtype: float64
>>> df.sum(min_count=3)
a 6.0
b NaN
dtype: float64
>>> df.sum(axis=1, min_count=1)
0 1.1
1 2.0
2 3.3
3 NaN
dtype: float64
On a Series:
>>> df['a'].sum()
6.0
>>> df['a'].sum(min_count=3)
6.0
>>> df['b'].sum(min_count=3)
nan
"""
def sum(spark_column, spark_type):
if isinstance(spark_type, BooleanType):
spark_column = spark_column.cast(LongType())
elif not isinstance(spark_type, NumericType):
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return F.coalesce(F.sum(spark_column), F.lit(0))
return self._reduce_for_stat_function(
sum, name="sum", axis=axis, numeric_only=numeric_only, min_count=min_count
)
def skew(
self, axis: Union[int, str] = None, numeric_only: bool = True
) -> Union[Scalar, "Series"]:
"""
Return unbiased skew normalized by N-1.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
skew : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.skew() # doctest: +SKIP
a 0.000000e+00
b -3.319678e-16
dtype: float64
On a Series:
>>> df['a'].skew()
0.0
"""
def skew(spark_column, spark_type):
if isinstance(spark_type, BooleanType):
spark_column = spark_column.cast(LongType())
elif not isinstance(spark_type, NumericType):
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return F.skewness(spark_column)
return self._reduce_for_stat_function(
skew, name="skew", axis=axis, numeric_only=numeric_only
)
def kurtosis(
self, axis: Union[int, str] = None, numeric_only: bool = True
) -> Union[Scalar, "Series"]:
"""
Return unbiased kurtosis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0).
Normalized by N-1.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
kurt : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.kurtosis()
a -1.5
b -1.5
dtype: float64
On a Series:
>>> df['a'].kurtosis()
-1.5
"""
def kurtosis(spark_column, spark_type):
if isinstance(spark_type, BooleanType):
spark_column = spark_column.cast(LongType())
elif not isinstance(spark_type, NumericType):
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return F.kurtosis(spark_column)
return self._reduce_for_stat_function(
kurtosis, name="kurtosis", axis=axis, numeric_only=numeric_only
)
kurt = kurtosis
def min(
self, axis: Union[int, str] = None, numeric_only: bool = None
) -> Union[Scalar, "Series"]:
"""
Return the minimum of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
If True, include only float, int, boolean columns. This parameter is mainly for
pandas compatibility. False is supported; however, the columns should
be all numeric or all non-numeric.
Returns
-------
min : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.min()
a 1.0
b 0.1
dtype: float64
>>> df.min(axis=1)
0 0.1
1 0.2
2 0.3
3 NaN
dtype: float64
On a Series:
>>> df['a'].min()
1.0
"""
return self._reduce_for_stat_function(
F.min, name="min", axis=axis, numeric_only=numeric_only
)
def max(
self, axis: Union[int, str] = None, numeric_only: bool = None
) -> Union[Scalar, "Series"]:
"""
Return the maximum of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
If True, include only float, int, boolean columns. This parameter is mainly for
pandas compatibility. False is supported; however, the columns should
be all numeric or all non-numeric.
Returns
-------
max : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.max()
a 3.0
b 0.3
dtype: float64
>>> df.max(axis=1)
0 1.0
1 2.0
2 3.0
3 NaN
dtype: float64
On a Series:
>>> df['a'].max()
3.0
"""
return self._reduce_for_stat_function(
F.max, name="max", axis=axis, numeric_only=numeric_only
)
def count(
self, axis: Union[int, str] = None, numeric_only: bool = None
) -> Union[Scalar, "Series"]:
"""
Count non-NA cells for each column.
The values `None`, `NaN` are considered NA.
Parameters
----------
axis : {0 or ‘index’, 1 or ‘columns’}, default 0
If 0 or ‘index’ counts are generated for each column. If 1 or ‘columns’ counts are
generated for each row.
numeric_only : bool, default None
If True, include only float, int, boolean columns. This parameter is mainly for
pandas compatibility.
Returns
-------
max : scalar for a Series, and a Series for a DataFrame.
See Also
--------
DataFrame.shape: Number of DataFrame rows and columns (including NA
elements).
DataFrame.isna: Boolean same-sized DataFrame showing places of NA
elements.
Examples
--------
Constructing DataFrame from a dictionary:
>>> df = ks.DataFrame({"Person":
... ["John", "Myla", "Lewis", "John", "Myla"],
... "Age": [24., np.nan, 21., 33, 26],
... "Single": [False, True, True, True, False]},
... columns=["Person", "Age", "Single"])
>>> df
Person Age Single
0 John 24.0 False
1 Myla NaN True
2 Lewis 21.0 True
3 John 33.0 True
4 Myla 26.0 False
Notice the uncounted NA values:
>>> df.count()
Person 5
Age 4
Single 5
dtype: int64
>>> df.count(axis=1)
0 3
1 2
2 3
3 3
4 3
dtype: int64
On a Series:
>>> df['Person'].count()
5
>>> df['Age'].count()
4
"""
return self._reduce_for_stat_function(
Frame._count_expr, name="count", axis=axis, numeric_only=numeric_only
)
def std(
self, axis: Union[int, str] = None, numeric_only: bool = True
) -> Union[Scalar, "Series"]:
"""
Return sample standard deviation.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
std : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.std()
a 1.0
b 0.1
dtype: float64
>>> df.std(axis=1)
0 0.636396
1 1.272792
2 1.909188
3 NaN
dtype: float64
On a Series:
>>> df['a'].std()
1.0
"""
def std(spark_column, spark_type):
if isinstance(spark_type, BooleanType):
spark_column = spark_column.cast(LongType())
elif not isinstance(spark_type, NumericType):
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return F.stddev(spark_column)
return self._reduce_for_stat_function(std, name="std", axis=axis, numeric_only=numeric_only)
def var(
self, axis: Union[int, str] = None, numeric_only: bool = True
) -> Union[Scalar, "Series"]:
"""
Return unbiased variance.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
var : scalar for a Series, and a Series for a DataFrame.
Examples
--------
>>> df = ks.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},
... columns=['a', 'b'])
On a DataFrame:
>>> df.var()
a 1.00
b 0.01
dtype: float64
>>> df.var(axis=1)
0 0.405
1 1.620
2 3.645
3 NaN
dtype: float64
On a Series:
>>> df['a'].var()
1.0
"""
def var(spark_column, spark_type):
if isinstance(spark_type, BooleanType):
spark_column = spark_column.cast(LongType())
elif not isinstance(spark_type, NumericType):
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return F.variance(spark_column)
return self._reduce_for_stat_function(var, name="var", axis=axis, numeric_only=numeric_only)
def median(
self, axis: Union[int, str] = None, numeric_only: bool = True, accuracy: int = 10000
) -> Union[Scalar, "Series"]:
"""
Return the median of the values for the requested axis.
.. note:: Unlike pandas', the median in Koalas is an approximated median based upon
approximate percentile computation because computing median across a large dataset
is extremely expensive.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default True
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
accuracy : int, optional
Default accuracy of approximation. Larger value means better accuracy.
The relative error can be deduced by 1.0 / accuracy.
Returns
-------
median : scalar or Series
Examples
--------
>>> df = ks.DataFrame({
... 'a': [24., 21., 25., 33., 26.], 'b': [1, 2, 3, 4, 5]}, columns=['a', 'b'])
>>> df
a b
0 24.0 1
1 21.0 2
2 25.0 3
3 33.0 4
4 26.0 5
On a DataFrame:
>>> df.median()
a 25.0
b 3.0
dtype: float64
On a Series:
>>> df['a'].median()
25.0
>>> (df['b'] + 100).median()
103.0
For multi-index columns,
>>> df.columns = pd.MultiIndex.from_tuples([('x', 'a'), ('y', 'b')])
>>> df
x y
a b
0 24.0 1
1 21.0 2
2 25.0 3
3 33.0 4
4 26.0 5
On a DataFrame:
>>> df.median()
x a 25.0
y b 3.0
dtype: float64
>>> df.median(axis=1)
0 12.5
1 11.5
2 14.0
3 18.5
4 15.5
dtype: float64
On a Series:
>>> df[('x', 'a')].median()
25.0
>>> (df[('y', 'b')] + 100).median()
103.0
"""
if not isinstance(accuracy, int):
raise ValueError(
"accuracy must be an integer; however, got [%s]" % type(accuracy).__name__
)
def median(spark_column, spark_type):
if isinstance(spark_type, (BooleanType, NumericType)):
spark_column = spark_column.cast(DoubleType())
else:
raise TypeError("Could not convert {} to numeric".format(spark_type.simpleString()))
return SF.percentile_approx(spark_column, 0.5, accuracy)
return self._reduce_for_stat_function(
median, name="median", numeric_only=numeric_only, axis=axis
)
@property
def size(self) -> int:
"""
Return an int representing the number of elements in this object.
Return the number of rows if Series. Otherwise return the number of
rows times number of columns if DataFrame.
Examples
--------
>>> s = ks.Series({'a': 1, 'b': 2, 'c': None})
>>> s.size
3
>>> df = ks.DataFrame({'col1': [1, 2, None], 'col2': [3, 4, None]})
>>> df.size
6
>>> df = ks.DataFrame(index=[1, 2, None])
>>> df.size
0
"""
num_columns = len(self._internal.data_spark_columns)
if num_columns == 0:
return 0
else:
return len(self) * num_columns # type: ignore
def abs(self) -> Union["DataFrame", "Series"]:
"""
Return a Series/DataFrame with absolute numeric value of each element.
Returns
-------
abs : Series/DataFrame containing the absolute value of each element.
Examples
--------
Absolute numeric values in a Series.
>>> s = ks.Series([-1.10, 2, -3.33, 4])
>>> s.abs()
0 1.10
1 2.00
2 3.33
3 4.00
dtype: float64
Absolute numeric values in a DataFrame.
>>> df = ks.DataFrame({
... 'a': [4, 5, 6, 7],
... 'b': [10, 20, 30, 40],
... 'c': [100, 50, -30, -50]
... },
... columns=['a', 'b', 'c'])
>>> df.abs()
a b c
0 4 10 100
1 5 20 50
2 6 30 30
3 7 40 50
"""
return self._apply_series_op(lambda kser: kser._with_new_scol(F.abs(kser.spark.column)))
# TODO: by argument only support the grouping name and as_index only for now. Documentation
# should be updated when it's supported.
def groupby(
self, by, axis=0, as_index: bool = True, dropna: bool = True
) -> Union["DataFrameGroupBy", "SeriesGroupBy"]:
"""
Group DataFrame or Series using a Series of columns.
A groupby operation involves some combination of splitting the
object, applying a function, and combining the results. This can be
used to group large amounts of data and compute operations on these
groups.
Parameters
----------
by : Series, label, or list of labels
Used to determine the groups for the groupby.
If Series is passed, the Series or dict VALUES
will be used to determine the groups. A label or list of
labels may be passed to group by the columns in ``self``.
axis : int, default 0 or 'index'
Can only be set to 0 at the moment.
as_index : bool, default True
For aggregated output, return object with group labels as the
index. Only relevant for DataFrame input. as_index=False is
effectively "SQL-style" grouped output.
dropna : bool, default True
If True, and if group keys contain NA values,
NA values together with row/column will be dropped.
If False, NA values will also be treated as the key in groups.
Returns
-------
DataFrameGroupBy or SeriesGroupBy
Depends on the calling object and returns groupby object that
contains information about the groups.
See Also
--------
koalas.groupby.GroupBy
Examples
--------
>>> df = ks.DataFrame({'Animal': ['Falcon', 'Falcon',
... 'Parrot', 'Parrot'],
... 'Max Speed': [380., 370., 24., 26.]},
... columns=['Animal', 'Max Speed'])
>>> df
Animal Max Speed
0 Falcon 380.0
1 Falcon 370.0
2 Parrot 24.0
3 Parrot 26.0
>>> df.groupby(['Animal']).mean().sort_index() # doctest: +NORMALIZE_WHITESPACE
Max Speed
Animal
Falcon 375.0
Parrot 25.0
>>> df.groupby(['Animal'], as_index=False).mean().sort_values('Animal')
... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Animal Max Speed
...Falcon 375.0
...Parrot 25.0
We can also choose to include NA in group keys or not by setting dropna parameter,
the default setting is True:
>>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]
>>> df = ks.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by=["b"]).sum().sort_index() # doctest: +NORMALIZE_WHITESPACE
a c
b
1.0 2 3
2.0 2 5
>>> df.groupby(by=["b"], dropna=False).sum().sort_index() # doctest: +NORMALIZE_WHITESPACE
a c
b
1.0 2 3
2.0 2 5
NaN 1 4
"""
from databricks.koalas.groupby import DataFrameGroupBy, SeriesGroupBy
if isinstance(by, ks.DataFrame):
raise ValueError("Grouper for '{}' not 1-dimensional".format(type(by).__name__))
elif isinstance(by, ks.Series):
by = [by]
elif is_name_like_tuple(by):
if isinstance(self, ks.Series):
raise KeyError(by)
by = [by]
elif is_name_like_value(by):
if isinstance(self, ks.Series):
raise KeyError(by)
by = [(by,)]
elif is_list_like(by):
new_by = [] # type: List[Union[Tuple, ks.Series]]
for key in by:
if isinstance(key, ks.DataFrame):
raise ValueError(
"Grouper for '{}' not 1-dimensional".format(type(key).__name__)
)
elif isinstance(key, ks.Series):
new_by.append(key)
elif is_name_like_tuple(key):
if isinstance(self, ks.Series):
raise KeyError(key)
new_by.append(key)
elif is_name_like_value(key):
if isinstance(self, ks.Series):
raise KeyError(key)
new_by.append((key,))
else:
raise ValueError(
"Grouper for '{}' not 1-dimensional".format(type(key).__name__)
)
by = new_by
else:
raise ValueError("Grouper for '{}' not 1-dimensional".format(type(by).__name__))
if not len(by):
raise ValueError("No group keys passed!")
axis = validate_axis(axis)
if axis != 0:
raise NotImplementedError('axis should be either 0 or "index" currently.')
if isinstance(self, ks.DataFrame):
return DataFrameGroupBy._build(self, by, as_index=as_index, dropna=dropna)
elif isinstance(self, ks.Series):
return SeriesGroupBy._build(self, by, as_index=as_index, dropna=dropna)
else:
raise TypeError(
"Constructor expects DataFrame or Series; however, " "got [%s]" % (self,)
)
def bool(self) -> bool:
"""
Return the bool of a single element in the current object.
This must be a boolean scalar value, either True or False. Raise a ValueError if
the object does not have exactly 1 element, or that element is not boolean
Returns
--------
bool
Examples
--------
>>> ks.DataFrame({'a': [True]}).bool()
True
>>> ks.Series([False]).bool()
False
If there are non-boolean or multiple values exist, it raises an exception in all
cases as below.
>>> ks.DataFrame({'a': ['a']}).bool()
Traceback (most recent call last):
...
ValueError: bool cannot act on a non-boolean single element DataFrame
>>> ks.DataFrame({'a': [True], 'b': [False]}).bool() # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().
>>> ks.Series([1]).bool()
Traceback (most recent call last):
...
ValueError: bool cannot act on a non-boolean single element DataFrame
"""
if isinstance(self, ks.DataFrame):
df = self
elif isinstance(self, ks.Series):
df = self.to_dataframe()
else:
raise TypeError("bool() expects DataFrame or Series; however, " "got [%s]" % (self,))
return df.head(2)._to_internal_pandas().bool()
def first_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:
"""
Retrieves the index of the first valid value.
Returns
-------
scalar, tuple, or None
Examples
--------
Support for DataFrame
>>> kdf = ks.DataFrame({'a': [None, 2, 3, 2],
... 'b': [None, 2.0, 3.0, 1.0],
... 'c': [None, 200, 400, 200]},
... index=['Q', 'W', 'E', 'R'])
>>> kdf
a b c
Q NaN NaN NaN
W 2.0 2.0 200.0
E 3.0 3.0 400.0
R 2.0 1.0 200.0
>>> kdf.first_valid_index()
'W'
Support for MultiIndex columns
>>> kdf.columns = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')])
>>> kdf
a b c
x y z
Q NaN NaN NaN
W 2.0 2.0 200.0
E 3.0 3.0 400.0
R 2.0 1.0 200.0
>>> kdf.first_valid_index()
'W'
Support for Series.
>>> s = ks.Series([None, None, 3, 4, 5], index=[100, 200, 300, 400, 500])
>>> s
100 NaN
200 NaN
300 3.0
400 4.0
500 5.0
dtype: float64
>>> s.first_valid_index()
300
Support for MultiIndex
>>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = ks.Series([None, None, None, None, 250, 1.5, 320, 1, 0.3], index=midx)
>>> s
lama speed NaN
weight NaN
length NaN
cow speed NaN
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.first_valid_index()
('cow', 'weight')
"""
data_spark_columns = self._internal.data_spark_columns
if len(data_spark_columns) == 0:
return None
cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))
first_valid_row = (
self._internal.spark_frame.filter(cond)
.select(self._internal.index_spark_columns)
.first()
)
# For Empty Series or DataFrame, returns None.
if first_valid_row is None:
return None
if len(first_valid_row) == 1:
return first_valid_row[0]
else:
return tuple(first_valid_row)
def last_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:
"""
Return index for last non-NA/null value.
Returns
-------
scalar, tuple, or None
Notes
-----
This API only works with PySpark >= 3.0.
Examples
--------
Support for DataFrame
>>> kdf = ks.DataFrame({'a': [1, 2, 3, None],
... 'b': [1.0, 2.0, 3.0, None],
... 'c': [100, 200, 400, None]},
... index=['Q', 'W', 'E', 'R'])
>>> kdf
a b c
Q 1.0 1.0 100.0
W 2.0 2.0 200.0
E 3.0 3.0 400.0
R NaN NaN NaN
>>> kdf.last_valid_index() # doctest: +SKIP
'E'
Support for MultiIndex columns
>>> kdf.columns = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')])
>>> kdf
a b c
x y z
Q 1.0 1.0 100.0
W 2.0 2.0 200.0
E 3.0 3.0 400.0
R NaN NaN NaN
>>> kdf.last_valid_index() # doctest: +SKIP
'E'
Support for Series.
>>> s = ks.Series([1, 2, 3, None, None], index=[100, 200, 300, 400, 500])
>>> s
100 1.0
200 2.0
300 3.0
400 NaN
500 NaN
dtype: float64
>>> s.last_valid_index() # doctest: +SKIP
300
Support for MultiIndex
>>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = ks.Series([250, 1.5, 320, 1, 0.3, None, None, None, None], index=midx)
>>> s
lama speed 250.0
weight 1.5
length 320.0
cow speed 1.0
weight 0.3
length NaN
falcon speed NaN
weight NaN
length NaN
dtype: float64
>>> s.last_valid_index() # doctest: +SKIP
('cow', 'weight')
"""
if LooseVersion(pyspark.__version__) < LooseVersion("3.0"):
raise RuntimeError("last_valid_index can be used in PySpark >= 3.0")
data_spark_columns = self._internal.data_spark_columns
if len(data_spark_columns) == 0:
return None
cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))
last_valid_rows = (
self._internal.spark_frame.filter(cond)
.select(self._internal.index_spark_columns)
.tail(1)
)
# For Empty Series or DataFrame, returns None.
if len(last_valid_rows) == 0:
return None
last_valid_row = last_valid_rows[0]
if len(last_valid_row) == 1:
return last_valid_row[0]
else:
return tuple(last_valid_row)
# TODO: 'center', 'win_type', 'on', 'axis' parameter should be implemented.
def rolling(self, window, min_periods=None) -> Rolling:
"""
Provide rolling transformations.
.. note:: 'min_periods' in Koalas works as a fixed window size unlike pandas.
Unlike pandas, NA is also counted as the period. This might be changed
in the near future.
Parameters
----------
window : int, or offset
Size of the moving window.
This is the number of observations used for calculating the statistic.
Each window will be a fixed size.
min_periods : int, default None
Minimum number of observations in window required to have a value
(otherwise result is NA).
For a window that is specified by an offset, min_periods will default to 1.
Otherwise, min_periods will default to the size of the window.
Returns
-------
a Window sub-classed for the particular operation
"""
return Rolling(self, window=window, min_periods=min_periods)
# TODO: 'center' and 'axis' parameter should be implemented.
# 'axis' implementation, refer https://github.com/databricks/koalas/pull/607
def expanding(self, min_periods=1) -> Expanding:
"""
Provide expanding transformations.
.. note:: 'min_periods' in Koalas works as a fixed window size unlike pandas.
Unlike pandas, NA is also counted as the period. This might be changed
in the near future.
Parameters
----------
min_periods : int, default 1
Minimum number of observations in window required to have a value
(otherwise result is NA).
Returns
-------
a Window sub-classed for the particular operation
"""
return Expanding(self, min_periods=min_periods)
def get(self, key, default=None) -> Any:
"""
Get item from object for given key (DataFrame column, Panel slice,
etc.). Returns default value if not found.
Parameters
----------
key : object
Returns
-------
value : same type as items contained in object
Examples
--------
>>> df = ks.DataFrame({'x':range(3), 'y':['a','b','b'], 'z':['a','b','b']},
... columns=['x', 'y', 'z'], index=[10, 20, 20])
>>> df
x y z
10 0 a a
20 1 b b
20 2 b b
>>> df.get('x')
10 0
20 1
20 2
Name: x, dtype: int64
>>> df.get(['x', 'y'])
x y
10 0 a
20 1 b
20 2 b
>>> df.x.get(10)
0
>>> df.x.get(20)
20 1
20 2
Name: x, dtype: int64
>>> df.x.get(15, -1)
-1
"""
try:
return self[key]
except (KeyError, ValueError, IndexError):
return default
def squeeze(self, axis=None) -> Union[Scalar, "DataFrame", "Series"]:
"""
Squeeze 1 dimensional axis objects into scalars.
Series or DataFrames with a single element are squeezed to a scalar.
DataFrames with a single column or a single row are squeezed to a
Series. Otherwise the object is unchanged.
This method is most useful when you don't know if your
object is a Series or DataFrame, but you do know it has just a single
column. In that case you can safely call `squeeze` to ensure you have a
Series.
Parameters
----------
axis : {0 or 'index', 1 or 'columns', None}, default None
A specific axis to squeeze. By default, all length-1 axes are
squeezed.
Returns
-------
DataFrame, Series, or scalar
The projection after squeezing `axis` or all the axes.
See Also
--------
Series.iloc : Integer-location based indexing for selecting scalars.
DataFrame.iloc : Integer-location based indexing for selecting Series.
Series.to_frame : Inverse of DataFrame.squeeze for a
single-column DataFrame.
Examples
--------
>>> primes = ks.Series([2, 3, 5, 7])
Slicing might produce a Series with a single value:
>>> even_primes = primes[primes % 2 == 0]
>>> even_primes
0 2
dtype: int64
>>> even_primes.squeeze()
2
Squeezing objects with more than one value in every axis does nothing:
>>> odd_primes = primes[primes % 2 == 1]
>>> odd_primes
1 3
2 5
3 7
dtype: int64
>>> odd_primes.squeeze()
1 3
2 5
3 7
dtype: int64
Squeezing is even more effective when used with DataFrames.
>>> df = ks.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> df
a b
0 1 2
1 3 4
Slicing a single column will produce a DataFrame with the columns
having only one value:
>>> df_a = df[['a']]
>>> df_a
a
0 1
1 3
So the columns can be squeezed down, resulting in a Series:
>>> df_a.squeeze('columns')
0 1
1 3
Name: a, dtype: int64
Slicing a single row from a single column will produce a single
scalar DataFrame:
>>> df_1a = df.loc[[1], ['a']]
>>> df_1a
a
1 3
Squeezing the rows produces a single scalar Series:
>>> df_1a.squeeze('rows')
a 3
Name: 1, dtype: int64
Squeezing all axes will project directly into a scalar:
>>> df_1a.squeeze()
3
"""
if axis is not None:
axis = "index" if axis == "rows" else axis
axis = validate_axis(axis)
if isinstance(self, ks.DataFrame):
from databricks.koalas.series import first_series
is_squeezable = len(self.columns[:2]) == 1
# If DataFrame has multiple columns, there is no change.
if not is_squeezable:
return self
series_from_column = first_series(self)
has_single_value = len(series_from_column.head(2)) == 1
# If DataFrame has only a single value, use pandas API directly.
if has_single_value:
result = self._to_internal_pandas().squeeze(axis)
return ks.Series(result) if isinstance(result, pd.Series) else result
elif axis == 0:
return self
else:
return series_from_column
else:
# The case of Series is simple.
# If Series has only a single value, just return it as a scalar.
# Otherwise, there is no change.
self_top_two = self.head(2)
has_single_value = len(self_top_two) == 1
return cast(Union[Scalar, ks.Series], self_top_two[0] if has_single_value else self)
def truncate(
self, before=None, after=None, axis=None, copy=True
) -> Union["DataFrame", "Series"]:
"""
Truncate a Series or DataFrame before and after some index value.
This is a useful shorthand for boolean indexing based on index
values above or below certain thresholds.
.. note:: This API is dependent on :meth:`Index.is_monotonic_increasing`
which can be expensive.
Parameters
----------
before : date, str, int
Truncate all rows before this index value.
after : date, str, int
Truncate all rows after this index value.
axis : {0 or 'index', 1 or 'columns'}, optional
Axis to truncate. Truncates the index (rows) by default.
copy : bool, default is True,
Return a copy of the truncated section.
Returns
-------
type of caller
The truncated Series or DataFrame.
See Also
--------
DataFrame.loc : Select a subset of a DataFrame by label.
DataFrame.iloc : Select a subset of a DataFrame by position.
Examples
--------
>>> df = ks.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],
... 'B': ['f', 'g', 'h', 'i', 'j'],
... 'C': ['k', 'l', 'm', 'n', 'o']},
... index=[1, 2, 3, 4, 5])
>>> df
A B C
1 a f k
2 b g l
3 c h m
4 d i n
5 e j o
>>> df.truncate(before=2, after=4)
A B C
2 b g l
3 c h m
4 d i n
The columns of a DataFrame can be truncated.
>>> df.truncate(before="A", after="B", axis="columns")
A B
1 a f
2 b g
3 c h
4 d i
5 e j
For Series, only rows can be truncated.
>>> df['A'].truncate(before=2, after=4)
2 b
3 c
4 d
Name: A, dtype: object
A Series has index that sorted integers.
>>> s = ks.Series([10, 20, 30, 40, 50, 60, 70],
... index=[1, 2, 3, 4, 5, 6, 7])
>>> s
1 10
2 20
3 30
4 40
5 50
6 60
7 70
dtype: int64
>>> s.truncate(2, 5)
2 20
3 30
4 40
5 50
dtype: int64
A Series has index that sorted strings.
>>> s = ks.Series([10, 20, 30, 40, 50, 60, 70],
... index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> s
a 10
b 20
c 30
d 40
e 50
f 60
g 70
dtype: int64
>>> s.truncate('b', 'e')
b 20
c 30
d 40
e 50
dtype: int64
"""
from databricks.koalas.series import first_series
axis = validate_axis(axis)
indexes = self.index
indexes_increasing = indexes.is_monotonic_increasing
if not indexes_increasing and not indexes.is_monotonic_decreasing:
raise ValueError("truncate requires a sorted index")
if (before is None) and (after is None):
return cast(Union[ks.DataFrame, ks.Series], self.copy() if copy else self)
if (before is not None and after is not None) and before > after:
raise ValueError("Truncate: %s must be after %s" % (after, before))
if isinstance(self, ks.Series):
if indexes_increasing:
result = first_series(self.to_frame().loc[before:after]).rename(self.name)
else:
result = first_series(self.to_frame().loc[after:before]).rename(self.name)
elif isinstance(self, ks.DataFrame):
if axis == 0:
if indexes_increasing:
result = self.loc[before:after]
else:
result = self.loc[after:before]
elif axis == 1:
result = self.loc[:, before:after]
return cast(Union[ks.DataFrame, ks.Series], result.copy() if copy else result)
def to_markdown(self, buf=None, mode=None) -> str:
"""
Print Series or DataFrame in Markdown-friendly format.
.. note:: This method should only be used if the resulting pandas object is expected
to be small, as all the data is loaded into the driver's memory.
Parameters
----------
buf : writable buffer, defaults to sys.stdout
Where to send the output. By default, the output is printed to
sys.stdout. Pass a writable buffer if you need to further process
the output.
mode : str, optional
Mode in which file is opened.
**kwargs
These parameters will be passed to `tabulate`.
Returns
-------
str
Series or DataFrame in Markdown-friendly format.
Examples
--------
>>> kser = ks.Series(["elk", "pig", "dog", "quetzal"], name="animal")
>>> print(kser.to_markdown()) # doctest: +SKIP
| | animal |
|---:|:---------|
| 0 | elk |
| 1 | pig |
| 2 | dog |
| 3 | quetzal |
>>> kdf = ks.DataFrame(
... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]}
... )
>>> print(kdf.to_markdown()) # doctest: +SKIP
| | animal_1 | animal_2 |
|---:|:-----------|:-----------|
| 0 | elk | dog |
| 1 | pig | quetzal |
"""
# `to_markdown` is supported in pandas >= 1.0.0 since it's newly added in pandas 1.0.0.
if LooseVersion(pd.__version__) < LooseVersion("1.0.0"):
raise NotImplementedError(
"`to_markdown()` only supported in Koalas with pandas >= 1.0.0"
)
# Make sure locals() call is at the top of the function so we don't capture local variables.
args = locals()
kser_or_kdf = self
internal_pandas = kser_or_kdf._to_internal_pandas()
return validate_arguments_and_invoke_function(
internal_pandas, self.to_markdown, type(internal_pandas).to_markdown, args
)
@abstractmethod
def fillna(self, value=None, method=None, axis=None, inplace=False, limit=None):
pass
# TODO: add 'downcast' when value parameter exists
def bfill(self, axis=None, inplace=False, limit=None) -> Union["DataFrame", "Series"]:
"""
Synonym for `DataFrame.fillna()` or `Series.fillna()` with ``method=`bfill```.
.. note:: the current implementation of 'bfill' uses Spark's Window
without specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
axis : {0 or `index`}
1 and `columns` are not supported.
inplace : boolean, default False
Fill in place (do not create a new object)
limit : int, default None
If method is specified, this is the maximum number of consecutive NaN values to
forward/backward fill. In other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. If method is not specified,
this is the maximum number of entries along the entire axis where NaNs will be filled.
Must be greater than 0 if not None
Returns
-------
DataFrame or Series
DataFrame or Series with NA entries filled.
Examples
--------
>>> kdf = ks.DataFrame({
... 'A': [None, 3, None, None],
... 'B': [2, 4, None, 3],
... 'C': [None, None, None, 1],
... 'D': [0, 1, 5, 4]
... },
... columns=['A', 'B', 'C', 'D'])
>>> kdf
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5
3 NaN 3.0 1.0 4
Propagate non-null values backward.
>>> kdf.bfill()
A B C D
0 3.0 2.0 1.0 0
1 3.0 4.0 1.0 1
2 NaN 3.0 1.0 5
3 NaN 3.0 1.0 4
For Series
>>> kser = ks.Series([None, None, None, 1])
>>> kser
0 NaN
1 NaN
2 NaN
3 1.0
dtype: float64
>>> kser.bfill()
0 1.0
1 1.0
2 1.0
3 1.0
dtype: float64
"""
return self.fillna(method="bfill", axis=axis, inplace=inplace, limit=limit)
backfill = bfill
# TODO: add 'downcast' when value parameter exists
def ffill(self, axis=None, inplace=False, limit=None) -> Union["DataFrame", "Series"]:
"""
Synonym for `DataFrame.fillna()` or `Series.fillna()` with ``method=`ffill```.
.. note:: the current implementation of 'ffill' uses Spark's Window
without specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
axis : {0 or `index`}
1 and `columns` are not supported.
inplace : boolean, default False
Fill in place (do not create a new object)
limit : int, default None
If method is specified, this is the maximum number of consecutive NaN values to
forward/backward fill. In other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. If method is not specified,
this is the maximum number of entries along the entire axis where NaNs will be filled.
Must be greater than 0 if not None
Returns
-------
DataFrame or Series
DataFrame or Series with NA entries filled.
Examples
--------
>>> kdf = ks.DataFrame({
... 'A': [None, 3, None, None],
... 'B': [2, 4, None, 3],
... 'C': [None, None, None, 1],
... 'D': [0, 1, 5, 4]
... },
... columns=['A', 'B', 'C', 'D'])
>>> kdf
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5
3 NaN 3.0 1.0 4
Propagate non-null values forward.
>>> kdf.ffill()
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 3.0 4.0 NaN 5
3 3.0 3.0 1.0 4
For Series
>>> kser = ks.Series([2, 4, None, 3])
>>> kser
0 2.0
1 4.0
2 NaN
3 3.0
dtype: float64
>>> kser.ffill()
0 2.0
1 4.0
2 4.0
3 3.0
dtype: float64
"""
return self.fillna(method="ffill", axis=axis, inplace=inplace, limit=limit)
pad = ffill
@property
def at(self) -> AtIndexer:
return AtIndexer(self)
at.__doc__ = AtIndexer.__doc__
@property
def iat(self) -> iAtIndexer:
return iAtIndexer(self)
iat.__doc__ = iAtIndexer.__doc__
@property
def iloc(self) -> iLocIndexer:
return iLocIndexer(self)
iloc.__doc__ = iLocIndexer.__doc__
@property
def loc(self) -> LocIndexer:
return LocIndexer(self)
loc.__doc__ = LocIndexer.__doc__
def __bool__(self):
raise ValueError(
"The truth value of a {0} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(self.__class__.__name__)
)
@staticmethod
def _count_expr(spark_column, spark_type):
# Special handle floating point types because Spark's count treats nan as a valid value,
# whereas pandas count doesn't include nan.
if isinstance(spark_type, (FloatType, DoubleType)):
return F.count(F.nanvl(spark_column, F.lit(None)))
else:
return F.count(spark_column)
| 1 | 17,420 | Hm, should we show pandas' dtype instead of Spark data type? | databricks-koalas | py |
@@ -23,10 +23,13 @@ namespace OpenTelemetry.Metrics
{
/*
Type:
- 0x10: Sum
- 0x20: Gauge
- 0x30: Histogram
- 0x40: Summary (reserved)
+ 0x10 0b00010000: Sum
+ 0x20 0b00100000: Gauge
+ 0x40 0b01000000: Histogram
+ 0x50 0b01010000: HistogramWithBuckets
+ 0x60 0b01100000: HistogramWithMinMax
+ 0x70 0b01110000: HistogramWithMinMaxAndBuckets
+ 0x80 0b10000000: Summary (reserved)
Point kind:
0x04: I1 (signed 1-byte integer) | 1 | // <copyright file="MetricType.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;
namespace OpenTelemetry.Metrics
{
[Flags]
public enum MetricType : byte
{
/*
Type:
0x10: Sum
0x20: Gauge
0x30: Histogram
0x40: Summary (reserved)
Point kind:
0x04: I1 (signed 1-byte integer)
0x05: U1 (unsigned 1-byte integer)
0x06: I2 (signed 2-byte integer)
0x07: U2 (unsigned 2-byte integer)
0x08: I4 (signed 4-byte integer)
0x09: U4 (unsigned 4-byte integer)
0x0a: I8 (signed 8-byte integer)
0x0b: U8 (unsigned 8-byte integer)
0x0c: R4 (4-byte floating point)
0x0d: R8 (8-byte floating point)
*/
/// <summary>
/// Sum of Long type.
/// </summary>
LongSum = 0x1a,
/// <summary>
/// Sum of Double type.
/// </summary>
DoubleSum = 0x1d,
/// <summary>
/// Gauge of Long type.
/// </summary>
LongGauge = 0x2a,
/// <summary>
/// Gauge of Double type.
/// </summary>
DoubleGauge = 0x2d,
/// <summary>
/// Histogram.
/// </summary>
Histogram = 0x30,
}
}
| 1 | 22,750 | @reyang when exponentialhistogram arrives, we won't have any bits left for it.. unless we take Summary or make this 16 bits instead of current 8 bytes | open-telemetry-opentelemetry-dotnet | .cs |
@@ -2,6 +2,8 @@
class PdoStatement {
/**
+ * @psalm-taint-sink text $class
+ *
* @template T
* @param class-string<T> $class
* @return false|T | 1 | <?php
class PdoStatement {
/**
* @template T
* @param class-string<T> $class
* @return false|T
*/
public function fetchObject($class = "stdclass") {}
}
| 1 | 9,429 | This change is not tested.. I guess this is how these taint-annotations work..? | vimeo-psalm | php |
@@ -485,6 +485,14 @@ class ConfigOverrider(object):
dest.dump()
+ def __apply_mult_override(self, obj, key, replace_value):
+ for k, v in obj.items():
+ if isinstance(v, dict):
+ obj[k] = self.__apply_mult_override(v, key, replace_value)
+ if key in obj:
+ obj[key] = replace_value
+ return obj
+
def __apply_single_override(self, dest, name, value):
"""
Apply single override | 1 | #! /usr/bin/env python
"""
Copyright 2015 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 copy
import logging
import os
import platform
import shutil
import signal
import sys
import tempfile
import traceback
from logging import Formatter
from optparse import OptionParser, Option
from tempfile import NamedTemporaryFile
import yaml
from colorlog import ColoredFormatter
import bzt
from bzt import ManualShutdown, NormalShutdown, RCProvider, TaurusException, AutomatedShutdown
from bzt import TaurusInternalException, TaurusConfigError, TaurusNetworkError, ToolError
from bzt.engine import Engine, Configuration, SETTINGS, EXEC
from bzt.linter import ConfigurationLinter
from bzt.six import HTTPError, string_types, get_stacktrace, integer_types
from bzt.utils import is_int, BetterDict, is_url, RESOURCES_DIR
class CLI(object):
"""
'cli' means 'tool' in hebrew, did you know that?
:param options: OptionParser parsed parameters
"""
console_handler = logging.StreamHandler(sys.stdout)
CLI_SETTINGS = "cli"
def __init__(self, options):
self.signal_count = 0
self.options = options
self.setup_logging(options)
self.log = logging.getLogger('')
self.log.info("Taurus CLI Tool v%s", bzt.VERSION)
self.log.debug("Command-line options: %s", self.options)
self.log.debug("Python: %s %s", platform.python_implementation(), platform.python_version())
self.log.debug("OS: %s", platform.uname())
self.engine = Engine(self.log)
self.exit_code = 0
@staticmethod
def setup_logging(options):
"""
Setting up console and file logging, colored if possible
:param options: OptionParser parsed options
"""
colors = {
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
fmt_file = Formatter("[%(asctime)s %(levelname)s %(name)s] %(message)s")
if sys.stdout.isatty():
fmt_verbose = ColoredFormatter("%(log_color)s[%(asctime)s %(levelname)s %(name)s] %(message)s",
log_colors=colors)
fmt_regular = ColoredFormatter("%(log_color)s%(asctime)s %(levelname)s: %(message)s",
"%H:%M:%S", log_colors=colors)
else:
fmt_verbose = Formatter("[%(asctime)s %(levelname)s %(name)s] %(message)s")
fmt_regular = Formatter("%(asctime)s %(levelname)s: %(message)s", "%H:%M:%S")
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
# log everything to file
if options.log is None:
tf = tempfile.NamedTemporaryFile(prefix="bzt_", suffix=".log", delete=False)
tf.close()
os.chmod(tf.name, 0o644)
options.log = tf.name
if options.log:
file_handler = logging.FileHandler(options.log, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(fmt_file)
logger.addHandler(file_handler)
# log something to console
if options.verbose:
CLI.console_handler.setLevel(logging.DEBUG)
CLI.console_handler.setFormatter(fmt_verbose)
elif options.quiet:
CLI.console_handler.setLevel(logging.WARNING)
CLI.console_handler.setFormatter(fmt_regular)
else:
CLI.console_handler.setLevel(logging.INFO)
CLI.console_handler.setFormatter(fmt_regular)
logger.addHandler(CLI.console_handler)
logging.getLogger("requests").setLevel(logging.WARNING) # misplaced?
def close_log(self):
"""
Close log handlers
:return:
"""
if self.options.log:
# need to finalize the logger before finishing
for handler in self.log.handlers[:]:
if issubclass(handler.__class__, logging.FileHandler):
self.log.debug("Closing log handler: %s", handler.baseFilename)
handler.close()
self.log.handlers.remove(handler)
def __move_log_to_artifacts(self):
"""
Close log handlers, copy log to artifacts dir, recreate file handlers
:return:
"""
if self.options.log:
for handler in self.log.handlers[:]:
if issubclass(handler.__class__, logging.FileHandler):
self.log.debug("Closing log handler: %s", handler.baseFilename)
handler.close()
self.log.handlers.remove(handler)
if os.path.exists(self.options.log):
self.engine.existing_artifact(self.options.log, move=True, target_filename="bzt.log")
self.options.log = os.path.join(self.engine.artifacts_dir, "bzt.log")
file_handler = logging.FileHandler(self.options.log, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(Formatter("[%(asctime)s %(levelname)s %(name)s] %(message)s"))
self.log.addHandler(file_handler)
self.log.debug("Switched writing logs to %s", self.options.log)
def __configure(self, configs):
self.log.info("Starting with configs: %s", configs)
if self.options.no_system_configs is None:
self.options.no_system_configs = False
bzt_rc = os.path.expanduser(os.path.join('~', ".bzt-rc"))
if os.path.exists(bzt_rc):
self.log.debug("Using personal config: %s" % bzt_rc)
else:
self.log.debug("Adding personal config: %s", bzt_rc)
self.log.info("No personal config found, creating one at %s", bzt_rc)
shutil.copy(os.path.join(RESOURCES_DIR, 'base-bzt-rc.yml'), bzt_rc)
merged_config = self.engine.configure([bzt_rc] + configs, not self.options.no_system_configs)
# apply aliases
for alias in self.options.aliases:
cli_aliases = self.engine.config.get('cli-aliases')
keys = sorted(cli_aliases.keys())
err = TaurusConfigError("'%s' not found in aliases. Available aliases are: %s" % (alias, ", ".join(keys)))
self.engine.config.merge(cli_aliases.get(alias, err))
if self.options.option:
overrider = ConfigOverrider(self.log)
overrider.apply_overrides(self.options.option, self.engine.config)
if self.__is_verbose():
CLI.console_handler.setLevel(logging.DEBUG)
self.engine.create_artifacts_dir(configs, merged_config)
self.engine.default_cwd = os.getcwd()
self.engine.eval_env() # yacky, I don't like having it here, but how to apply it after aliases and artif dir?
def __is_verbose(self):
settings = self.engine.config.get(SETTINGS, force_set=True)
settings.get('verbose', bool(self.options.verbose)) # respect value from config
if self.options.verbose: # force verbosity if cmdline asked for it
settings['verbose'] = True
return settings.get('verbose', False)
def __lint_config(self):
settings = self.engine.config.get(CLI.CLI_SETTINGS).get("linter")
self.log.debug("Linting config")
self.warn_on_unfamiliar_fields = settings.get("warn-on-unfamiliar-fields", True)
config_copy = copy.deepcopy(self.engine.config)
ignored_warnings = settings.get("ignored-warnings", [])
self.linter = ConfigurationLinter(config_copy, ignored_warnings, self.log)
self.linter.register_checkers()
self.linter.lint()
warnings = self.linter.get_warnings()
for warning in warnings:
self.log.warning(str(warning))
if settings.get("lint-and-exit", False):
if warnings:
raise TaurusConfigError("Errors were found in the configuration")
else:
raise NormalShutdown("Linting has finished, no errors were found")
def _level_down_logging(self):
target = logging.DEBUG if self.__is_verbose() else logging.INFO
for handler in self.log.handlers:
if issubclass(handler.__class__, logging.FileHandler):
if handler.level != target:
msg = "Leveling down log file verbosity to %s, use -v option to have DEBUG messages enabled"
self.log.debug(msg, logging.getLevelName(target))
handler.setLevel(target)
def _level_up_logging(self):
for handler in self.log.handlers:
if issubclass(handler.__class__, logging.FileHandler):
if handler.level != logging.DEBUG:
handler.setLevel(logging.DEBUG)
self.log.debug("Leveled up log file verbosity")
def perform(self, configs):
"""
Run the tool
:type configs: list
:return: integer exit code
"""
url_shorthands = []
jmx_shorthands = []
jtl_shorthands = []
try:
url_shorthands = self.__get_url_shorthands(configs)
configs.extend(url_shorthands)
jmx_shorthands = self.__get_jmx_shorthands(configs)
configs.extend(jmx_shorthands)
jtl_shorthands = self.__get_jtl_shorthands(configs)
configs.extend(jtl_shorthands)
if not self.engine.config.get(SETTINGS).get('verbose', False, force_set=True):
self.engine.logging_level_down = self._level_down_logging
self.engine.logging_level_up = self._level_up_logging
self.__configure(configs)
self.__move_log_to_artifacts()
self.__lint_config()
self.engine.prepare()
self.engine.run()
except BaseException as exc:
self.handle_exception(exc)
finally:
try:
for fname in url_shorthands + jmx_shorthands + jtl_shorthands:
os.remove(fname)
self.engine.post_process()
except BaseException as exc:
self.handle_exception(exc)
self.log.info("Artifacts dir: %s", self.engine.artifacts_dir)
if self.engine.artifacts_dir is None:
self.log.info("Log file: %s", self.options.log)
if self.exit_code:
self.log.warning("Done performing with code: %s", self.exit_code)
else:
self.log.info("Done performing with code: %s", self.exit_code)
self.close_log()
return self.exit_code
def handle_exception(self, exc):
log_level = {'info': logging.DEBUG, 'http': logging.DEBUG, 'default': logging.DEBUG}
if not self.exit_code: # only fist exception goes to the screen
log_level['info'] = logging.WARNING
log_level['http'] = logging.ERROR
log_level['default'] = logging.ERROR
if isinstance(exc, RCProvider):
self.exit_code = exc.get_rc()
else:
self.exit_code = 1
if isinstance(exc, KeyboardInterrupt):
self.__handle_keyboard_interrupt(exc, log_level)
log_level['default'] = logging.DEBUG
elif isinstance(exc, TaurusException):
self.__handle_taurus_exception(exc, log_level['default'])
log_level['default'] = logging.DEBUG
elif isinstance(exc, HTTPError):
msg = "Response from %s: [%s] %s %s" % (exc.geturl(), exc.code, exc.reason, exc.read())
self.log.log(log_level['http'], msg)
log_level['default'] = logging.DEBUG
self.log.log(log_level['default'], "%s: %s\n%s", type(exc).__name__, exc, get_stacktrace(exc))
def __handle_keyboard_interrupt(self, exc, log_level):
if isinstance(exc, ManualShutdown):
self.log.log(log_level['info'], "Interrupted by user")
elif isinstance(exc, AutomatedShutdown):
self.log.log(log_level['info'], "Automated shutdown")
elif isinstance(exc, NormalShutdown):
self.log.log(logging.DEBUG, "Shutting down by request from code")
elif isinstance(exc, KeyboardInterrupt):
self.log.log(log_level['info'], "Keyboard interrupt")
else:
msg = "Non-KeyboardInterrupt exception %s: %s\n%s"
raise ValueError(msg % (type(exc), exc, get_stacktrace(exc)))
def __handle_taurus_exception(self, exc, log_level):
if isinstance(exc, TaurusConfigError):
self.log.log(log_level, "Config Error: %s", exc)
elif isinstance(exc, TaurusInternalException):
self.log.log(log_level, "Internal Error: %s", exc)
elif isinstance(exc, ToolError):
self.log.log(log_level, "Child Process Error: %s", exc)
if exc.diagnostics is not None:
for line in exc.diagnostics:
self.log.log(log_level, line)
elif isinstance(exc, TaurusNetworkError):
self.log.log(log_level, "Network Error: %s", exc)
else:
self.log.log(log_level, "Generic Taurus Error: %s", exc)
def __get_jmx_shorthands(self, configs):
"""
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
"""
jmxes = []
for filename in configs[:]:
if filename.lower().endswith(".jmx"):
jmxes.append(filename)
configs.remove(filename)
if jmxes:
self.log.debug("Adding JMX shorthand config for: %s", jmxes)
fds = NamedTemporaryFile(prefix="jmx_", suffix=".json")
fname = fds.name
fds.close()
config = Configuration()
for jmx_file in jmxes:
piece = BetterDict.from_dict({"executor": "jmeter", "scenario": {"script": jmx_file}})
config.get(EXEC, [], force_set=True).append(piece) # Does it brake single execution?
config.dump(fname, Configuration.JSON)
return [fname]
else:
return []
def __get_jtl_shorthands(self, configs):
"""
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
"""
jtls = []
for filename in configs[:]:
if filename.lower().endswith(".jtl"):
jtls.append(filename)
configs.remove(filename)
if jtls:
self.log.debug("Adding JTL shorthand config for: %s", jtls)
fds = NamedTemporaryFile(prefix="jtl_", suffix=".json")
fname = fds.name
fds.close()
config = Configuration()
for jtl in jtls:
piece = BetterDict.from_dict({"executor": "external-results-loader", "data-file": jtl})
config.get(EXEC, [], force_set=True).append(piece)
config.dump(fname, Configuration.JSON)
return [fname]
else:
return []
def __get_url_shorthands(self, configs):
"""
:type configs: list
:return: list
"""
urls = []
for candidate in configs[:]:
if is_url(candidate):
urls.append(candidate)
configs.remove(candidate)
if urls:
self.log.debug("Adding HTTP shorthand config for: %s", urls)
config_fds = NamedTemporaryFile(prefix="http_", suffix=".yml")
fname = config_fds.name
config_fds.close()
config = Configuration.from_dict({
"execution": [{
"concurrency": "${__tstFeedback(Throughput_Limiter,1,${__P(concurrencyCap,1)},2)}",
"hold-for": "2m",
"throughput": "${__P(throughput,600)}",
"scenario": "linear-growth",
}],
"scenarios": {
"linear-growth": {
"retrieve-resources": False,
"timeout": "5s",
"keepalive": False,
"requests": [{
"action": "pause",
"pause-duration": 0,
"jsr223": [{
"language": "javascript",
"execute": "before",
"script-text": """
var startTime = parseInt(props.get("startTime"));
if (!startTime) {
startTime = Math.floor((new Date()).getTime() / 1000);
props.put("startTime", startTime);
} else {
var now = Math.floor((new Date()).getTime() / 1000);
var offset = now - startTime;
if (offset < 60) {
var targetOffset = Math.max(offset * 10, 10);
props.put("throughput", targetOffset.toString());
}
}"""
}]
}] + urls,
}
},
"modules": {
"jmeter": {
"properties": {
"throughput": 1,
"concurrencyCap": 500,
},
}
}
})
config.dump(fname, Configuration.JSON)
return [fname]
else:
return []
class ConfigOverrider(object):
def __init__(self, logger):
"""
:type logger: logging.Logger
"""
super(ConfigOverrider, self).__init__()
self.log = logger.getChild(self.__class__.__name__)
def apply_overrides(self, options, dest):
"""
Apply overrides
:type options: list[str]
:type dest: Configuration
"""
for option in options:
name = option[:option.index('=')]
value = option[option.index('=') + 1:]
try:
self.__apply_single_override(dest, name, value)
except BaseException:
self.log.debug("Failed override: %s", traceback.format_exc())
self.log.error("Failed to apply override %s=%s", name, value)
raise
dest.dump()
def __apply_single_override(self, dest, name, value):
"""
Apply single override
:type name: str
:type value: str
"""
self.log.debug("Applying %s=%s", name, value)
parts = [(int(x) if is_int(x) else x) for x in name.split(".")]
pointer = dest
for index, part in enumerate(parts[:-1]):
self.__ensure_list_capacity(pointer, part, parts[index + 1])
if isinstance(part, integer_types):
if part < 0:
if isinstance(parts[index + 1], integer_types):
pointer.append([])
else:
pointer.append(BetterDict())
pointer = pointer[-1]
else:
pointer = pointer[part]
elif isinstance(parts[index + 1], integer_types) and isinstance(pointer, dict):
pointer = pointer.get(part, [], force_set=True)
else:
pointer = pointer.get(part, force_set=True)
self.__ensure_list_capacity(pointer, parts[-1])
self.log.debug("Applying: [%s]=%s", parts[-1], value)
if isinstance(parts[-1], string_types) and parts[-1][0] == '^':
item = parts[-1][1:]
if isinstance(pointer, list):
item = int(item)
if -len(pointer) <= item < len(pointer):
del pointer[item]
else:
self.log.debug("No value to delete: %s", item)
elif isinstance(pointer, dict):
if item in pointer:
del pointer[item]
else:
self.log.debug("No value to delete: %s", item)
else:
raise ValueError("Cannot handle override %s in non-iterable type %s" % (item, pointer))
else:
parsed_value = self.__parse_override_value(value)
self.log.debug("Parsed override value: %r -> %r (%s)", value, parsed_value, type(parsed_value))
if isinstance(parsed_value, dict):
parsed_value = BetterDict.from_dict(parsed_value)
if isinstance(pointer, list) and parts[-1] < 0:
pointer.append(parsed_value)
else:
pointer[parts[-1]] = parsed_value
@staticmethod
def __parse_override_value(override):
try:
return yaml.safe_load(override)
except BaseException:
return override
def __ensure_list_capacity(self, pointer, part, next_part=None):
"""
Extend pointer list to hold additional item
:type pointer: list
:type part: int
"""
if isinstance(pointer, list) and isinstance(part, integer_types):
while len(pointer) <= part:
self.log.debug("Len %s less than %s", len(pointer), part)
if isinstance(next_part, integer_types):
pointer.append([])
else:
pointer.append(BetterDict())
class OptionParserWithAliases(OptionParser, object):
"""
Decorator that processes short opts as aliases
"""
def __init__(self,
usage=None,
option_list=None,
option_class=Option,
version=None,
conflict_handler="error",
description=None,
formatter=None,
add_help_option=True,
prog=None,
epilog=None):
super(OptionParserWithAliases, self).__init__(
usage=usage, option_list=option_list,
option_class=option_class, version=version,
conflict_handler=conflict_handler, description=description, formatter=formatter,
add_help_option=add_help_option, prog=prog, epilog=epilog)
self.aliases = []
def _process_short_opts(self, rargs, values):
if rargs[0].startswith('-') and len(rargs[0]) > 2:
self.aliases.append(rargs.pop(0)[1:])
else:
return OptionParser._process_short_opts(self, rargs, values)
def parse_args(self, args=None, values=None):
res = OptionParser.parse_args(self, args, values)
res[0].aliases = self.aliases
return res
def get_option_parser():
usage = "Usage: bzt [options] [configs] [-aliases]"
dsc = "BlazeMeter Taurus Tool v%s, the configuration-driven test running engine" % bzt.VERSION
parser = OptionParserWithAliases(usage=usage, description=dsc, prog="bzt")
parser.add_option('-l', '--log', action='store', default=None,
help="Log file location")
parser.add_option('-o', '--option', action='append',
help="Override option in config")
parser.add_option('-q', '--quiet', action='store_true',
help="Only errors and warnings printed to console")
parser.add_option('-v', '--verbose', action='store_true',
help="Prints all logging messages to console")
parser.add_option('-n', '--no-system-configs', action='store_true',
help="Skip system and user config files")
return parser
def signal_handler(sig, frame):
"""
required for non-tty python runs to interrupt
:param frame:
:param sig:
"""
del sig, frame
raise ManualShutdown()
def main():
"""
This function is used as entrypoint by setuptools
"""
parser = get_option_parser()
parsed_options, parsed_configs = parser.parse_args()
executor = CLI(parsed_options)
try:
code = executor.perform(parsed_configs)
except BaseException as exc_top:
logging.error("%s: %s", type(exc_top).__name__, exc_top)
logging.debug("Exception: %s", traceback.format_exc())
code = 1
exit(code)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
main()
| 1 | 15,395 | Fails if obj is list. Please fix! | Blazemeter-taurus | py |
@@ -28,5 +28,16 @@ class TestInstanceStatusResponseParsing(unittest.TestCase):
self.assertEqual(all_statuses.next_token, 'page-2')
+ def test_include_all_instances(self):
+ ec2 = EC2Connection(aws_access_key_id='aws_access_key_id',
+ aws_secret_access_key='aws_secret_access_key')
+ mock_response = mock.Mock()
+ mock_response.read.return_value = INSTANCE_STATUS_RESPONSE
+ mock_response.status = 200
+ ec2.make_request = mock.Mock(return_value=mock_response)
+ all_statuses = ec2.get_all_instance_status(include_all_instances=True)
+ self.assertEqual(all_statuses.next_token, 'page-2')
+
+
if __name__ == '__main__':
unittest.main() | 1 | #!/usr/bin/env python
from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase
import mock
from boto.ec2.connection import EC2Connection
INSTANCE_STATUS_RESPONSE = br"""<?xml version="1.0" encoding="UTF-8"?>
<DescribeInstanceStatusResponse xmlns="http://ec2.amazonaws.com/doc/2013-02-01/">
<requestId>3be1508e-c444-4fef-89cc-0b1223c4f02fEXAMPLE</requestId>
<nextToken>page-2</nextToken>
<instanceStatusSet />
</DescribeInstanceStatusResponse>
"""
class TestInstanceStatusResponseParsing(unittest.TestCase):
def test_next_token(self):
ec2 = EC2Connection(aws_access_key_id='aws_access_key_id',
aws_secret_access_key='aws_secret_access_key')
mock_response = mock.Mock()
mock_response.read.return_value = INSTANCE_STATUS_RESPONSE
mock_response.status = 200
ec2.make_request = mock.Mock(return_value=mock_response)
all_statuses = ec2.get_all_instance_status()
self.assertEqual(all_statuses.next_token, 'page-2')
if __name__ == '__main__':
unittest.main()
| 1 | 10,369 | Could you add an assertion to make sure the `IncludeAllInstances` parameter is actually set and passed to the request? | boto-boto | py |
@@ -79,7 +79,8 @@ def __get_analyzer_version(context, analyzer_config_map):
version = [analyzer_bin, u' --version']
try:
output = subprocess.check_output(shlex.split(' '.join(version)),
- env=check_env)
+ env=check_env,
+ universal_newlines=True)
versions[analyzer_bin] = output
except (subprocess.CalledProcessError, OSError) as oerr:
LOG.warning("Failed to get analyzer version: %s", | 1 | # -------------------------------------------------------------------------
# The CodeChecker Infrastructure
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
# -------------------------------------------------------------------------
"""
Prepare and start different analysis types
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from multiprocessing.managers import SyncManager
import os
import shlex
import shutil
import signal
import subprocess
import time
from codechecker_common.logger import get_logger
from codechecker_common.env import get_check_env
from . import analysis_manager, pre_analysis_manager
from .analyzers import analyzer_types
from .analyzers.clangsa.analyzer import ClangSA
from .analyzers.clangsa.statistics_collector import \
SpecialReturnValueCollector
from .analyzers.clangsa.statistics_collector import ReturnValueCollector
LOG = get_logger('analyzer')
def prepare_actions(actions, enabled_analyzers):
"""
Set the analyzer type for each buildaction.
Multiple actions if multiple source analyzers are set.
"""
res = []
for ea in enabled_analyzers:
for action in actions:
res.append(action.with_attr('analyzer_type', ea))
return res
def create_actions_map(actions, manager):
"""
Create a dict for the build actions which is shareable
safely between processes.
Key: (source_file, target)
Value: BuildAction
"""
result = manager.dict()
for act in actions:
key = act.source, act.target
if key in result:
LOG.debug("Multiple entires in compile database "
"with the same (source, target) pair: (%s, %s)",
act.source, act.target)
result[key] = act
return result
def __get_analyzer_version(context, analyzer_config_map):
"""
Get the path and the version of the analyzer binaries.
"""
check_env = get_check_env(context.path_env_extra,
context.ld_lib_path_extra)
# Get the analyzer binaries from the config_map which
# contains only the checked and available analyzers.
versions = {}
for _, analyzer_cfg in analyzer_config_map.items():
analyzer_bin = analyzer_cfg.analyzer_binary
version = [analyzer_bin, u' --version']
try:
output = subprocess.check_output(shlex.split(' '.join(version)),
env=check_env)
versions[analyzer_bin] = output
except (subprocess.CalledProcessError, OSError) as oerr:
LOG.warning("Failed to get analyzer version: %s",
' '.join(version))
LOG.warning(oerr.strerror)
return versions
def __mgr_init():
"""
This function is set for the SyncManager object which handles shared data
structures among the processes of the pool. Ignoring the SIGINT signal is
necessary in the manager object so it doesn't terminate before the
termination of the process pool.
"""
signal.signal(signal.SIGINT, signal.SIG_IGN)
def __get_statistics_data(args, manager):
statistics_data = None
if 'stats_enabled' in args and args.stats_enabled:
statistics_data = manager.dict({
'stats_out_dir': os.path.join(args.output_path, "stats")})
if 'stats_output' in args and args.stats_output:
statistics_data = manager.dict({'stats_out_dir':
args.stats_output})
if 'stats_min_sample_count' in args and statistics_data:
if args.stats_min_sample_count > 1:
statistics_data['stats_min_sample_count'] =\
args.stats_min_sample_count
else:
LOG.error("stats_min_sample_count"
"must be greater than 1.")
return None
if 'stats_relevance_threshold' in args and statistics_data:
if 1 > args.stats_relevance_threshold > 0:
statistics_data['stats_relevance_threshold'] =\
args.stats_relevance_threshold
else:
LOG.error("stats-relevance-threshold must be"
" greater than 0 and smaller than 1.")
return None
return statistics_data
def perform_analysis(args, skip_handler, context, actions, metadata):
"""
Perform static analysis via the given (or if not, all) analyzers,
in the given analysis context for the supplied build actions.
Additionally, insert statistical information into the metadata dict.
"""
analyzers = args.analyzers if 'analyzers' in args \
else analyzer_types.supported_analyzers
analyzers, _ = analyzer_types.check_supported_analyzers(
analyzers, context)
ctu_collect = False
ctu_analyze = False
ctu_dir = ''
if 'ctu_phases' in args:
ctu_dir = os.path.join(args.output_path, 'ctu-dir')
args.ctu_dir = ctu_dir
if ClangSA.ANALYZER_NAME not in analyzers:
LOG.error("CTU can only be used with the clang static analyzer.")
return
ctu_collect = args.ctu_phases[0]
ctu_analyze = args.ctu_phases[1]
if 'stats_enabled' in args and args.stats_enabled:
if ClangSA.ANALYZER_NAME not in analyzers:
LOG.debug("Statistics can only be used with "
"the Clang Static Analyzer.")
return
actions = prepare_actions(actions, analyzers)
config_map = analyzer_types.build_config_handlers(args, context, analyzers)
if 'stats_enabled' in args:
config_map[ClangSA.ANALYZER_NAME].set_checker_enabled(
SpecialReturnValueCollector.checker_analyze)
config_map[ClangSA.ANALYZER_NAME].set_checker_enabled(
ReturnValueCollector.checker_analyze)
# Save some metadata information.
versions = __get_analyzer_version(context, config_map)
metadata['versions'].update(versions)
metadata['checkers'] = {}
for analyzer in analyzers:
metadata['checkers'][analyzer] = {}
for check, data in config_map[analyzer].checks().items():
enabled, _ = data
metadata['checkers'][analyzer].update({check: enabled})
if ctu_collect:
shutil.rmtree(ctu_dir, ignore_errors=True)
elif ctu_analyze and not os.path.exists(ctu_dir):
LOG.error("CTU directory: '%s' does not exist.", ctu_dir)
return
start_time = time.time()
# Use Manager to create data objects which can be
# safely shared between processes.
manager = SyncManager()
manager.start(__mgr_init)
config_map = manager.dict(config_map)
actions_map = create_actions_map(actions, manager)
# Setting to not None value will enable statistical analysis features.
statistics_data = __get_statistics_data(args, manager)
if ctu_collect or statistics_data:
ctu_data = None
if ctu_collect or ctu_analyze:
ctu_data = manager.dict({'ctu_dir': ctu_dir,
'ctu_func_map_file': 'externalFnMap.txt',
'ctu_temp_fnmap_folder':
'tmpExternalFnMaps'})
pre_analyze = [a for a in actions
if a.analyzer_type == ClangSA.ANALYZER_NAME]
pre_analysis_manager.run_pre_analysis(pre_analyze,
context,
config_map,
args.jobs,
skip_handler,
ctu_data,
statistics_data,
manager)
if 'stats_output' in args and args.stats_output:
return
if 'stats_dir' in args and args.stats_dir:
statistics_data = manager.dict({'stats_out_dir': args.stats_dir})
ctu_reanalyze_on_failure = 'ctu_reanalyze_on_failure' in args and \
args.ctu_reanalyze_on_failure
if ctu_analyze or statistics_data or (not ctu_analyze and not ctu_collect):
LOG.info("Starting static analysis ...")
analysis_manager.start_workers(actions_map, actions, context,
config_map, args.jobs,
args.output_path,
skip_handler,
metadata,
'quiet' in args,
'capture_analysis_output' in args,
args.timeout if 'timeout' in args
else None,
ctu_reanalyze_on_failure,
statistics_data,
manager)
LOG.info("Analysis finished.")
LOG.info("To view results in the terminal use the "
"\"CodeChecker parse\" command.")
LOG.info("To store results use the \"CodeChecker store\" command.")
LOG.info("See --help and the user guide for further options about"
" parsing and storing the reports.")
LOG.info("----=================----")
end_time = time.time()
LOG.info("Analysis length: %s sec.", end_time - start_time)
metadata['timestamps'] = {'begin': start_time,
'end': end_time}
if ctu_collect and ctu_analyze:
shutil.rmtree(ctu_dir, ignore_errors=True)
manager.shutdown()
| 1 | 10,403 | The name of this argument is not too intuitive. The point is, these kind of subprocess calls will return `str`s in Python2 and 'byte`s in Python3. It would be a lot of work to make CodeChecker handle both `str` and `byte` everywhere. Using the `universal_newlines` argument, we can force Python3 to return text rather then bytes. | Ericsson-codechecker | c |
@@ -63,7 +63,7 @@ func toProtoDomainReplicationConfiguration(in *shared.DomainReplicationConfigura
}
return &common.DomainReplicationConfiguration{
ActiveClusterName: in.GetActiveClusterName(),
- Clusters: toProtoClusterReplicationConfigurations(in.Clusters),
+ Clusters: toProtoClusterReplicationConfigurations(in.GetClusters()),
}
}
| 1 | // Copyright (c) 2019 Temporal 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 adapter
import (
"github.com/temporalio/temporal-proto/common"
"github.com/temporalio/temporal-proto/enums"
"github.com/temporalio/temporal/.gen/go/replicator"
"github.com/temporalio/temporal/.gen/go/shared"
)
func toProtoBool(in *bool) *common.BoolValue {
if in == nil {
return nil
}
return &common.BoolValue{Value: *in}
}
func toThriftBool(in *common.BoolValue) *bool {
if in == nil {
return nil
}
return &in.Value
}
func toProtoDomainInfo(in *shared.DomainInfo) *common.DomainInfo {
if in == nil {
return nil
}
return &common.DomainInfo{
Name: in.GetName(),
Status: enums.DomainStatus(in.GetStatus()),
Description: in.GetDescription(),
OwnerEmail: in.GetOwnerEmail(),
Data: in.GetData(),
Uuid: in.GetUUID(),
}
}
func toProtoDomainReplicationConfiguration(in *shared.DomainReplicationConfiguration) *common.DomainReplicationConfiguration {
if in == nil {
return nil
}
return &common.DomainReplicationConfiguration{
ActiveClusterName: in.GetActiveClusterName(),
Clusters: toProtoClusterReplicationConfigurations(in.Clusters),
}
}
func toProtoDomainConfiguration(in *shared.DomainConfiguration) *common.DomainConfiguration {
if in == nil {
return nil
}
return &common.DomainConfiguration{
WorkflowExecutionRetentionPeriodInDays: in.GetWorkflowExecutionRetentionPeriodInDays(),
EmitMetric: toProtoBool(in.EmitMetric),
BadBinaries: toProtoBadBinaries(in.BadBinaries),
HistoryArchivalStatus: toProtoArchivalStatus(in.HistoryArchivalStatus),
HistoryArchivalURI: in.GetVisibilityArchivalURI(),
VisibilityArchivalStatus: toProtoArchivalStatus(in.VisibilityArchivalStatus),
VisibilityArchivalURI: in.GetVisibilityArchivalURI(),
}
}
func toProtoBadBinaries(in *shared.BadBinaries) *common.BadBinaries {
if in == nil {
return nil
}
ret := make(map[string]*common.BadBinaryInfo, len(in.Binaries))
for key, value := range in.Binaries {
ret[key] = toProtoBadBinaryInfo(value)
}
return &common.BadBinaries{
Binaries: ret,
}
}
func toProtoBadBinaryInfo(in *shared.BadBinaryInfo) *common.BadBinaryInfo {
if in == nil {
return nil
}
return &common.BadBinaryInfo{
Reason: in.GetReason(),
Operator: in.GetOperator(),
CreatedTimeNano: in.GetCreatedTimeNano(),
}
}
func toThriftClusterReplicationConfigurations(in []*common.ClusterReplicationConfiguration) []*shared.ClusterReplicationConfiguration {
var ret []*shared.ClusterReplicationConfiguration
for _, cluster := range in {
ret = append(ret, &shared.ClusterReplicationConfiguration{ClusterName: &cluster.ClusterName})
}
return ret
}
func toProtoClusterReplicationConfigurations(in []*shared.ClusterReplicationConfiguration) []*common.ClusterReplicationConfiguration {
var ret []*common.ClusterReplicationConfiguration
for _, cluster := range in {
ret = append(ret, &common.ClusterReplicationConfiguration{ClusterName: *cluster.ClusterName})
}
return ret
}
func toThriftUpdateDomainInfo(in *common.UpdateDomainInfo) *shared.UpdateDomainInfo {
if in == nil {
return nil
}
return &shared.UpdateDomainInfo{
Description: &in.Description,
OwnerEmail: &in.OwnerEmail,
Data: in.Data,
}
}
func toThriftDomainConfiguration(in *common.DomainConfiguration) *shared.DomainConfiguration {
if in == nil {
return nil
}
return &shared.DomainConfiguration{
WorkflowExecutionRetentionPeriodInDays: &in.WorkflowExecutionRetentionPeriodInDays,
EmitMetric: toThriftBool(in.EmitMetric),
BadBinaries: toThriftBadBinaries(in.BadBinaries),
HistoryArchivalStatus: toThriftArchivalStatus(in.HistoryArchivalStatus),
HistoryArchivalURI: &in.HistoryArchivalURI,
VisibilityArchivalStatus: toThriftArchivalStatus(in.VisibilityArchivalStatus),
VisibilityArchivalURI: &in.VisibilityArchivalURI,
}
}
func toThriftDomainReplicationConfiguration(in *common.DomainReplicationConfiguration) *shared.DomainReplicationConfiguration {
if in == nil {
return nil
}
return &shared.DomainReplicationConfiguration{
ActiveClusterName: &in.ActiveClusterName,
Clusters: toThriftClusterReplicationConfigurations(in.Clusters),
}
}
func toThriftBadBinaries(in *common.BadBinaries) *shared.BadBinaries {
if in == nil {
return nil
}
ret := make(map[string]*shared.BadBinaryInfo, len(in.Binaries))
for key, value := range in.Binaries {
ret[key] = toThriftBadBinaryInfo(value)
}
return &shared.BadBinaries{
Binaries: ret,
}
}
func toThriftBadBinaryInfo(in *common.BadBinaryInfo) *shared.BadBinaryInfo {
if in == nil {
return nil
}
return &shared.BadBinaryInfo{
Reason: &in.Reason,
Operator: &in.Operator,
CreatedTimeNano: &in.CreatedTimeNano,
}
}
func toThriftWorkflowType(in *common.WorkflowType) *shared.WorkflowType {
if in == nil {
return nil
}
return &shared.WorkflowType{
Name: &in.Name,
}
}
func toThriftTaskList(in *common.TaskList) *shared.TaskList {
if in == nil {
return nil
}
return &shared.TaskList{
Name: &in.Name,
Kind: toThriftTaskListKind(in.Kind),
}
}
func toThriftRetryPolicy(in *common.RetryPolicy) *shared.RetryPolicy {
if in == nil {
return nil
}
return &shared.RetryPolicy{
InitialIntervalInSeconds: &in.InitialIntervalInSeconds,
BackoffCoefficient: &in.BackoffCoefficient,
MaximumIntervalInSeconds: &in.MaximumIntervalInSeconds,
MaximumAttempts: &in.MaximumAttempts,
NonRetriableErrorReasons: in.NonRetriableErrorReasons,
ExpirationIntervalInSeconds: &in.ExpirationIntervalInSeconds,
}
}
func toThriftMemo(in *common.Memo) *shared.Memo {
if in == nil {
return nil
}
return &shared.Memo{
Fields: in.Fields,
}
}
func toThriftHeader(in *common.Header) *shared.Header {
if in == nil {
return nil
}
return &shared.Header{
Fields: in.Fields,
}
}
func toThriftSearchAttributes(in *common.SearchAttributes) *shared.SearchAttributes {
if in == nil {
return nil
}
return &shared.SearchAttributes{
IndexedFields: in.IndexedFields,
}
}
func toThriftWorkflowExecution(in *common.WorkflowExecution) *shared.WorkflowExecution {
if in == nil {
return nil
}
return &shared.WorkflowExecution{
WorkflowId: &in.WorkflowId,
RunId: &in.RunId,
}
}
func toProtoWorkflowType(in *shared.WorkflowType) *common.WorkflowType {
if in == nil {
return nil
}
return &common.WorkflowType{
Name: in.GetName(),
}
}
func toProtoWorkflowExecution(in *shared.WorkflowExecution) *common.WorkflowExecution {
if in == nil {
return nil
}
return &common.WorkflowExecution{
WorkflowId: in.GetWorkflowId(),
RunId: in.GetRunId(),
}
}
func toProtoTaskList(in *shared.TaskList) *common.TaskList {
if in == nil {
return nil
}
return &common.TaskList{
Name: in.GetName(),
Kind: enums.TaskListKind(in.GetKind()),
}
}
func toProtoRetryPolicy(in *shared.RetryPolicy) *common.RetryPolicy {
if in == nil {
return nil
}
return &common.RetryPolicy{
InitialIntervalInSeconds: in.GetInitialIntervalInSeconds(),
BackoffCoefficient: in.GetBackoffCoefficient(),
MaximumIntervalInSeconds: in.GetMaximumIntervalInSeconds(),
MaximumAttempts: in.GetMaximumAttempts(),
NonRetriableErrorReasons: in.GetNonRetriableErrorReasons(),
ExpirationIntervalInSeconds: in.GetExpirationIntervalInSeconds(),
}
}
func toProtoMemo(in *shared.Memo) *common.Memo {
if in == nil {
return nil
}
return &common.Memo{
Fields: in.GetFields(),
}
}
func toProtoSearchAttributes(in *shared.SearchAttributes) *common.SearchAttributes {
if in == nil {
return nil
}
return &common.SearchAttributes{
IndexedFields: in.GetIndexedFields(),
}
}
func toProtoResetPoints(in *shared.ResetPoints) *common.ResetPoints {
if in == nil {
return nil
}
var points []*common.ResetPointInfo
for _, point := range in.GetPoints() {
points = append(points, toProtoResetPointInfo(point))
}
return &common.ResetPoints{
Points: points,
}
}
func toProtoHeader(in *shared.Header) *common.Header {
if in == nil {
return nil
}
return &common.Header{
Fields: in.GetFields(),
}
}
func toProtoActivityType(in *shared.ActivityType) *common.ActivityType {
if in == nil {
return nil
}
return &common.ActivityType{
Name: in.GetName(),
}
}
func toProtoResetPointInfo(in *shared.ResetPointInfo) *common.ResetPointInfo {
if in == nil {
return nil
}
return &common.ResetPointInfo{
BinaryChecksum: in.GetBinaryChecksum(),
RunId: in.GetRunId(),
FirstDecisionCompletedId: in.GetFirstDecisionCompletedId(),
CreatedTimeNano: in.GetCreatedTimeNano(),
ExpiringTimeNano: in.GetExpiringTimeNano(),
Resettable: in.GetResettable(),
}
}
func toProtoWorkflowExecutionInfo(in *shared.WorkflowExecutionInfo) *common.WorkflowExecutionInfo {
if in == nil {
return nil
}
return &common.WorkflowExecutionInfo{
Execution: toProtoWorkflowExecution(in.GetExecution()),
Type: toProtoWorkflowType(in.GetType()),
StartTime: in.GetStartTime(),
CloseTime: in.GetCloseTime(),
CloseStatus: enums.WorkflowExecutionCloseStatus(in.GetCloseStatus()),
HistoryLength: in.GetHistoryLength(),
ParentDomainId: in.GetParentDomainId(),
ParentExecution: toProtoWorkflowExecution(in.GetParentExecution()),
ExecutionTime: in.GetExecutionTime(),
Memo: toProtoMemo(in.GetMemo()),
SearchAttributes: toProtoSearchAttributes(in.GetSearchAttributes()),
AutoResetPoints: toProtoResetPoints(in.GetAutoResetPoints()),
}
}
func toThriftStartTimeFilter(in *common.StartTimeFilter) *shared.StartTimeFilter {
if in == nil {
return nil
}
return &shared.StartTimeFilter{
EarliestTime: &in.EarliestTime,
LatestTime: &in.LatestTime,
}
}
func toThriftWorkflowExecutionFilter(in *common.WorkflowExecutionFilter) *shared.WorkflowExecutionFilter {
if in == nil {
return nil
}
return &shared.WorkflowExecutionFilter{
WorkflowId: &in.WorkflowId,
RunId: &in.RunId,
}
}
func toThriftWorkflowTypeFilter(in *common.WorkflowTypeFilter) *shared.WorkflowTypeFilter {
if in == nil {
return nil
}
return &shared.WorkflowTypeFilter{
Name: &in.Name,
}
}
func toProtoWorkflowExecutionInfos(in []*shared.WorkflowExecutionInfo) []*common.WorkflowExecutionInfo {
if in == nil {
return nil
}
var executions []*common.WorkflowExecutionInfo
for _, execution := range in {
executions = append(executions, toProtoWorkflowExecutionInfo(execution))
}
return executions
}
func toProtoWorkflowExecutionConfiguration(in *shared.WorkflowExecutionConfiguration) *common.WorkflowExecutionConfiguration {
if in == nil {
return nil
}
return &common.WorkflowExecutionConfiguration{
TaskList: toProtoTaskList(in.GetTaskList()),
ExecutionStartToCloseTimeoutSeconds: in.GetExecutionStartToCloseTimeoutSeconds(),
TaskStartToCloseTimeoutSeconds: in.GetTaskStartToCloseTimeoutSeconds(),
}
}
func toProtoPendingActivityInfos(in []*shared.PendingActivityInfo) []*common.PendingActivityInfo {
if in == nil {
return nil
}
var infos []*common.PendingActivityInfo
for _, info := range in {
infos = append(infos, toProtoPendingActivityInfo(info))
}
return infos
}
func toProtoPendingChildExecutionInfos(in []*shared.PendingChildExecutionInfo) []*common.PendingChildExecutionInfo {
if in == nil {
return nil
}
var infos []*common.PendingChildExecutionInfo
for _, info := range in {
infos = append(infos, toProtoPendingChildExecutionInfo(info))
}
return infos
}
func toProtoPendingActivityInfo(in *shared.PendingActivityInfo) *common.PendingActivityInfo {
if in == nil {
return nil
}
return &common.PendingActivityInfo{
ActivityID: in.GetActivityID(),
ActivityType: toProtoActivityType(in.GetActivityType()),
State: enums.PendingActivityState(in.GetState()),
HeartbeatDetails: in.GetHeartbeatDetails(),
LastHeartbeatTimestamp: in.GetLastHeartbeatTimestamp(),
LastStartedTimestamp: in.GetLastStartedTimestamp(),
Attempt: in.GetAttempt(),
MaximumAttempts: in.GetMaximumAttempts(),
ScheduledTimestamp: in.GetScheduledTimestamp(),
ExpirationTimestamp: in.GetExpirationTimestamp(),
LastFailureReason: in.GetLastFailureReason(),
LastWorkerIdentity: in.GetLastWorkerIdentity(),
LastFailureDetails: in.GetLastFailureDetails(),
}
}
func toProtoPendingChildExecutionInfo(in *shared.PendingChildExecutionInfo) *common.PendingChildExecutionInfo {
if in == nil {
return nil
}
return &common.PendingChildExecutionInfo{
WorkflowID: in.GetWorkflowID(),
RunID: in.GetRunID(),
WorkflowTypName: in.GetWorkflowTypName(),
InitiatedID: in.GetInitiatedID(),
ParentClosePolicy: enums.ParentClosePolicy(in.GetParentClosePolicy()),
}
}
func toProtoWorkflowQuery(in *shared.WorkflowQuery) *common.WorkflowQuery {
if in == nil {
return nil
}
return &common.WorkflowQuery{
QueryType: in.GetQueryType(),
QueryArgs: in.GetQueryArgs(),
}
}
func toProtoWorkflowQueries(in map[string]*shared.WorkflowQuery) map[string]*common.WorkflowQuery {
if in == nil {
return nil
}
ret := make(map[string]*common.WorkflowQuery, len(in))
for k, v := range in {
ret[k] = toProtoWorkflowQuery(v)
}
return ret
}
// toThriftActivityType ...
func toThriftActivityType(in *common.ActivityType) *shared.ActivityType {
if in == nil {
return nil
}
return &shared.ActivityType{
Name: &in.Name,
}
}
// toThriftStickyExecutionAttributes ...
func toThriftStickyExecutionAttributes(in *common.StickyExecutionAttributes) *shared.StickyExecutionAttributes {
if in == nil {
return nil
}
return &shared.StickyExecutionAttributes{
WorkerTaskList: toThriftTaskList(in.WorkerTaskList),
ScheduleToStartTimeoutSeconds: &in.ScheduleToStartTimeoutSeconds,
}
}
func toThriftWorkflowQueryResults(in map[string]*common.WorkflowQueryResult) map[string]*shared.WorkflowQueryResult {
if in == nil {
return nil
}
ret := make(map[string]*shared.WorkflowQueryResult, len(in))
for k, v := range in {
ret[k] = toThriftWorkflowQueryResult(v)
}
return ret
}
// toThriftWorkflowQueryResult ...
func toThriftWorkflowQueryResult(in *common.WorkflowQueryResult) *shared.WorkflowQueryResult {
if in == nil {
return nil
}
return &shared.WorkflowQueryResult{
ResultType: toThriftQueryResultType(in.ResultType),
Answer: in.Answer,
ErrorMessage: &in.ErrorMessage,
}
}
// toThriftTaskListMetadata ...
func toThriftTaskListMetadata(in *common.TaskListMetadata) *shared.TaskListMetadata {
if in == nil {
return nil
}
return &shared.TaskListMetadata{
MaxTasksPerSecond: &in.MaxTasksPerSecond,
}
}
// toThriftWorkflowQuery ...
func toThriftWorkflowQuery(in *common.WorkflowQuery) *shared.WorkflowQuery {
if in == nil {
return nil
}
return &shared.WorkflowQuery{
QueryType: &in.QueryType,
QueryArgs: in.QueryArgs,
}
}
// toThriftReplicationToken ...
func toThriftReplicationToken(in *common.ReplicationToken) *replicator.ReplicationToken {
if in == nil {
return nil
}
return &replicator.ReplicationToken{
ShardID: &in.ShardID,
LastRetrivedMessageId: &in.LastRetrivedMessageId,
LastProcessedMessageId: &in.LastProcessedMessageId,
}
}
func toThriftReplicationTokens(in []*common.ReplicationToken) []*replicator.ReplicationToken {
if in == nil {
return nil
}
var ret []*replicator.ReplicationToken
for _, item := range in {
ret = append(ret, toThriftReplicationToken(item))
}
return ret
}
// toThriftDataBlob ...
func toThriftDataBlob(in *common.DataBlob) *shared.DataBlob {
if in == nil {
return nil
}
return &shared.DataBlob{
EncodingType: toThriftEncodingType(in.EncodingType),
Data: in.Data,
}
}
// toProtoQueryRejected ...
func toProtoQueryRejected(in *shared.QueryRejected) *common.QueryRejected {
if in == nil {
return nil
}
return &common.QueryRejected{
CloseStatus: enums.WorkflowExecutionCloseStatus(in.GetCloseStatus()),
}
}
// toProtoPollerInfo ...
func toProtoPollerInfo(in *shared.PollerInfo) *common.PollerInfo {
if in == nil {
return nil
}
return &common.PollerInfo{
LastAccessTime: in.GetLastAccessTime(),
Identity: in.GetIdentity(),
RatePerSecond: in.GetRatePerSecond(),
}
}
func toProtoPollerInfos(in []*shared.PollerInfo) []*common.PollerInfo {
if in == nil {
return nil
}
var ret []*common.PollerInfo
for _, item := range in {
ret = append(ret, toProtoPollerInfo(item))
}
return ret
}
// toProtoTaskListStatus ...
func toProtoTaskListStatus(in *shared.TaskListStatus) *common.TaskListStatus {
if in == nil {
return nil
}
return &common.TaskListStatus{
BacklogCountHint: in.GetBacklogCountHint(),
ReadLevel: in.GetReadLevel(),
AckLevel: in.GetAckLevel(),
RatePerSecond: in.GetRatePerSecond(),
TaskIDBlock: toProtoTaskIDBlock(in.GetTaskIDBlock()),
}
}
// toProtoTaskIDBlock ...
func toProtoTaskIDBlock(in *shared.TaskIDBlock) *common.TaskIDBlock {
if in == nil {
return nil
}
return &common.TaskIDBlock{
StartID: in.GetStartID(),
EndID: in.GetEndID(),
}
}
// toProtoReplicationMessages ...
func toProtoReplicationMessages(in *replicator.ReplicationMessages) *common.ReplicationMessages {
if in == nil {
return nil
}
return &common.ReplicationMessages{
ReplicationTasks: toProtoReplicationTasks(in.GetReplicationTasks()),
LastRetrivedMessageId: in.GetLastRetrivedMessageId(),
HasMore: in.GetHasMore(),
}
}
func toProtoReplicationTasks(in []*replicator.ReplicationTask) []*common.ReplicationTask {
if in == nil {
return nil
}
var ret []*common.ReplicationTask
for _, item := range in {
ret = append(ret, toProtoReplicationTask(item))
}
return ret
}
// toProtoReplicationTask ...
func toProtoReplicationTask(in *replicator.ReplicationTask) *common.ReplicationTask {
if in == nil {
return nil
}
ret := &common.ReplicationTask{
TaskType: enums.ReplicationTaskType(in.GetTaskType()),
SourceTaskId: in.GetSourceTaskId(),
}
switch ret.TaskType {
case enums.ReplicationTaskTypeDomain:
ret.Attributes = &common.ReplicationTask_DomainTaskAttributes{DomainTaskAttributes: toProtoDomainTaskAttributes(in.GetDomainTaskAttributes())}
case enums.ReplicationTaskTypeHistory:
ret.Attributes = &common.ReplicationTask_HistoryTaskAttributes{HistoryTaskAttributes: toProtoHistoryTaskAttributes(in.GetHistoryTaskAttributes())}
case enums.ReplicationTaskTypeSyncShardStatus:
ret.Attributes = &common.ReplicationTask_SyncShardStatusTaskAttributes{SyncShardStatusTaskAttributes: toProtoSyncShardStatusTaskAttributes(in.GetSyncShardStatusTaskAttributes())}
case enums.ReplicationTaskTypeSyncActivity:
ret.Attributes = &common.ReplicationTask_SyncActicvityTaskAttributes{SyncActicvityTaskAttributes: toProtoSyncActicvityTaskAttributes(in.GetSyncActicvityTaskAttributes())}
case enums.ReplicationTaskTypeHistoryMetadata:
ret.Attributes = &common.ReplicationTask_HistoryMetadataTaskAttributes{HistoryMetadataTaskAttributes: toProtoHistoryMetadataTaskAttributes(in.GetHistoryMetadataTaskAttributes())}
case enums.ReplicationTaskTypeHistoryV2:
ret.Attributes = &common.ReplicationTask_HistoryTaskV2Attributes{HistoryTaskV2Attributes: toProtoHistoryTaskV2Attributes(in.GetHistoryTaskV2Attributes())}
}
return ret
}
// toProtoDomainTaskAttributes ...
func toProtoDomainTaskAttributes(in *replicator.DomainTaskAttributes) *common.DomainTaskAttributes {
if in == nil {
return nil
}
return &common.DomainTaskAttributes{
DomainOperation: enums.DomainOperation(in.GetDomainOperation()),
Id: in.GetID(),
Info: toProtoDomainInfo(in.GetInfo()),
Config: toProtoDomainConfiguration(in.GetConfig()),
ReplicationConfig: toProtoDomainReplicationConfiguration(in.GetReplicationConfig()),
ConfigVersion: in.GetConfigVersion(),
FailoverVersion: in.GetFailoverVersion(),
}
}
// toProtoHistoryTaskAttributes ...
func toProtoHistoryTaskAttributes(in *replicator.HistoryTaskAttributes) *common.HistoryTaskAttributes {
if in == nil {
return nil
}
return &common.HistoryTaskAttributes{
TargetClusters: in.GetTargetClusters(),
DomainId: in.GetDomainId(),
WorkflowId: in.GetWorkflowId(),
RunId: in.GetRunId(),
FirstEventId: in.GetFirstEventId(),
NextEventId: in.GetNextEventId(),
Version: in.GetVersion(),
ReplicationInfo: toProtoReplicationInfos(in.GetReplicationInfo()),
History: toProtoHistory(in.GetHistory()),
NewRunHistory: toProtoHistory(in.GetNewRunHistory()),
EventStoreVersion: in.GetEventStoreVersion(),
NewRunEventStoreVersion: in.GetNewRunEventStoreVersion(),
ResetWorkflow: in.GetResetWorkflow(),
NewRunNDC: in.GetNewRunNDC(),
}
}
func toProtoReplicationInfos(in map[string]*shared.ReplicationInfo) map[string]*common.ReplicationInfo {
if in == nil {
return nil
}
ret := make(map[string]*common.ReplicationInfo, len(in))
for k, v := range in {
ret[k] = toProtoReplicationInfo(v)
}
return ret
}
// toProtoReplicationInfo ...
func toProtoReplicationInfo(in *shared.ReplicationInfo) *common.ReplicationInfo {
if in == nil {
return nil
}
return &common.ReplicationInfo{
Version: in.GetVersion(),
LastEventId: in.GetLastEventId(),
}
}
// toProtoHistoryMetadataTaskAttributes ...
func toProtoHistoryMetadataTaskAttributes(in *replicator.HistoryMetadataTaskAttributes) *common.HistoryMetadataTaskAttributes {
if in == nil {
return nil
}
return &common.HistoryMetadataTaskAttributes{
TargetClusters: in.GetTargetClusters(),
DomainId: in.GetDomainId(),
WorkflowId: in.GetWorkflowId(),
RunId: in.GetRunId(),
FirstEventId: in.GetFirstEventId(),
NextEventId: in.GetNextEventId(),
}
}
// toProtoSyncShardStatusTaskAttributes ...
func toProtoSyncShardStatusTaskAttributes(in *replicator.SyncShardStatusTaskAttributes) *common.SyncShardStatusTaskAttributes {
if in == nil {
return nil
}
return &common.SyncShardStatusTaskAttributes{
SourceCluster: in.GetSourceCluster(),
ShardId: in.GetShardId(),
Timestamp: in.GetTimestamp(),
}
}
// toProtoSyncActicvityTaskAttributes ...
func toProtoSyncActicvityTaskAttributes(in *replicator.SyncActicvityTaskAttributes) *common.SyncActicvityTaskAttributes {
if in == nil {
return nil
}
return &common.SyncActicvityTaskAttributes{
DomainId: in.GetDomainId(),
WorkflowId: in.GetWorkflowId(),
RunId: in.GetRunId(),
Version: in.GetVersion(),
ScheduledId: in.GetScheduledId(),
ScheduledTime: in.GetScheduledTime(),
StartedId: in.GetStartedId(),
StartedTime: in.GetStartedTime(),
LastHeartbeatTime: in.GetLastHeartbeatTime(),
Details: in.GetDetails(),
Attempt: in.GetAttempt(),
LastFailureReason: in.GetLastFailureReason(),
LastWorkerIdentity: in.GetLastWorkerIdentity(),
LastFailureDetails: in.GetLastFailureDetails(),
VersionHistory: toProtoVersionHistory(in.GetVersionHistory()),
}
}
// toProtoVersionHistoryItem ...
func toProtoVersionHistoryItem(in *shared.VersionHistoryItem) *common.VersionHistoryItem {
if in == nil {
return nil
}
return &common.VersionHistoryItem{
EventID: in.GetEventID(),
Version: in.GetVersion(),
}
}
// toProtoVersionHistory ...
func toProtoVersionHistory(in *shared.VersionHistory) *common.VersionHistory {
if in == nil {
return nil
}
return &common.VersionHistory{
BranchToken: in.GetBranchToken(),
Items: toProtoVersionHistoryItems(in.GetItems()),
}
}
func toProtoVersionHistoryItems(in []*shared.VersionHistoryItem) []*common.VersionHistoryItem {
if in == nil {
return nil
}
var ret []*common.VersionHistoryItem
for _, item := range in {
ret = append(ret, toProtoVersionHistoryItem(item))
}
return ret
}
// toProtoHistoryTaskV2Attributes ...
func toProtoHistoryTaskV2Attributes(in *replicator.HistoryTaskV2Attributes) *common.HistoryTaskV2Attributes {
if in == nil {
return nil
}
return &common.HistoryTaskV2Attributes{
TaskId: in.GetTaskId(),
DomainId: in.GetDomainId(),
WorkflowId: in.GetWorkflowId(),
RunId: in.GetRunId(),
VersionHistoryItems: toProtoVersionHistoryItems(in.GetVersionHistoryItems()),
Events: toProtoDataBlob(in.GetEvents()),
NewRunEvents: toProtoDataBlob(in.GetNewRunEvents()),
}
}
func toProtoDataBlob(in *shared.DataBlob) *common.DataBlob {
if in == nil {
return nil
}
return &common.DataBlob{
EncodingType: enums.EncodingType(in.GetEncodingType()),
Data: in.GetData(),
}
}
func toProtoIndexedValueTypes(in map[string]shared.IndexedValueType) map[string]enums.IndexedValueType {
if in == nil {
return nil
}
ret := make(map[string]enums.IndexedValueType, len(in))
for k, v := range in {
ret[k] = enums.IndexedValueType(v)
}
return ret
}
func toProtoReplicationMessagess(in map[int32]*replicator.ReplicationMessages) map[int32]*common.ReplicationMessages {
if in == nil {
return nil
}
ret := make(map[int32]*common.ReplicationMessages, len(in))
for k, v := range in {
ret[k] = toProtoReplicationMessages(v)
}
return ret
}
| 1 | 9,129 | These `Get`s are just cosmetic changes for consistency. | temporalio-temporal | go |
@@ -55,13 +55,7 @@ def test_read_yaml(tmpdir):
assert parsed_string == parsed_path_obj
-def test_yaml_has_comments(tmpdir):
- no_comments_yaml = """blah: foo\nfizz: boop"""
-
- assert not util.yaml_has_comments(util.read_yaml(no_comments_yaml))
- assert util.yaml_has_comments(util.read_yaml(TEST_YAML))
-
-
+@pytest.mark.skip(reason="Broken due to yaml safe load")
def test_read_yaml_exec_flaw(capfd):
# We don't execute anything remote, but someone could give a bad build.yml..
util.read_yaml("""!!python/object/apply:os.system\nargs: ['echo arbitrary code execution!']""") | 1 | # -*- coding: utf-8 -*-
""" Testing for util.py """
### Python imports
import pathlib
### Third Party imports
import pytest
### Project imports
from quilt3 import util
### Constants
TEST_YAML = """
# This is an arbitrary comment solely for the purposes of testing.
c: the speed of light
d: a programming language that almost mattered
# Another arbitrary comment.
e: a not-so-hip MC from a relatively unknown nightclub # do you like cats?
"""
### Code
def test_write_yaml(tmpdir):
fname = tmpdir / 'some_file.yml'
util.write_yaml({'testing': 'foo'}, fname)
assert fname.read_text('utf-8') == 'testing: foo\n'
util.write_yaml({'testing': 'bar'}, fname, keep_backup=True)
fnames = [name for name in tmpdir.listdir() if name.basename.startswith('some_file')]
assert len(fnames) == 2
fname2 = max(fnames, key=lambda x: len(x.basename)) # backup name is longer
assert fname2.read_text('utf-8') == 'testing: foo\n'
assert fname.read_text('utf-8') == 'testing: bar\n'
def test_read_yaml(tmpdir):
# Read a string
parsed_string = util.read_yaml(TEST_YAML)
fname = tmpdir / 'test_read_yaml.yml'
util.write_yaml(parsed_string, fname)
# Read file descriptor..
with fname.open('r') as f:
parsed_file = util.read_yaml(f)
assert parsed_file == parsed_string
# Read Path object
parsed_path_obj = util.read_yaml(pathlib.Path(fname))
assert parsed_string == parsed_path_obj
def test_yaml_has_comments(tmpdir):
no_comments_yaml = """blah: foo\nfizz: boop"""
assert not util.yaml_has_comments(util.read_yaml(no_comments_yaml))
assert util.yaml_has_comments(util.read_yaml(TEST_YAML))
def test_read_yaml_exec_flaw(capfd):
# We don't execute anything remote, but someone could give a bad build.yml..
util.read_yaml("""!!python/object/apply:os.system\nargs: ['echo arbitrary code execution!']""")
out, err = capfd.readouterr()
assert not out
assert not err
def test_validate_url():
with pytest.raises(util.QuiltException, match='Port must be a number'):
util.validate_url('http://foo:bar')
with pytest.raises(util.QuiltException, match='Requires at least scheme and host'):
util.validate_url('blah')
| 1 | 18,359 | We should never skip unit tests, but instead fix them. Look at `pytest.raises` for cases where we expect an exception. | quiltdata-quilt | py |
@@ -79,11 +79,15 @@ namespace Microsoft.DotNet.Build.Tasks.Feed
public async Task<bool> PushItemsToFeedAsync(IEnumerable<string> items, bool allowOverwrite)
{
Log.LogMessage(MessageImportance.Low, $"START pushing items to feed");
- Random rnd = new Random();
- try
+ if (!items.Any())
{
+ Log.LogMessage("No items to push found in the items list.");
+ return true;
+ }
+ try
+ {
bool result = await PushAsync(items.ToList(), allowOverwrite);
return result;
} | 1 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.DotNet.Build.CloudTestTasks;
using Microsoft.WindowsAzure.Storage;
using Newtonsoft.Json.Linq;
using Sleet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MSBuild = Microsoft.Build.Utilities;
using CloudTestTasks = Microsoft.DotNet.Build.CloudTestTasks;
namespace Microsoft.DotNet.Build.Tasks.Feed
{
sealed class BlobFeedAction
{
private MSBuild.TaskLoggingHelper Log;
private static readonly CancellationTokenSource TokenSource = new CancellationTokenSource();
private static readonly CancellationToken CancellationToken = TokenSource.Token;
private const string feedRegex = @"(?<feedurl>https:\/\/(?<accountname>[^\.-]+)(?<domain>[^\/]*)\/((?<token>[a-zA-Z0-9+\/]*?\/\d{4}-\d{2}-\d{2})\/)?(?<containername>[^\/]+)\/(?<relativepath>.*\/)?)index\.json";
private string feedUrl;
private SleetSource source;
private bool hasToken = false;
public BlobFeed feed;
public BlobFeedAction(string expectedFeedUrl, string accountKey, MSBuild.TaskLoggingHelper Log)
{
this.Log = Log;
Match m = Regex.Match(expectedFeedUrl, feedRegex);
if (m.Success)
{
string accountName = m.Groups["accountname"].Value;
string containerName = m.Groups["containername"].Value;
string relativePath = m.Groups["relativepath"].Value;
feed = new BlobFeed(accountName, accountKey, containerName, relativePath, Log);
feedUrl = m.Groups["feedurl"].Value;
hasToken = !string.IsNullOrEmpty(m.Groups["token"].Value);
source = new SleetSource
{
Name = feed.ContainerName,
Type = "azure",
Path = feedUrl,
Container = feed.ContainerName,
FeedSubPath = feed.RelativePath,
ConnectionString = $"DefaultEndpointsProtocol=https;AccountName={feed.AccountName};AccountKey={feed.AccountKey};EndpointSuffix=core.windows.net"
};
}
else
{
throw new Exception("Unable to parse expected feed. Please check ExpectedFeedUrl.");
}
}
public async Task<bool> PushToFeed(IEnumerable<string> items, bool allowOverwrite = false)
{
if (IsSanityChecked(items))
{
if (CancellationToken.IsCancellationRequested)
{
Log.LogError("Task PushToFeed cancelled");
CancellationToken.ThrowIfCancellationRequested();
}
await PushItemsToFeedAsync(items, allowOverwrite);
}
return !Log.HasLoggedErrors;
}
public async Task<bool> PushItemsToFeedAsync(IEnumerable<string> items, bool allowOverwrite)
{
Log.LogMessage(MessageImportance.Low, $"START pushing items to feed");
Random rnd = new Random();
try
{
bool result = await PushAsync(items.ToList(), allowOverwrite);
return result;
}
catch (Exception e)
{
Log.LogErrorFromException(e);
}
return !Log.HasLoggedErrors;
}
public async Task UploadAssets(ITaskItem item, SemaphoreSlim clientThrottle, bool allowOverwrite = false)
{
string relativeBlobPath = item.GetMetadata("RelativeBlobPath");
if (string.IsNullOrEmpty(relativeBlobPath))
{
string fileName = Path.GetFileName(item.ItemSpec);
string recursiveDir = item.GetMetadata("RecursiveDir");
relativeBlobPath = $"{feed.RelativePath}{recursiveDir}{fileName}";
}
relativeBlobPath = relativeBlobPath.Replace("\\", "/");
Log.LogMessage($"Uploading {relativeBlobPath}");
await clientThrottle.WaitAsync();
try
{
bool blobExists = false;
if (!allowOverwrite)
{
blobExists = await feed.CheckIfBlobExists(relativeBlobPath);
}
if (allowOverwrite || !blobExists)
{
Log.LogMessage($"Uploading {item} to {relativeBlobPath}.");
UploadClient uploadClient = new UploadClient(Log);
await uploadClient.UploadBlockBlobAsync(
CancellationToken,
feed.AccountName,
feed.AccountKey,
feed.ContainerName,
item.ItemSpec,
relativeBlobPath);
}
else
{
Log.LogError($"Item '{item}' already exists in {relativeBlobPath}.");
}
}
catch (Exception exc)
{
Log.LogError($"Unable to upload to {relativeBlobPath} due to {exc}.");
throw;
}
finally
{
clientThrottle.Release();
}
}
public async Task CreateContainerAsync(IBuildEngine buildEngine)
{
Log.LogMessage($"Creating container {feed.ContainerName}...");
CreateAzureContainer createContainer = new CreateAzureContainer
{
AccountKey = feed.AccountKey,
AccountName = feed.AccountName,
ContainerName = feed.ContainerName,
FailIfExists = false,
IsPublic = !hasToken,
BuildEngine = buildEngine
};
await createContainer.ExecuteAsync();
Log.LogMessage($"Creating container {feed.ContainerName} succeeded!");
try
{
bool result = await InitAsync();
if (result)
{
Log.LogMessage($"Initializing sub-feed {source.FeedSubPath} succeeded!");
}
else
{
throw new Exception($"Initializing sub-feed {source.FeedSubPath} failed!");
}
}
catch (Exception e)
{
Log.LogErrorFromException(e);
}
}
private bool IsSanityChecked(IEnumerable<string> items)
{
Log.LogMessage(MessageImportance.Low, $"START checking sanitized items for feed");
foreach (var item in items)
{
if (items.Any(s => Path.GetExtension(item) != ".nupkg"))
{
Log.LogError($"{item} is not a nupkg");
return false;
}
}
List<string> duplicates = items.GroupBy(x => x)
.Where(group => group.Count() > 1)
.Select(group => group.Key).ToList();
if (duplicates.Count > 0)
{
Log.LogError($"Duplicates found: {duplicates}");
return false;
}
Log.LogMessage(MessageImportance.Low, $"DONE checking for sanitized items for feed");
return true;
}
private LocalSettings GetSettings()
{
SleetSettings sleetSettings = new SleetSettings()
{
Sources = new List<SleetSource>
{
source
}
};
LocalSettings settings = new LocalSettings
{
Json = JObject.FromObject(sleetSettings)
};
return settings;
}
private AzureFileSystem GetAzureFileSystem()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(source.ConnectionString);
AzureFileSystem fileSystem = new AzureFileSystem(new LocalCache(), new Uri(source.Path), new Uri(source.Path), storageAccount, source.Name, source.FeedSubPath);
return fileSystem;
}
private async Task<bool> PushAsync(IEnumerable<string> items, bool allowOverwrite)
{
LocalSettings settings = GetSettings();
AzureFileSystem fileSystem = GetAzureFileSystem();
bool result = await PushCommand.RunAsync(settings, fileSystem, items.ToList(), allowOverwrite, false, new SleetLogger(Log));
return result;
}
private async Task<bool> InitAsync()
{
LocalSettings settings = GetSettings();
AzureFileSystem fileSystem = GetAzureFileSystem();
bool result = await InitCommand.RunAsync(settings, fileSystem, true, true, new SleetLogger(Log), CancellationToken);
return result;
}
}
}
| 1 | 14,115 | Do we need to call ToList here? | dotnet-buildtools | .cs |
@@ -5,5 +5,8 @@ class EpisodesController < ApplicationController
def show
@episode = Episode.find(params[:id])
+ if topic = @episode.topics.first
+ @products = topic.products.ordered
+ end
end
end | 1 | class EpisodesController < ApplicationController
def index
@episodes = Episode.published
end
def show
@episode = Episode.find(params[:id])
end
end
| 1 | 6,637 | I think this can be moved into the model, at the very least, but I also think you might be able to do a has many through. | thoughtbot-upcase | rb |
@@ -785,7 +785,7 @@ public interface Tree<T> extends Traversable<T> {
if (tree.isLeaf()) {
return value;
} else {
- return String.format("(%s %s)", value, tree.getChildren().map(Node::toLispString).mkString(" "));
+ return "(" + value + " " + (tree.getChildren().map(Node::toLispString).mkString(" ")) + ")";
}
}
| 1 | /* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.Tuple3;
import javaslang.collection.List.Nil;
import javaslang.collection.Tree.Empty;
import javaslang.collection.Tree.Node;
import javaslang.collection.TreeModule.*;
import javaslang.control.Option;
import java.io.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;
import static javaslang.collection.Tree.Order.PRE_ORDER;
/**
* A general Tree interface.
*
* @param <T> component type of this Tree
* @author Daniel Dietrich
* @author Grzegorz Piwowarek
* @since 1.1.0
*/
public interface Tree<T> extends Traversable<T> {
/**
* Returns a {@link java.util.stream.Collector} which may be used in conjunction with
* {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.Tree}.
*
* @param <T> Component type of the Tree.
* @return A javaslang.collection.Tree Collector.
*/
static <T> Collector<T, ArrayList<T>, Tree<T>> collector() {
final Supplier<ArrayList<T>> supplier = ArrayList::new;
final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
left.addAll(right);
return left;
};
final Function<ArrayList<T>, Tree<T>> finisher = Tree::ofAll;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns the singleton empty tree.
*
* @param <T> Type of tree values.
* @return The empty tree.
*/
static <T> Empty<T> empty() {
return Empty.instance();
}
/**
* Narrows a widened {@code Tree<? extends T>} to {@code Tree<T>}
* by performing a type safe-cast. This is eligible because immutable/read-only
* collections are covariant.
*
* @param tree An {@code Tree}.
* @param <T> Component type of the {@code Tree}.
* @return the given {@code tree} instance as narrowed type {@code Tree<T>}.
*/
@SuppressWarnings("unchecked")
static <T> Tree<T> narrow(Tree<? extends T> tree) {
return (Tree<T>) tree;
}
/**
* Returns a new Node containing the given value and having no children.
*
* @param value A value
* @param <T> Value type
* @return A new Node instance.
*/
static <T> Node<T> of(T value) {
return new Node<>(value, List.empty());
}
/**
* Returns a new Node containing the given value and having the given children.
*
* @param value A value
* @param children The child nodes, possibly empty
* @param <T> Value type
* @return A new Node instance.
*/
@SuppressWarnings("varargs")
@SafeVarargs
static <T> Node<T> of(T value, Node<T>... children) {
Objects.requireNonNull(children, "children is null");
return new Node<>(value, List.of(children));
}
/**
* Returns a new Node containing the given value and having the given children.
*
* @param value A value
* @param children The child nodes, possibly empty
* @param <T> Value type
* @return A new Node instance.
*/
static <T> Node<T> of(T value, Iterable<Node<T>> children) {
Objects.requireNonNull(children, "children is null");
return new Node<>(value, List.ofAll(children));
}
/**
* Creates a Tree of the given elements.
*
* @param <T> Component type of the List.
* @param values Zero or more values.
* @return A Tree containing the given values.
* @throws NullPointerException if {@code values} is null
*/
@SuppressWarnings("varargs")
@SafeVarargs
static <T> Tree<T> of(T... values) {
Objects.requireNonNull(values, "values is null");
List<T> list = List.of(values);
return list.isEmpty() ? Empty.instance() : new Node<>(list.head(), list.tail().map(Tree::of));
}
/**
* Creates a Tree of the given elements.
* <p>
* If the given iterable is a tree, it is returned as result.
* if the iteration order of the elements is stable.
*
* @param <T> Component type of the List.
* @param iterable An Iterable of elements.
* @return A list containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("unchecked")
static <T> Tree<T> ofAll(Iterable<? extends T> iterable) {
Objects.requireNonNull(iterable, "iterable is null");
if (iterable instanceof Tree) {
return (Tree<T>) iterable;
} else {
final List<T> list = List.ofAll(iterable);
return list.isEmpty() ? Empty.instance() : new Node<>(list.head(), list.tail().map(Tree::of));
}
}
/**
* Returns a Tree containing {@code n} values of a given Function {@code f}
* over a range of integer values from 0 to {@code n - 1}.
*
* @param <T> Component type of the Tree
* @param n The number of elements in the Tree
* @param f The Function computing element values
* @return A Tree consisting of elements {@code f(0),f(1), ..., f(n - 1)}
* @throws NullPointerException if {@code f} is null
*/
static <T> Tree<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
Objects.requireNonNull(f, "f is null");
return Collections.tabulate(n, f, Tree.empty(), Tree::of);
}
/**
* Returns a Tree containing {@code n} values supplied by a given Supplier {@code s}.
*
* @param <T> Component type of the Tree
* @param n The number of elements in the Tree
* @param s The Supplier computing element values
* @return A Tree of size {@code n}, where each element contains the result supplied by {@code s}.
* @throws NullPointerException if {@code s} is null
*/
static <T> Tree<T> fill(int n, Supplier<? extends T> s) {
Objects.requireNonNull(s, "s is null");
return Collections.fill(n, s, Tree.empty(), Tree::of);
}
/**
* Gets the value of this tree.
*
* @return The value of this tree.
* @throws java.lang.UnsupportedOperationException if this tree is empty
*/
T getValue();
/**
* Returns the children of this tree.
*
* @return the tree's children
*/
List<Node<T>> getChildren();
/**
* Checks if this Tree is a leaf. A tree is a leaf if it is a Node with no children.
* Because the empty tree is no Node, it is not a leaf by definition.
*
* @return true if this tree is a leaf, false otherwise.
*/
boolean isLeaf();
/**
* Checks if this Tree is a branch. A Tree is a branch if it is a Node which has children.
* Because the empty tree is not a Node, it is not a branch by definition.
*
* @return true if this tree is a branch, false otherwise.
*/
default boolean isBranch() {
return !(isEmpty() || isLeaf());
}
/**
* Traverses this tree values in a specific {@link javaslang.collection.Tree.Order}.
*
* @param order A traversal order
* @return A new Iterator
*/
default Iterator<T> iterator(Order order) {
return values(order).iterator();
}
/**
* Transforms this {@code Tree}.
*
* @param f A transformation
* @param <U> Type of transformation result
* @return An instance of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
default <U> U transform(Function<? super Tree<T>, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return f.apply(this);
}
/**
* Traverses this tree in {@link Order#PRE_ORDER}.
*
* @return A sequence of nodes.
*/
default Seq<Node<T>> traverse() {
return traverse(PRE_ORDER);
}
/**
* Traverses this tree in a specific order.
*
* @param order the tree traversal order
* @return A sequence of nodes.
* @throws java.lang.NullPointerException if order is null
*/
default Seq<Node<T>> traverse(Order order) {
Objects.requireNonNull(order, "order is null");
if (isEmpty()) {
return Stream.empty();
} else {
final Node<T> node = (Node<T>) this;
switch (order) {
case PRE_ORDER:
return Traversal.preOrder(node);
case IN_ORDER:
return Traversal.inOrder(node);
case POST_ORDER:
return Traversal.postOrder(node);
case LEVEL_ORDER:
return Traversal.levelOrder(node);
default:
throw new IllegalStateException("Unknown order: " + order.name());
}
}
}
/**
* Traverses this tree values in {@link Order#PRE_ORDER}.
* Syntactic sugar for {@code traverse().map(Node::getValue)}.
*
* @return A sequence of the tree values.
*/
default Seq<T> values() {
return traverse(PRE_ORDER).map(Node::getValue);
}
/**
* Traverses this tree values in a specific order.
* Syntactic sugar for {@code traverse(order).map(Node::getValue)}.
*
* @param order the tree traversal order
* @return A sequence of the tree values.
* @throws java.lang.NullPointerException if order is null
*/
default Seq<T> values(Order order) {
return traverse(order).map(Node::getValue);
}
/**
* Counts the number of branches of this tree. The empty tree and a leaf have no branches.
*
* @return The number of branches of this tree.
*/
default int branchCount() {
if (isEmpty() || isLeaf()) {
return 0;
} else {
return getChildren().foldLeft(1, (count, child) -> count + child.branchCount());
}
}
/**
* Counts the number of leaves of this tree. The empty tree has no leaves.
*
* @return The number of leaves of this tree.
*/
default int leafCount() {
if (isEmpty()) {
return 0;
} else if (isLeaf()) {
return 1;
} else {
return getChildren().foldLeft(0, (count, child) -> count + child.leafCount());
}
}
/**
* Counts the number of nodes (i.e. branches and leaves) of this tree. The empty tree has no nodes.
*
* @return The number of nodes of this tree.
*/
default int nodeCount() {
return length();
}
// -- Methods inherited from Traversable
@Override
default Seq<T> distinct() {
return values().distinct();
}
@Override
default Seq<T> distinctBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
if (isEmpty()) {
return Stream.empty();
} else {
return values().distinctBy(comparator);
}
}
@Override
default <U> Seq<T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor is null");
if (isEmpty()) {
return Stream.empty();
} else {
return values().distinctBy(keyExtractor);
}
}
@Override
default Seq<T> drop(long n) {
if (n >= length()) {
return Stream.empty();
} else {
return values().drop(n);
}
}
@Override
default Seq<T> dropRight(long n) {
if (n >= length()) {
return Stream.empty();
} else {
return values().dropRight(n);
}
}
@Override
default Seq<T> dropUntil(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return dropWhile(predicate.negate());
}
@Override
default Seq<T> dropWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Stream.empty();
} else {
return values().dropWhile(predicate);
}
}
@Override
default Seq<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Stream.empty();
} else {
return values().filter(predicate);
}
}
@Override
default <U> Tree<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return isEmpty() ? Empty.instance() : FlatMap.apply((Node<T>) this, mapper);
}
@Override
default <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
if (isEmpty()) {
return zero;
} else {
return iterator().foldRight(zero, f);
}
}
@SuppressWarnings("unchecked")
@Override
default <C> Map<C, Seq<T>> groupBy(Function<? super T, ? extends C> classifier) {
Objects.requireNonNull(classifier, "classifier is null");
if (isEmpty()) {
return HashMap.empty();
} else {
return (Map<C, Seq<T>>) values().groupBy(classifier);
}
}
@Override
default Iterator<Seq<T>> grouped(long size) {
return sliding(size, size);
}
@Override
default boolean hasDefiniteSize() {
return true;
}
@Override
default T head() {
if (isEmpty()) {
throw new NoSuchElementException("head of empty tree");
} else {
return iterator().next();
}
}
@Override
default Seq<T> init() {
if (isEmpty()) {
throw new UnsupportedOperationException("init of empty tree");
} else {
return values().init();
}
}
@Override
default Option<Seq<T>> initOption() {
return isEmpty() ? Option.none() : Option.some(init());
}
@Override
default boolean isTraversableAgain() {
return true;
}
@Override
default Iterator<T> iterator() {
return values().iterator();
}
@Override
default <U> Tree<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return isEmpty() ? Empty.instance() : TreeModule.Map.apply((Node<T>) this, mapper);
}
@SuppressWarnings("unchecked")
@Override
default Tuple2<Seq<T>, Seq<T>> partition(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Tuple.of(Stream.empty(), Stream.empty());
} else {
return (Tuple2<Seq<T>, Seq<T>>) values().partition(predicate);
}
}
@Override
default Tree<T> peek(Consumer<? super T> action) {
Objects.requireNonNull(action, "action is null");
if (!isEmpty()) {
action.accept(head());
}
return this;
}
@Override
default Tree<T> replace(T currentElement, T newElement) {
if (isEmpty()) {
return Empty.instance();
} else {
return Replace.apply((Node<T>) this, currentElement, newElement);
}
}
@Override
default Tree<T> replaceAll(T currentElement, T newElement) {
return map(t -> Objects.equals(t, currentElement) ? newElement : t);
}
@Override
default Seq<T> retainAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
return values().retainAll(elements);
}
@Override
default Seq<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) {
return scanLeft(zero, operation);
}
@Override
default <U> Seq<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) {
Objects.requireNonNull(operation, "operation is null");
return Collections.scanLeft(this, zero, operation, List.empty(), List::prepend, List::reverse);
}
@Override
default <U> Seq<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
Objects.requireNonNull(operation, "operation is null");
return Collections.scanRight(this, zero, operation, List.empty(), List::prepend, Function.identity());
}
@Override
default Iterator<Seq<T>> sliding(long size) {
return sliding(size, 1);
}
@Override
default Iterator<Seq<T>> sliding(long size, long step) {
return iterator().sliding(size, step);
}
@SuppressWarnings("unchecked")
@Override
default Tuple2<Seq<T>, Seq<T>> span(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Tuple.of(Stream.empty(), Stream.empty());
} else {
return (Tuple2<Seq<T>, Seq<T>>) values().span(predicate);
}
}
@Override
default Spliterator<T> spliterator() {
// the focus of the Stream API is on random-access collections of *known size*
return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE);
}
@Override
default String stringPrefix() {
return "Tree";
}
@Override
default Seq<T> tail() {
if (isEmpty()) {
throw new UnsupportedOperationException("tail of empty tree");
} else {
return values().tail();
}
}
@Override
default Option<Seq<T>> tailOption() {
return isEmpty() ? Option.none() : Option.some(tail());
}
@Override
default Seq<T> take(long n) {
if (isEmpty()) {
return Stream.empty();
} else {
return values().take(n);
}
}
@Override
default Seq<T> takeRight(long n) {
if (isEmpty()) {
return Stream.empty();
} else {
return values().takeRight(n);
}
}
@Override
default Seq<T> takeUntil(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return values().takeUntil(predicate);
}
@Override
default Seq<T> takeWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return values().takeWhile(predicate);
}
@SuppressWarnings("unchecked")
@Override
default <T1, T2> Tuple2<Tree<T1>, Tree<T2>> unzip(
Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
if (isEmpty()) {
return Tuple.of(Empty.instance(), Empty.instance());
} else {
return (Tuple2<Tree<T1>, Tree<T2>>) (Object) Unzip.apply((Node<T>) this, unzipper);
}
}
@SuppressWarnings("unchecked")
@Override
default <T1, T2, T3> Tuple3<Tree<T1>, Tree<T2>, Tree<T3>> unzip3(
Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
if (isEmpty()) {
return Tuple.of(Empty.instance(), Empty.instance(), Empty.instance());
} else {
return (Tuple3<Tree<T1>, Tree<T2>, Tree<T3>>) (Object) Unzip.apply3((Node<T>) this, unzipper);
}
}
@Override
default <U> Tree<Tuple2<T, U>> zip(Iterable<? extends U> that) {
Objects.requireNonNull(that, "that is null");
if (isEmpty()) {
return Empty.instance();
} else {
return Zip.apply((Node<T>) this, that.iterator());
}
}
@Override
default <U> Tree<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) {
Objects.requireNonNull(that, "that is null");
if (isEmpty()) {
return Iterator.ofAll(that).map(elem -> Tuple.of(thisElem, elem)).toTree();
} else {
final java.util.Iterator<? extends U> thatIter = that.iterator();
final Tree<Tuple2<T, U>> tree = ZipAll.apply((Node<T>) this, thatIter, thatElem);
if (thatIter.hasNext()) {
final Iterable<Node<Tuple2<T, U>>> remainder = Iterator
.ofAll(thatIter)
.map(elem -> Tree.of(Tuple.of(thisElem, elem)));
return new Node<>(tree.getValue(), tree.getChildren().appendAll(remainder));
} else {
return tree;
}
}
}
@Override
default Tree<Tuple2<T, Long>> zipWithIndex() {
return zip(Iterator.from(0L));
}
@Override
boolean equals(Object o);
@Override
int hashCode();
@Override
String toString();
/**
* Creates a neat 2-dimensional drawing of a tree. Unicode characters are used to draw node junctions.
*
* @return A nice string representation of the tree.
*/
String draw();
/**
* Represents a tree node.
*
* @param <T> value type
*/
final class Node<T> implements Tree<T>, Serializable {
private static final long serialVersionUID = 1L;
private final T value;
private final List<Node<T>> children;
private final int size;
/**
* Constructs a rose tree branch.
*
* @param value A value.
* @param children A non-empty list of children.
* @throws NullPointerException if children is null
* @throws IllegalArgumentException if children is empty
*/
public Node(T value, List<Node<T>> children) {
Objects.requireNonNull(children, "children is null");
this.value = value;
this.children = children;
this.size = 1 + this.children.foldLeft(0, (acc, child) -> acc + child.size);
}
@Override
public List<Node<T>> getChildren() {
return children;
}
@Override
public T getValue() {
return value;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public int length() {
return size;
}
@Override
public boolean isLeaf() {
return size == 1;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof Node) {
final Node<?> that = (Node<?>) o;
return Objects.equals(this.getValue(), that.getValue())
&& Objects.equals(this.getChildren(), that.getChildren());
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(value, children);
}
@Override
public String toString() {
return stringPrefix() + (isLeaf() ? "(" + value + ")" : toLispString(this));
}
@Override
public String draw() {
StringBuilder builder = new StringBuilder();
drawAux("", builder);
return builder.toString();
}
private void drawAux(String indent, StringBuilder builder) {
builder.append(value);
for (List<Node<T>> it = children; !it.isEmpty(); it = it.tail()) {
final boolean isLast = it.tail().isEmpty();
builder.append('\n')
.append(indent)
.append(isLast ? "└──" : "├──");
it.head().drawAux(indent + (isLast ? " " : "│ "), builder);
}
}
private static String toLispString(Tree<?> tree) {
final String value = String.valueOf(tree.getValue());
if (tree.isLeaf()) {
return value;
} else {
return String.format("(%s %s)", value, tree.getChildren().map(Node::toLispString).mkString(" "));
}
}
// -- Serializable implementation
/**
* {@code writeReplace} method for the serialization proxy pattern.
* <p>
* The presence of this method causes the serialization system to emit a SerializationProxy instance instead of
* an instance of the enclosing class.
*
* @return A SerialiationProxy for this enclosing class.
*/
private Object writeReplace() {
return new SerializationProxy<>(this);
}
/**
* {@code readObject} method for the serialization proxy pattern.
* <p>
* Guarantees that the serialization system will never generate a serialized instance of the enclosing class.
*
* @param stream An object serialization stream.
* @throws java.io.InvalidObjectException This method will throw with the message "Proxy required".
*/
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Proxy required");
}
/**
* A serialization proxy which, in this context, is used to deserialize immutable nodes with final
* instance fields.
*
* @param <T> The component type of the underlying tree.
*/
// DEV NOTE: The serialization proxy pattern is not compatible with non-final, i.e. extendable,
// classes. Also, it may not be compatible with circular object graphs.
private static final class SerializationProxy<T> implements Serializable {
private static final long serialVersionUID = 1L;
// the instance to be serialized/deserialized
private transient Node<T> node;
/**
* Constructor for the case of serialization, called by {@link Node#writeReplace()}.
* <p/>
* The constructor of a SerializationProxy takes an argument that concisely represents the logical state of
* an instance of the enclosing class.
*
* @param node a Branch
*/
SerializationProxy(Node<T> node) {
this.node = node;
}
/**
* Write an object to a serialization stream.
*
* @param s An object serialization stream.
* @throws java.io.IOException If an error occurs writing to the stream.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(node.value);
s.writeObject(node.children);
}
/**
* Read an object from a deserialization stream.
*
* @param s An object deserialization stream.
* @throws ClassNotFoundException If the object's class read from the stream cannot be found.
* @throws IOException If an error occurs reading from the stream.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
s.defaultReadObject();
final T value = (T) s.readObject();
final List<Node<T>> children = (List<Node<T>>) s.readObject();
node = new Node<>(value, children);
}
/**
* {@code readResolve} method for the serialization proxy pattern.
* <p>
* Returns a logically equivalent instance of the enclosing class. The presence of this method causes the
* serialization system to translate the serialization proxy back into an instance of the enclosing class
* upon deserialization.
*
* @return A deserialized instance of the enclosing class.
*/
private Object readResolve() {
return node;
}
}
}
/**
* The empty tree. Use Tree.empty() to create an instance.
*
* @param <T> type of the tree's values
*/
final class Empty<T> implements Tree<T>, Serializable {
private static final long serialVersionUID = 1L;
private static final Empty<?> INSTANCE = new Empty<>();
// hidden
private Empty() {
}
@SuppressWarnings("unchecked")
public static <T> Empty<T> instance() {
return (Empty<T>) INSTANCE;
}
@Override
public List<Node<T>> getChildren() {
return Nil.instance();
}
@Override
public T getValue() {
throw new UnsupportedOperationException("getValue of empty Tree");
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public int length() {
return 0;
}
@Override
public boolean isLeaf() {
return false;
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return 1;
}
@Override
public String toString() {
return stringPrefix() + "()";
}
@Override
public String draw() { return "▣"; }
// -- Serializable implementation
/**
* Instance control for object serialization.
*
* @return The singleton instance of Nil.
* @see java.io.Serializable
*/
private Object readResolve() {
return INSTANCE;
}
}
/**
* Tree traversal order.
* <p>
* Example tree:
* <pre>
* <code>
* 1
* / \
* / \
* / \
* 2 3
* / \ /
* 4 5 6
* / / \
* 7 8 9
* </code>
* </pre>
*
* See also
* <ul>
* <li><a href="http://en.wikipedia.org/wiki/Tree_traversal">Tree traversal</a> (wikipedia)</li>
* <li>See <a href="http://rosettacode.org/wiki/Tree_traversal">Tree traversal</a> (rosetta code)</li>
* </ul>
*/
// see http://programmers.stackexchange.com/questions/138766/in-order-traversal-of-m-way-trees
enum Order {
/**
* 1 2 4 7 5 3 6 8 9 (= depth-first)
*/
PRE_ORDER,
/**
* 7 4 2 5 1 8 6 9 3
*/
IN_ORDER,
/**
* 7 4 5 2 8 9 6 3 1
*/
POST_ORDER,
/**
* 1 2 3 4 5 6 7 8 9 (= breadth-first)
*/
LEVEL_ORDER
}
}
/**
* Because the empty tree {@code Empty} cannot be a child of an existing tree, method implementations distinguish between the
* empty and non-empty case. Because the structure of trees is recursive, often we have commands in the form of module
* classes with one static method.
*/
interface TreeModule {
final class FlatMap {
@SuppressWarnings("unchecked")
static <T, U> Tree<U> apply(Node<T> node, Function<? super T, ? extends Iterable<? extends U>> mapper) {
final Tree<U> mapped = Tree.ofAll(mapper.apply(node.getValue()));
if (mapped.isEmpty()) {
return Tree.empty();
} else {
final List<Node<U>> children = (List<Node<U>>) (Object) node
.getChildren()
.map(child -> FlatMap.apply(child, mapper))
.filter(Tree::nonEmpty);
return Tree.of(mapped.getValue(), children.prependAll(mapped.getChildren()));
}
}
}
final class Map {
static <T, U> Node<U> apply(Node<T> node, Function<? super T, ? extends U> mapper) {
final U value = mapper.apply(node.getValue());
final List<Node<U>> children = node.getChildren().map(child -> Map.apply(child, mapper));
return new Node<>(value, children);
}
}
final class Replace {
// Idea:
// Traverse (depth-first) until a match is found, then stop and rebuild relevant parts of the tree.
// If not found, return the same tree instance.
static <T> Node<T> apply(Node<T> node, T currentElement, T newElement) {
if (Objects.equals(node.getValue(), currentElement)) {
return new Node<>(newElement, node.getChildren());
} else {
for (Node<T> child : node.getChildren()) {
final Node<T> newChild = Replace.apply(child, currentElement, newElement);
final boolean found = newChild != child;
if (found) {
final List<Node<T>> newChildren = node.getChildren().replace(child, newChild);
return new Node<>(node.getValue(), newChildren);
}
}
return node;
}
}
}
final class Traversal {
static <T> Stream<Node<T>> preOrder(Node<T> node) {
return node.getChildren().foldLeft(Stream.of(node),
(acc, child) -> acc.appendAll(preOrder(child)));
}
static <T> Stream<Node<T>> inOrder(Node<T> node) {
if (node.isLeaf()) {
return Stream.of(node);
} else {
final List<Node<T>> children = node.getChildren();
return children
.tail()
.foldLeft(Stream.<Node<T>> empty(), (acc, child) -> acc.appendAll(inOrder(child)))
.prepend(node)
.prependAll(inOrder(children.head()));
}
}
static <T> Stream<Node<T>> postOrder(Node<T> node) {
return node
.getChildren()
.foldLeft(Stream.<Node<T>> empty(), (acc, child) -> acc.appendAll(postOrder(child)))
.append(node);
}
static <T> Stream<Node<T>> levelOrder(Node<T> node) {
Stream<Node<T>> result = Stream.empty();
final java.util.Queue<Node<T>> queue = new java.util.LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
final Node<T> next = queue.remove();
result = result.prepend(next);
queue.addAll(next.getChildren().toJavaList());
}
return result.reverse();
}
}
final class Unzip {
static <T, T1, T2> Tuple2<Node<T1>, Node<T2>> apply(Node<T> node,
Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
final Tuple2<? extends T1, ? extends T2> value = unzipper.apply(node.getValue());
final List<Tuple2<Node<T1>, Node<T2>>> children = node
.getChildren()
.map(child -> Unzip.apply(child, unzipper));
final Node<T1> node1 = new Node<>(value._1, children.map(t -> t._1));
final Node<T2> node2 = new Node<>(value._2, children.map(t -> t._2));
return Tuple.of(node1, node2);
}
static <T, T1, T2, T3> Tuple3<Node<T1>, Node<T2>, Node<T3>> apply3(Node<T> node,
Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
final Tuple3<? extends T1, ? extends T2, ? extends T3> value = unzipper.apply(node.getValue());
final List<Tuple3<Node<T1>, Node<T2>, Node<T3>>> children = node.getChildren()
.map(child -> Unzip.apply3(child, unzipper));
final Node<T1> node1 = new Node<>(value._1, children.map(t -> t._1));
final Node<T2> node2 = new Node<>(value._2, children.map(t -> t._2));
final Node<T3> node3 = new Node<>(value._3, children.map(t -> t._3));
return Tuple.of(node1, node2, node3);
}
}
final class Zip {
@SuppressWarnings("unchecked")
static <T, U> Tree<Tuple2<T, U>> apply(Node<T> node, java.util.Iterator<? extends U> that) {
if (!that.hasNext()) {
return Empty.instance();
} else {
final Tuple2<T, U> value = Tuple.of(node.getValue(), that.next());
final List<Node<Tuple2<T, U>>> children = (List<Node<Tuple2<T, U>>>) (Object) node
.getChildren()
.map(child -> Zip.apply(child, that))
.filter(Tree::nonEmpty);
return new Node<>(value, children);
}
}
}
final class ZipAll {
@SuppressWarnings("unchecked")
static <T, U> Tree<Tuple2<T, U>> apply(Node<T> node, java.util.Iterator<? extends U> that, U thatElem) {
if (!that.hasNext()) {
return node.map(value -> Tuple.of(value, thatElem));
} else {
final Tuple2<T, U> value = Tuple.of(node.getValue(), that.next());
final List<Node<Tuple2<T, U>>> children = (List<Node<Tuple2<T, U>>>) (Object) node
.getChildren()
.map(child -> ZipAll.apply(child, that, thatElem))
.filter(Tree::nonEmpty);
return new Node<>(value, children);
}
}
}
}
| 1 | 7,801 | could you please separate computations from string concatenation? | vavr-io-vavr | java |
@@ -216,8 +216,8 @@ namespace Microsoft.Rest.Generator.Tests
var type = clientModel.ModelTypes.First();
- Assert.Equal("code", type.Properties[0].Name);
- Assert.Equal("message", type.Properties[1].Name);
+ Assert.Equal("errorCode", type.Properties[0].Name);
+ Assert.Equal("errorMessage", type.Properties[1].Name);
Assert.Equal("parentError", type.Properties[2].Name);
}
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.IO;
using System.Linq;
using Microsoft.Rest.Generator.Ruby.TemplateModels;
using Microsoft.Rest.Modeler.Swagger;
using Xunit;
namespace Microsoft.Rest.Generator.Tests
{
public class ExtensionsTests
{
[Fact]
public void TestClientModelWithPayloadFlattening()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-payload-flatten.json"),
PayloadFlatteningThreshold = 3
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
Assert.NotNull(clientModel);
Assert.Equal(4, clientModel.Methods[0].Parameters.Count);
Assert.Equal("String subscriptionId", clientModel.Methods[0].Parameters[0].ToString());
Assert.Equal("String resourceGroupName", clientModel.Methods[0].Parameters[1].ToString());
Assert.Equal("String apiVersion", clientModel.Methods[0].Parameters[2].ToString());
Assert.Equal("MaxProduct max_product", clientModel.Methods[0].Parameters[3].ToString());
Assert.Equal(6, clientModel.Methods[1].Parameters.Count);
Assert.Equal("String subscriptionId", clientModel.Methods[1].Parameters[0].ToString());
Assert.Equal("String resourceGroupName", clientModel.Methods[1].Parameters[1].ToString());
Assert.Equal("String apiVersion", clientModel.Methods[1].Parameters[2].ToString());
Assert.Equal("String base_product_id", clientModel.Methods[1].Parameters[3].ToString());
Assert.Equal(true, clientModel.Methods[1].Parameters[3].IsRequired);
Assert.Equal("String base_product_description", clientModel.Methods[1].Parameters[4].ToString());
Assert.Equal(false, clientModel.Methods[1].Parameters[4].IsRequired);
Assert.Equal("MaxProduct max_product_reference", clientModel.Methods[1].Parameters[5].ToString());
Assert.Equal(false, clientModel.Methods[1].Parameters[5].IsRequired);
Assert.Equal(1, clientModel.Methods[1].InputParameterTransformation.Count);
Assert.Equal(3, clientModel.Methods[1].InputParameterTransformation[0].ParameterMappings.Count);
}
[Fact]
public void TestClientModelWithPayloadFlatteningViaXMSClientFlatten()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-flatten.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
Assert.NotNull(clientModel);
Assert.Equal(8, clientModel.ModelTypes.Count);
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "BaseProduct"));
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "SimpleProduct"));
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "ConflictedProduct"));
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "ConflictedProductProperties")); // Since it's referenced in the response
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "RecursiveProduct"));
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "Error"));
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "ProductWithInheritance"));
Assert.True(clientModel.ModelTypes.Any(m => m.Name == "BaseFlattenedProduct"));
var simpleProduct = clientModel.ModelTypes.First(m => m.Name == "SimpleProduct");
Assert.True(simpleProduct.Properties.Any(p => p.SerializedName == "details.max_product_display_name"
&& p.Name == "max_product_display_name"));
Assert.True(simpleProduct.Properties.Any(p => p.SerializedName == "details.max_product_capacity"
&& p.Name == "max_product_capacity"));
Assert.True(simpleProduct.Properties.Any(p => p.SerializedName == "details.max_product_image.@odata\\\\.value"
&& p.Name == "@odata.value"));
var conflictedProduct = clientModel.ModelTypes.First(m => m.Name == "ConflictedProduct");
Assert.True(conflictedProduct.Properties.Any(p => p.SerializedName == "max_product_display_name"
&& p.Name == "max_product_display_name"));
Assert.True(conflictedProduct.Properties.Any(p => p.SerializedName == "details.max_product_display_name"
&& p.Name == "ConflictedProductProperties_max_product_display_name"));
Assert.True(conflictedProduct.Properties.Any(p => p.SerializedName == "simpleDetails.max_product_display_name"
&& p.Name == "SimpleProductProperties_max_product_display_name"));
Assert.True(conflictedProduct.Properties.Any(p => p.SerializedName == "details.base_product_description"
&& p.Name == "ConflictedProduct_base_product_description"));
var recursiveProduct = clientModel.ModelTypes.First(m => m.Name == "RecursiveProduct");
Assert.True(recursiveProduct.Properties.Any(p => p.SerializedName == "properties.name"
&& p.Name == "name"));
Assert.True(recursiveProduct.Properties.Any(p => p.SerializedName == "properties.parent"
&& p.Name == "parent"));
var error = clientModel.ModelTypes.First(m => m.Name == "Error");
Assert.Equal(3, error.Properties.Count);
Assert.True(error.Properties.Any(p => p.SerializedName == "code" && p.Name == "code"));
Assert.True(error.Properties.Any(p => p.SerializedName == "message" && p.Name == "message"));
Assert.True(error.Properties.Any(p => p.SerializedName == "parentError" && p.Name == "parentError"));
Assert.True(error.Properties.First(p => p.SerializedName == "parentError" && p.Name == "parentError").Type == error);
}
[Fact]
public void TestClientModelClientName()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
Assert.NotNull(clientModel);
Assert.Equal(2, clientModel.Methods.Count);
Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName());
Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName());
Assert.Equal("subscriptionId", clientModel.Methods[0].Parameters[0].Name);
Assert.Equal("apiVersion", clientModel.Methods[0].Parameters[1].Name);
Assert.Equal(2, clientModel.Properties.Count);
Assert.Equal("subscription", clientModel.Properties[0].GetClientName());
Assert.Equal("_version", clientModel.Properties[1].GetClientName());
Assert.Equal("subscriptionId", clientModel.Properties[0].Name);
Assert.Equal("apiVersion", clientModel.Properties[1].Name);
Assert.Equal(1, clientModel.ModelTypes.Count);
var type = clientModel.ModelTypes.First();
Assert.Equal("code", type.Properties[0].Name);
Assert.Equal("message", type.Properties[1].Name);
Assert.Equal("parentError", type.Properties[2].Name);
Assert.Equal("errorCode", type.Properties[0].GetClientName());
Assert.Equal("errorMessage", type.Properties[1].GetClientName());
Assert.Equal("ParentError", type.Properties[2].GetClientName());
}
[Fact]
public void TestClientNameCSharpNormalization()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
var namer = new Microsoft.Rest.Generator.CSharp.CSharpCodeNamer();
namer.NormalizeClientModel(clientModel);
Assert.NotNull(clientModel);
Assert.Equal(2, clientModel.Methods.Count);
Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName());
Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name);
Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name);
Assert.Equal(2, clientModel.Properties.Count);
Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Properties[0].GetClientName());
Assert.Equal("_version", clientModel.Properties[1].GetClientName());
Assert.Equal("Subscription", clientModel.Properties[0].Name);
Assert.Equal("_version", clientModel.Properties[1].Name);
var type = clientModel.ModelTypes.First();
Assert.Equal("ErrorCode", type.Properties[0].Name);
Assert.Equal("ErrorMessage", type.Properties[1].Name);
Assert.Equal("ParentError", type.Properties[2].Name);
}
[Fact]
public void TestClientNameJavaNormalization()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
var namer = new Microsoft.Rest.Generator.Java.JavaCodeNamer();
namer.NormalizeClientModel(clientModel);
Assert.NotNull(clientModel);
Assert.Equal(2, clientModel.Methods.Count);
Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName());
Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name);
Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name);
Assert.Equal(2, clientModel.Properties.Count);
Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Properties[0].GetClientName());
Assert.Equal("_version", clientModel.Properties[1].GetClientName());
Assert.Equal("subscription", clientModel.Properties[0].Name);
Assert.Equal("_version", clientModel.Properties[1].Name);
var type = clientModel.ModelTypes.First();
Assert.Equal("code", type.Properties[0].Name);
Assert.Equal("message", type.Properties[1].Name);
Assert.Equal("parentError", type.Properties[2].Name);
}
[Fact]
public void TestClientNameNodeJSNormalization()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
var namer = new Microsoft.Rest.Generator.NodeJS.NodeJsCodeNamer();
namer.NormalizeClientModel(clientModel);
Assert.NotNull(clientModel);
Assert.Equal(2, clientModel.Methods.Count);
Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName());
Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name);
Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name);
Assert.Equal(2, clientModel.Properties.Count);
Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Properties[0].GetClientName());
Assert.Equal("_version", clientModel.Properties[1].GetClientName());
Assert.Equal("subscription", clientModel.Properties[0].Name);
Assert.Equal("_version", clientModel.Properties[1].Name);
var type = clientModel.ModelTypes.First();
Assert.Equal("errorCode", type.Properties[0].Name);
Assert.Equal("errorMessage", type.Properties[1].Name);
Assert.Equal("parentError", type.Properties[2].Name);
}
[Fact]
public void TestClientNamePythonNormalization()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
var namer = new Microsoft.Rest.Generator.Python.PythonCodeNamer();
namer.NormalizeClientModel(clientModel);
Assert.NotNull(clientModel);
Assert.Equal(2, clientModel.Methods.Count);
Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName());
Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name);
Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name);
Assert.Equal(2, clientModel.Properties.Count);
Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Properties[0].GetClientName());
Assert.Equal("_version", clientModel.Properties[1].GetClientName());
Assert.Equal("subscription", clientModel.Properties[0].Name);
Assert.Equal("_version", clientModel.Properties[1].Name);
var type = clientModel.ModelTypes.First();
Assert.Equal("code", type.Properties[0].Name);
Assert.Equal("message", type.Properties[1].Name);
Assert.Equal("parent_error", type.Properties[2].Name);
}
[Fact]
public void TestClientNameRubyNormalization()
{
var setting = new Settings
{
Namespace = "Test",
Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json")
};
var modeler = new SwaggerModeler(setting);
var clientModel = modeler.Build();
Extensions.NormalizeClientModel(clientModel, setting);
var namer = new Microsoft.Rest.Generator.Ruby.RubyCodeNamer();
namer.NormalizeClientModel(clientModel);
Assert.NotNull(clientModel);
Assert.Equal(2, clientModel.Methods.Count);
Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName());
Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName());
Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name);
Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name);
Assert.Equal(2, clientModel.Properties.Count);
Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count());
Assert.Equal("subscription", clientModel.Properties[0].GetClientName());
Assert.Equal("_version", clientModel.Properties[1].GetClientName());
Assert.Equal("subscription", clientModel.Properties[0].Name);
Assert.Equal("_version", clientModel.Properties[1].Name);
var type = clientModel.ModelTypes.First();
Assert.Equal("error_code", type.Properties[0].Name);
Assert.Equal("error_message", type.Properties[1].Name);
Assert.Equal("parent_error", type.Properties[2].Name);
}
}
}
| 1 | 21,657 | @NiklasGustafsson - I had to make these changes for the x-ms-client-name extension tests for java and python. The tests were expecting wire format instead of the client name. Hence modified them appropriately. Let me know what you think ? | Azure-autorest | java |
@@ -59,6 +59,13 @@ static int on_req(h2o_handler_t *_self, h2o_req_t *req)
authority = &self->upstream.authority;
}
+ /* rewrite headers */
+ if (self->config.header_cmds.size != 0) {
+ h2o_headers_command_t *cmd;
+ for (cmd = self->config.header_cmds.entries; cmd->cmd != H2O_HEADERS_CMD_NULL; ++cmd)
+ h2o_rewrite_headers(&req->pool, &req->headers, cmd);
+ }
+
/* request reprocess */
h2o_reprocess_request(req, req->method, scheme, *authority,
h2o_build_destination(req, self->upstream.path.base, self->upstream.path.len, 0), overrides, 0); | 1 | /*
* Copyright (c) 2014,2015 DeNA Co., Ltd., Masahiro Nagano
*
* 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 <sys/un.h>
#include "h2o.h"
#include "h2o/socketpool.h"
struct rp_handler_t {
h2o_handler_t super;
h2o_url_t upstream; /* host should be NULL-terminated */
h2o_socketpool_t *sockpool; /* non-NULL if config.use_keepalive == 1 */
h2o_proxy_config_vars_t config;
};
static int on_req(h2o_handler_t *_self, h2o_req_t *req)
{
struct rp_handler_t *self = (void *)_self;
h2o_req_overrides_t *overrides = h2o_mem_alloc_pool(&req->pool, sizeof(*overrides));
const h2o_url_scheme_t *scheme;
h2o_iovec_t *authority;
/* setup overrides */
*overrides = (h2o_req_overrides_t){NULL};
if (self->sockpool != NULL) {
overrides->socketpool = self->sockpool;
} else if (self->config.preserve_host) {
overrides->hostport.host = self->upstream.host;
overrides->hostport.port = h2o_url_get_port(&self->upstream);
}
overrides->location_rewrite.match = &self->upstream;
overrides->location_rewrite.path_prefix = req->pathconf->path;
overrides->use_proxy_protocol = self->config.use_proxy_protocol;
overrides->client_ctx = h2o_context_get_handler_context(req->conn->ctx, &self->super);
/* determine the scheme and authority */
if (self->config.preserve_host) {
scheme = req->scheme;
authority = &req->authority;
} else {
scheme = self->upstream.scheme;
authority = &self->upstream.authority;
}
/* request reprocess */
h2o_reprocess_request(req, req->method, scheme, *authority,
h2o_build_destination(req, self->upstream.path.base, self->upstream.path.len, 0), overrides, 0);
return 0;
}
static void on_context_init(h2o_handler_t *_self, h2o_context_t *ctx)
{
struct rp_handler_t *self = (void *)_self;
/* use the loop of first context for handling socketpool timeouts */
if (self->sockpool != NULL && self->sockpool->timeout == UINT64_MAX)
h2o_socketpool_set_timeout(self->sockpool, ctx->loop, self->config.keepalive_timeout);
/* setup a specific client context only if we need to */
if (ctx->globalconf->proxy.io_timeout == self->config.io_timeout && !self->config.websocket.enabled &&
self->config.ssl_ctx == ctx->globalconf->proxy.ssl_ctx)
return;
h2o_http1client_ctx_t *client_ctx = h2o_mem_alloc(sizeof(*ctx));
client_ctx->loop = ctx->loop;
client_ctx->getaddr_receiver = &ctx->receivers.hostinfo_getaddr;
if (ctx->globalconf->proxy.io_timeout == self->config.io_timeout) {
client_ctx->io_timeout = &ctx->proxy.io_timeout;
} else {
client_ctx->io_timeout = h2o_mem_alloc(sizeof(*client_ctx->io_timeout));
h2o_timeout_init(client_ctx->loop, client_ctx->io_timeout, self->config.io_timeout);
}
if (self->config.websocket.enabled) {
/* FIXME avoid creating h2o_timeout_t for every path-level context in case the timeout values are the same */
client_ctx->websocket_timeout = h2o_mem_alloc(sizeof(*client_ctx->websocket_timeout));
h2o_timeout_init(client_ctx->loop, client_ctx->websocket_timeout, self->config.websocket.timeout);
} else {
client_ctx->websocket_timeout = NULL;
}
client_ctx->ssl_ctx = self->config.ssl_ctx;
h2o_context_set_handler_context(ctx, &self->super, client_ctx);
}
static void on_context_dispose(h2o_handler_t *_self, h2o_context_t *ctx)
{
struct rp_handler_t *self = (void *)_self;
h2o_http1client_ctx_t *client_ctx = h2o_context_get_handler_context(ctx, &self->super);
if (client_ctx == NULL)
return;
if (client_ctx->io_timeout != &ctx->proxy.io_timeout) {
h2o_timeout_dispose(client_ctx->loop, client_ctx->io_timeout);
free(client_ctx->io_timeout);
}
if (client_ctx->websocket_timeout != NULL) {
h2o_timeout_dispose(client_ctx->loop, client_ctx->websocket_timeout);
free(client_ctx->websocket_timeout);
}
free(client_ctx);
}
static void on_handler_dispose(h2o_handler_t *_self)
{
struct rp_handler_t *self = (void *)_self;
if (self->config.ssl_ctx != NULL)
SSL_CTX_free(self->config.ssl_ctx);
free(self->upstream.host.base);
free(self->upstream.path.base);
if (self->sockpool != NULL) {
h2o_socketpool_dispose(self->sockpool);
free(self->sockpool);
}
}
void h2o_proxy_register_reverse_proxy(h2o_pathconf_t *pathconf, h2o_url_t *upstream, h2o_proxy_config_vars_t *config)
{
struct rp_handler_t *self = (void *)h2o_create_handler(pathconf, sizeof(*self));
self->super.on_context_init = on_context_init;
self->super.on_context_dispose = on_context_dispose;
self->super.dispose = on_handler_dispose;
self->super.on_req = on_req;
if (config->keepalive_timeout != 0) {
self->sockpool = h2o_mem_alloc(sizeof(*self->sockpool));
struct sockaddr_un sa;
const char *to_sa_err;
int is_ssl = upstream->scheme == &H2O_URL_SCHEME_HTTPS;
if ((to_sa_err = h2o_url_host_to_sun(upstream->host, &sa)) == h2o_url_host_to_sun_err_is_not_unix_socket) {
h2o_socketpool_init_by_hostport(self->sockpool, upstream->host, h2o_url_get_port(upstream), is_ssl,
SIZE_MAX /* FIXME */);
} else {
assert(to_sa_err == NULL);
h2o_socketpool_init_by_address(self->sockpool, (void *)&sa, sizeof(sa), is_ssl, SIZE_MAX /* FIXME */);
}
}
h2o_url_copy(NULL, &self->upstream, upstream);
h2o_strtolower(self->upstream.host.base, self->upstream.host.len);
self->config = *config;
if (self->config.ssl_ctx != NULL)
SSL_CTX_up_ref(self->config.ssl_ctx);
}
| 1 | 11,802 | Could we just set the list of header modification commands to `req->overrides` and apply them only when the request is sent upstream in lib/core/proxy.c? The reason I ask is because an upstream server (accessed using the modified headers) might return 399. In such case, the request would be delegated to the next handler. I think that the headers of the original request should be passed to the next handler, since per my understanding the intended behavior of `proxy.header.*` is to modify the headers passed to the upstream server only. | h2o-h2o | c |
@@ -214,6 +214,12 @@ type Table struct {
// to top-level chains.
insertMode string
+ // Record when we did our most recent updates and refreshes of the table. We use these to
+ // calculate the next time we should force a refresh.
+ lastUpdateTime time.Time
+ lastRefreshTime time.Time
+ refreshInterval time.Duration
+
logCxt *log.Entry
gaugeNumChains prometheus.Gauge | 1 | // Copyright (c) 2016-2017 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package iptables
import (
"bytes"
"fmt"
"reflect"
"regexp"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
"github.com/projectcalico/felix/set"
)
const (
MaxChainNameLength = 28
)
var (
// List of all the top-level kernel-created chains by iptables table.
tableToKernelChains = map[string][]string{
"filter": []string{"INPUT", "FORWARD", "OUTPUT"},
"nat": []string{"PREROUTING", "INPUT", "OUTPUT", "POSTROUTING"},
"mangle": []string{"PREROUTING", "INPUT", "FORWARD", "OUTPUT", "POSTROUTING"},
"raw": []string{"PREROUTING", "OUTPUT"},
}
// chainCreateRegexp matches iptables-save output lines for chain forward reference lines.
// It captures the name of the chain.
chainCreateRegexp = regexp.MustCompile(`^:(\S+)`)
// appendRegexp matches an iptables-save output line for an append operation.
appendRegexp = regexp.MustCompile(`^-A (\S+)`)
// Prometheus metrics.
countNumRestoreCalls = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_restore_calls",
Help: "Number of iptables-restore calls.",
})
countNumRestoreErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_restore_errors",
Help: "Number of iptables-restore errors.",
})
countNumSaveCalls = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_save_calls",
Help: "Number of iptables-save calls.",
})
countNumSaveErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_save_errors",
Help: "Number of iptables-save errors.",
})
gaugeNumChains = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "felix_iptables_chains",
Help: "Number of active iptables chains.",
}, []string{"ip_version", "table"})
gaugeNumRules = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "felix_iptables_rules",
Help: "Number of active iptables rules.",
}, []string{"ip_version", "table"})
countNumLinesExecuted = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "felix_iptables_lines_executed",
Help: "Number of iptables rule updates executed.",
}, []string{"ip_version", "table"})
)
func init() {
prometheus.MustRegister(countNumRestoreCalls)
prometheus.MustRegister(countNumRestoreErrors)
prometheus.MustRegister(countNumSaveCalls)
prometheus.MustRegister(countNumSaveErrors)
prometheus.MustRegister(gaugeNumChains)
prometheus.MustRegister(gaugeNumRules)
prometheus.MustRegister(countNumLinesExecuted)
}
// Table represents a single one of the iptables tables i.e. "raw", "nat", "filter", etc. It
// caches the desired state of that table, then attempts to bring it into sync when Apply() is
// called.
//
// API Model
//
// Table supports two classes of operation: "rule insertions" and "full chain updates".
//
// As the name suggests, rule insertions allow for inserting one or more rules into a pre-existing
// chain. Rule insertions are intended to be used to hook kernel chains (such as "FORWARD") in
// order to direct them to a Felix-owned chain. It is important to minimise the use of rule
// insertions because the top-level chains are shared resources, which can be modified by other
// applications. In addition, rule insertions are harder to clean up after an upgrade to a new
// version of Felix (because we need a way to recognise our rules in a crowded chain).
//
// Full chain updates replace the entire contents of a Felix-owned chain with a new set of rules.
// Limiting the operation to "replace whole chain" in this way significantly simplifies the API.
// Although the API operates on full chains, the dataplane write logic tries to avoid rewriting
// a whole chain if only part of it has changed (this was not the case in Felix 1.4). This
// prevents iptables counters from being reset unnecessarily.
//
// In either case, the actual dataplane updates are deferred until the next call to Apply() so
// chain updates and insertions may occur in any order as long as they are consistent (i.e. there
// are no references to non-existent chains) by the time Apply() is called.
//
// Design
//
// We had several goals in designing the iptables machinery in 2.0.0:
//
// (1) High performance. Felix needs to handle high churn of endpoints and rules.
//
// (2) Ability to restore rules, even if other applications accidentally break them: we found that
// other applications sometimes misuse iptables-save and iptables-restore to do a read, modify,
// write cycle. That behaviour is not safe under concurrent modification.
//
// (3) Avoid rewriting rules that haven't changed so that we don't reset iptables counters.
//
// (4) Avoid parsing iptables commands (for example, the output from iptables/iptables-save).
// This is very hard to do robustly because iptables rules do not necessarily round-trip through
// the kernel in the same form. In addition, the format could easily change due to changes or
// fixes in the iptables/iptables-save command.
//
// (5) Support for graceful restart. I.e. deferring potentially incorrect updates until we're
// in-sync with the datastore. For example, if we have 100 endpoints on a host, after a restart
// we don't want to write a "dispatch" chain when we learn about the first endpoint (possibly
// replacing an existing one that had all 100 endpoints in place and causing traffic to glitch);
// instead, we want to defer until we've seen all 100 and then do the write.
//
// (6) Improved handling of rule inserts vs Felix 1.4.x. Previous versions of Felix sometimes
// inserted special-case rules that were not marked as Calico rules in any sensible way making
// cleanup of those rules after an upgrade difficult.
//
// Implementation
//
// For high performance (goal 1), we use iptables-restore to do bulk updates to iptables. This is
// much faster than individual iptables calls.
//
// To allow us to restore rules after they are clobbered by another process (goal 2), we cache
// them at this layer. This means that we don't need a mechanism to ask the other layers of Felix
// to do a resync. Note: Table doesn't start a thread of its own so it relies on the main event
// loop to trigger any dataplane resync polls.
//
// There is tension between goals 3 and 4. In order to avoid full rewrites (goal 3), we need to
// know what rules are in place, but we also don't want to parse them to find out (goal 4)! As
// a compromise, we deterministically calculate an ID for each rule and store it in an iptables
// comment. Then, when we want to know what rules are in place, we _do_ parse the output from
// iptables-save, but only to read back the rule IDs. That limits the amount of parsing we need
// to do and keeps it manageable/robust.
//
// To support graceful restart (goal 5), we defer updates to the dataplane until Apply() is called,
// then we do an atomic update using iptables-restore. As long as the first Apply() call is
// after we're in sync, the dataplane won't be touched until the right time. Felix 1.4.x had a
// more complex mechanism to support partial updates during the graceful restart period but
// Felix 2.0.0 resyncs so quickly that the added complexity is not justified.
//
// To make it easier to manage rule insertions (goal 6), we add rule IDs to those too. With
// rule IDs in place, we can easily distinguish Calico rules from non-Calico rules without needing
// to know exactly which rules to expect. To deal with cleanup after upgrade from older versions
// that did not write rule IDs, we support special-case regexes to detect our old rules.
//
// Thread safety
//
// Table doesn't do any internal synchronization, its methods should only be called from one
// thread. To avoid conflicts in the dataplane itself, there should only be one instance of
// Table for each iptable table in an application.
type Table struct {
Name string
IPVersion uint8
// chainToInsertedRules maps from chain name to a list of rules to be inserted at the start
// of that chain. Rules are written with rule hash comments. The Table cleans up inserted
// rules with unknown hashes.
chainToInsertedRules map[string][]Rule
dirtyInserts set.Set
// chainToRuleFragments contains the desired state of our iptables chains, indexed by
// chain name. The values are slices of iptables fragments, such as
// "--match foo --jump DROP" (i.e. omitting the action and chain name, which are calculated
// as needed).
chainNameToChain map[string]*Chain
dirtyChains set.Set
inSyncWithDataPlane bool
// chainToDataplaneHashes contains the rule hashes that we think are in the dataplane.
// it is updated when we write to the dataplane but it can also be read back and compared
// to what we calculate from chainToContents.
chainToDataplaneHashes map[string][]string
// hashCommentPrefix holds the prefix that we prepend to our rule-tracking hashes.
hashCommentPrefix string
// hashCommentRegexp matches the rule-tracking comment, capturing the rule hash.
hashCommentRegexp *regexp.Regexp
// ourChainsRegexp matches the names of chains that are "ours", i.e. start with one of our
// prefixes.
ourChainsRegexp *regexp.Regexp
// oldInsertRegexp matches inserted rules from old pre rule-hash versions of felix.
oldInsertRegexp *regexp.Regexp
iptablesRestoreCmd string
iptablesSaveCmd string
// insertMode is either "insert" or "append"; whether we insert our rules or append them
// to top-level chains.
insertMode string
logCxt *log.Entry
gaugeNumChains prometheus.Gauge
gaugeNumRules prometheus.Gauge
countNumLinesExecuted prometheus.Counter
// Factory for making commands, used by UTs to shim exec.Command().
newCmd cmdFactory
// sleep is a shim for time.Sleep.
sleep func(d time.Duration)
}
type TableOptions struct {
HistoricChainPrefixes []string
ExtraCleanupRegexPattern string
InsertMode string
// NewCmdOverride for tests, if non-nil, factory to use instead of the real exec.Command()
NewCmdOverride cmdFactory
// SleepOverride for tests, if non-nil, replacement for time.Sleep()
SleepOverride func(d time.Duration)
}
func NewTable(
name string,
ipVersion uint8,
hashPrefix string,
options TableOptions,
) *Table {
// Calculate the regex used to match the hash comment. The comment looks like this:
// --comment "cali:abcd1234_-".
hashCommentRegexp := regexp.MustCompile(`--comment "?` + hashPrefix + `([a-zA-Z0-9_-]+)"?`)
ourChainsPattern := "^(" + strings.Join(options.HistoricChainPrefixes, "|") + ")"
ourChainsRegexp := regexp.MustCompile(ourChainsPattern)
oldInsertRegexpParts := []string{}
for _, prefix := range options.HistoricChainPrefixes {
part := fmt.Sprintf("(?:-j|--jump) %s", prefix)
oldInsertRegexpParts = append(oldInsertRegexpParts, part)
}
if options.ExtraCleanupRegexPattern != "" {
oldInsertRegexpParts = append(oldInsertRegexpParts,
options.ExtraCleanupRegexPattern)
}
oldInsertPattern := strings.Join(oldInsertRegexpParts, "|")
oldInsertRegexp := regexp.MustCompile(oldInsertPattern)
// Pre-populate the insert table with empty lists for each kernel chain. Ensures that we
// clean up any chains that we hooked on a previous run.
inserts := map[string][]Rule{}
dirtyInserts := set.New()
for _, kernelChain := range tableToKernelChains[name] {
inserts[kernelChain] = []Rule{}
dirtyInserts.Add(kernelChain)
}
var insertMode string
switch options.InsertMode {
case "", "insert":
insertMode = "insert"
case "append":
insertMode = "append"
default:
log.WithField("insertMode", options.InsertMode).Panic("Unknown insert mode")
}
// Allow override of exec.Command() and time.Sleep() for test purposes.
newCmd := newRealCmd
if options.NewCmdOverride != nil {
newCmd = options.NewCmdOverride
}
sleep := time.Sleep
if options.SleepOverride != nil {
sleep = options.SleepOverride
}
table := &Table{
Name: name,
IPVersion: ipVersion,
chainToInsertedRules: inserts,
dirtyInserts: dirtyInserts,
chainNameToChain: map[string]*Chain{},
dirtyChains: set.New(),
chainToDataplaneHashes: map[string][]string{},
logCxt: log.WithFields(log.Fields{
"ipVersion": ipVersion,
"table": name,
}),
hashCommentPrefix: hashPrefix,
hashCommentRegexp: hashCommentRegexp,
ourChainsRegexp: ourChainsRegexp,
oldInsertRegexp: oldInsertRegexp,
insertMode: insertMode,
newCmd: newCmd,
sleep: sleep,
gaugeNumChains: gaugeNumChains.WithLabelValues(fmt.Sprintf("%d", ipVersion), name),
gaugeNumRules: gaugeNumRules.WithLabelValues(fmt.Sprintf("%d", ipVersion), name),
countNumLinesExecuted: countNumLinesExecuted.WithLabelValues(fmt.Sprintf("%d", ipVersion), name),
}
if ipVersion == 4 {
table.iptablesRestoreCmd = "iptables-restore"
table.iptablesSaveCmd = "iptables-save"
} else {
table.iptablesRestoreCmd = "ip6tables-restore"
table.iptablesSaveCmd = "ip6tables-save"
}
return table
}
func (t *Table) SetRuleInsertions(chainName string, rules []Rule) {
t.logCxt.WithField("chainName", chainName).Debug("Updating rule insertions")
oldRules := t.chainToInsertedRules[chainName]
t.chainToInsertedRules[chainName] = rules
numRulesDelta := len(rules) - len(oldRules)
t.gaugeNumRules.Add(float64(numRulesDelta))
t.dirtyInserts.Add(chainName)
}
func (t *Table) UpdateChains(chains []*Chain) {
for _, chain := range chains {
t.UpdateChain(chain)
}
}
func (t *Table) UpdateChain(chain *Chain) {
t.logCxt.WithField("chainName", chain.Name).Info("Queueing update of chain.")
oldNumRules := 0
if oldChain := t.chainNameToChain[chain.Name]; oldChain != nil {
oldNumRules = len(oldChain.Rules)
}
t.chainNameToChain[chain.Name] = chain
numRulesDelta := len(chain.Rules) - oldNumRules
t.gaugeNumRules.Add(float64(numRulesDelta))
t.dirtyChains.Add(chain.Name)
}
func (t *Table) RemoveChains(chains []*Chain) {
for _, chain := range chains {
t.RemoveChainByName(chain.Name)
}
}
func (t *Table) RemoveChainByName(name string) {
t.logCxt.WithField("chainName", name).Info("Queing deletion of chain.")
if oldChain, known := t.chainNameToChain[name]; known {
t.gaugeNumRules.Sub(float64(len(oldChain.Rules)))
delete(t.chainNameToChain, name)
t.dirtyChains.Add(name)
}
}
func (t *Table) loadDataplaneState() {
// Load the hashes from the dataplane.
t.logCxt.Info("Scanning for out-of-sync iptables chains")
dataplaneHashes := t.getHashesFromDataplane()
// Check that the rules we think we've programmed are still there and mark any inconsistent
// chains for refresh.
for chainName, expectedHashes := range t.chainToDataplaneHashes {
logCxt := t.logCxt.WithField("chainName", chainName)
if t.dirtyChains.Contains(chainName) || t.dirtyInserts.Contains(chainName) {
// Already an update pending for this chain; no point in flagging it as
// out-of-sync.
logCxt.Debug("Skipping known-dirty chain")
continue
}
dpHashes := dataplaneHashes[chainName]
if !t.ourChainsRegexp.MatchString(chainName) {
// Not one of our chains so it may be one that we're inserting rules into.
// Re-calculate the expected rule insertions based on the current length
// of the chain (since other processes may have inserted/removed rules
// from the chain, throwing off the numbers).
expectedHashes, _ = t.expectedHashesForInsertChain(
chainName,
numEmptyStrings(dpHashes),
)
if !reflect.DeepEqual(dpHashes, expectedHashes) {
logCxt.WithFields(log.Fields{
"expectedRuleIDs": expectedHashes,
"actualRuleIDs": dpHashes,
}).Warn("Detected out-of-sync inserts, marking for resync")
t.dirtyInserts.Add(chainName)
}
} else {
// One of our chains, should match exactly.
if !reflect.DeepEqual(dpHashes, expectedHashes) {
logCxt.Warn("Detected out-of-sync Calico chain, marking for resync")
t.dirtyChains.Add(chainName)
}
}
}
// Now scan for chains that shouldn't be there and mark for deletion.
t.logCxt.Info("Scanning for unexpected iptables chains")
for chainName, dataplaneHashes := range dataplaneHashes {
logCxt := t.logCxt.WithField("chainName", chainName)
if t.dirtyChains.Contains(chainName) || t.dirtyInserts.Contains(chainName) {
// Already an update pending for this chain.
logCxt.Debug("Skipping known-dirty chain")
continue
}
if _, ok := t.chainToDataplaneHashes[chainName]; ok {
// Chain expected, we'll have checked its contents above.
logCxt.Debug("Skipping expected chain")
continue
}
if !t.ourChainsRegexp.MatchString(chainName) {
// Non-calico chain that is not tracked in chainToDataplaneHashes. We
// haven't seen the chain before and we haven't been asked to insert
// anything into it. Check that it doesn't have an rule insertions in it
// from a previous run of Felix.
for _, hash := range dataplaneHashes {
if hash != "" {
logCxt.Info("Found unexpected insert, marking for cleanup")
t.dirtyInserts.Add(chainName)
break
}
}
continue
}
// Chain exists in dataplane but not in memory, mark as dirty so we'll clean it up.
logCxt.Info("Found unexpected chain, marking for cleanup")
t.dirtyChains.Add(chainName)
}
t.logCxt.Info("Done scanning, in sync with dataplane")
t.chainToDataplaneHashes = dataplaneHashes
t.inSyncWithDataPlane = true
}
// expectedHashesForInsertChain calculates the expected hashes for a whole top-level chain
// given our inserts. If we're in append mode, that consists of numNonCalicoRules empty strings
// followed by our hashes; in insert mode, the opposite way round. To avoid recalculation, it
// returns the rule hashes as a second output.
func (t *Table) expectedHashesForInsertChain(
chainName string,
numNonCalicoRules int,
) (allHashes, ourHashes []string) {
insertedRules := t.chainToInsertedRules[chainName]
allHashes = make([]string, len(insertedRules)+numNonCalicoRules)
ourHashes = calculateRuleInsertHashes(chainName, insertedRules)
offset := 0
if t.insertMode == "append" {
log.Debug("In append mode, returning our hashes at end.")
offset = numNonCalicoRules
}
for i, hash := range ourHashes {
allHashes[i+offset] = hash
}
return
}
// getHashesFromDataplane loads the current state of our table and parses out the hashes that we
// add to rules. It returns a map with an entry for each chain in the table. Each entry is a slice
// containing the hashes for the rules in that table. Rules with no hashes are represented by
// an empty string.
func (t *Table) getHashesFromDataplane() map[string][]string {
retries := 3
retryDelay := 100 * time.Millisecond
// Retry a few times before we panic. This deals with any transient errors and it prevents
// us from spamming a panic into the log when we're being gracefully shut down by a SIGTERM.
for {
cmd := t.newCmd(t.iptablesSaveCmd, "-t", t.Name)
countNumSaveCalls.Inc()
output, err := cmd.Output()
if err != nil {
countNumSaveErrors.Inc()
t.logCxt.WithError(err).Warnf("%s command failed", t.iptablesSaveCmd)
if retries > 0 {
retries--
t.sleep(retryDelay)
retryDelay *= 2
} else {
t.logCxt.Panicf("%s command failed after retries", t.iptablesSaveCmd)
}
continue
}
buf := bytes.NewBuffer(output)
return t.getHashesFromBuffer(buf)
}
}
// getHashesFromBuffer parses a buffer containing iptables-save output for this table, extracting
// our rule hashes. Entries in the returned map are indexed by chain name. For rules that we
// wrote, the hash is extracted from a comment that we added to the rule. For rules written by
// previous versions of Felix, returns a dummy non-zero value. For rules not written by Felix,
// returns a zero string. Hence, the lengths of the returned values are the lengths of the chains
// whether written by Felix or not.
func (t *Table) getHashesFromBuffer(buf *bytes.Buffer) map[string][]string {
newHashes := map[string][]string{}
for {
// Read the next line of the output.
line, err := buf.ReadString('\n')
if err != nil { // EOF
break
}
// Look for lines of the form ":chain-name - [0:0]", which are forward declarations
// for (possibly empty) chains.
logCxt := t.logCxt.WithField("line", line)
logCxt.Debug("Parsing line")
captures := chainCreateRegexp.FindStringSubmatch(line)
if captures != nil {
// Chain forward-reference, make sure the chain exists.
chainName := captures[1]
logCxt.WithField("chainName", chainName).Debug("Found forward-reference")
newHashes[chainName] = []string{}
continue
}
// Look for append lines, such as "-A chain-name -m foo --foo bar"; these are the
// actual rules.
captures = appendRegexp.FindStringSubmatch(line)
if captures == nil {
// Skip any non-append lines.
logCxt.Debug("Not an append, skipping")
continue
}
chainName := captures[1]
// Look for one of our hashes on the rule. We record a zero hash for unknown rules
// so that they get cleaned up. Note: we're implicitly capturing the first match
// of the regex. When writing the rules, we ensure that the hash is written as the
// first comment.
hash := ""
captures = t.hashCommentRegexp.FindStringSubmatch(line)
if captures != nil {
hash = captures[1]
logCxt.WithField("hash", hash).Debug("Found hash in rule")
} else if t.oldInsertRegexp.FindString(line) != "" {
logCxt.WithFields(log.Fields{
"rule": line,
"chainName": chainName,
}).Info("Found inserted rule from previous Felix version, marking for cleanup.")
hash = "OLD INSERT RULE"
}
newHashes[chainName] = append(newHashes[chainName], hash)
}
t.logCxt.Debugf("Read hashes from dataplane: %#v", newHashes)
return newHashes
}
func (t *Table) InvalidateDataplaneCache() {
t.inSyncWithDataPlane = false
}
func (t *Table) Apply() {
// Retry until we succeed. There are several reasons that updating iptables may fail:
//
// - A concurrent write may invalidate iptables-restore's compare-and-swap; this manifests
// as a failure on the COMMIT line.
// - Another process may have clobbered some of our state, resulting in inconsistencies
// in what we try to program. This could manifest in a number of ways depending on what
// the other process did.
// - Random transient failure.
//
// It's also possible that we're bugged and trying to write bad data so we give up
// eventually.
retries := 10
backoffTime := 1 * time.Millisecond
failedAtLeastOnce := false
for {
if !t.inSyncWithDataPlane {
// We have reason to believe that our picture of the dataplane is out of
// sync. Refresh it. This may mark more chains as dirty.
t.loadDataplaneState()
}
if err := t.applyUpdates(); err != nil {
if retries > 0 {
retries--
t.logCxt.WithError(err).Warn("Failed to program iptables, will retry")
t.sleep(backoffTime)
backoffTime *= 2
t.logCxt.WithError(err).Warn("Retrying...")
failedAtLeastOnce = true
continue
} else {
t.logCxt.WithError(err).Error("Failed to program iptables, loading diags before panic.")
cmd := t.newCmd(t.iptablesSaveCmd, "-t", t.Name)
output, err2 := cmd.Output()
if err2 != nil {
t.logCxt.WithError(err2).Error("Failed to load iptables state")
} else {
t.logCxt.WithField("iptablesState", string(output)).Error("Current state of iptables")
}
t.logCxt.WithError(err).Panic("Failed to program iptables, giving up after retries")
}
}
if failedAtLeastOnce {
t.logCxt.Warn("Succeeded after retry.")
}
break
}
t.gaugeNumChains.Set(float64(len(t.chainNameToChain)))
}
func (t *Table) applyUpdates() error {
var inputBuf bytes.Buffer
// iptables-restore input starts with a line indicating the table name.
tableNameLine := fmt.Sprintf("*%s\n", t.Name)
inputBuf.WriteString(tableNameLine)
// Make a pass over the dirty chains and generate a forward reference for any that need to
// be created or flushed.
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
chainNeedsToBeFlushed := false
if _, ok := t.chainNameToChain[chainName]; !ok {
// About to delete this chain, flush it first to sever dependencies.
chainNeedsToBeFlushed = true
} else if _, ok := t.chainToDataplaneHashes[chainName]; !ok {
// Chain doesn't exist in dataplane, mark it for creation.
chainNeedsToBeFlushed = true
}
if chainNeedsToBeFlushed {
inputBuf.WriteString(fmt.Sprintf(":%s - -\n", chainName))
t.countNumLinesExecuted.Inc()
}
return nil
})
// Make a second pass over the dirty chains. This time, we write out the rule changes.
newHashes := map[string][]string{}
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
if chain, ok := t.chainNameToChain[chainName]; ok {
// Chain update or creation. Scan the chain against its previous hashes
// and replace/append/delete as appropriate.
previousHashes := t.chainToDataplaneHashes[chainName]
currentHashes := chain.RuleHashes()
newHashes[chainName] = currentHashes
for i := 0; i < len(previousHashes) || i < len(currentHashes); i++ {
var line string
if i < len(previousHashes) && i < len(currentHashes) {
if previousHashes[i] == currentHashes[i] {
continue
}
// Hash doesn't match, replace the rule.
ruleNum := i + 1 // 1-indexed.
prefixFrag := t.commentFrag(currentHashes[i])
line = chain.Rules[i].RenderReplace(chainName, ruleNum, prefixFrag)
} else if i < len(previousHashes) {
// previousHashes was longer, remove the old rules from the end.
ruleNum := len(currentHashes) + 1 // 1-indexed
line = deleteRule(chainName, ruleNum)
} else {
// currentHashes was longer. Append.
prefixFrag := t.commentFrag(currentHashes[i])
line = chain.Rules[i].RenderAppend(chainName, prefixFrag)
}
inputBuf.WriteString(line)
inputBuf.WriteString("\n")
t.countNumLinesExecuted.Inc()
}
}
return nil // Delay clearing the set until we've programmed iptables.
})
// Now calculate iptables updates for our inserted rules, which are used to hook top-level
// chains.
t.dirtyInserts.Iter(func(item interface{}) error {
chainName := item.(string)
previousHashes := t.chainToDataplaneHashes[chainName]
// Calculate the hashes for our inserted rules.
newChainHashes, newRuleHashes := t.expectedHashesForInsertChain(
chainName, numEmptyStrings(previousHashes))
if reflect.DeepEqual(newChainHashes, previousHashes) {
// Chain is in sync, skip to next one.
return nil
}
// For simplicity, if we've discovered that we're out-of-sync, remove all our
// rules from this chain, then re-insert/re-append them below.
//
// Remove in reverse order so that we don't disturb the rule numbers of rules we're
// about to remove.
for i := len(previousHashes) - 1; i >= 0; i-- {
if previousHashes[i] != "" {
ruleNum := i + 1
line := deleteRule(chainName, ruleNum)
inputBuf.WriteString(line)
inputBuf.WriteString("\n")
t.countNumLinesExecuted.Inc()
}
}
rules := t.chainToInsertedRules[chainName]
if t.insertMode == "insert" {
log.Debug("Rendering insert rules.")
// Since each insert is pushed onto the top of the chain, do the inserts in
// reverse order so that they end up in the correct order in the final
// state of the chain.
for i := len(rules) - 1; i >= 0; i-- {
prefixFrag := t.commentFrag(newRuleHashes[i])
line := rules[i].RenderInsert(chainName, prefixFrag)
inputBuf.WriteString(line)
inputBuf.WriteString("\n")
t.countNumLinesExecuted.Inc()
}
} else {
log.Debug("Rendering append rules.")
for i := 0; i < len(rules); i++ {
prefixFrag := t.commentFrag(newRuleHashes[i])
line := rules[i].RenderAppend(chainName, prefixFrag)
inputBuf.WriteString(line)
inputBuf.WriteString("\n")
t.countNumLinesExecuted.Inc()
}
}
newHashes[chainName] = newChainHashes
return nil // Delay clearing the set until we've programmed iptables.
})
// Do deletions at the end. This ensures that we don't try to delete any chains that
// are still referenced (because we'll have removed the references in the modify pass
// above). Note: if a chain is being deleted at the same time as a chain that it refers to
// then we'll issue a create+flush instruction in the very first pass, which will sever the
// references.
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
if _, ok := t.chainNameToChain[chainName]; !ok {
// Chain deletion
inputBuf.WriteString(fmt.Sprintf("--delete-chain %s\n", chainName))
t.countNumLinesExecuted.Inc()
newHashes[chainName] = nil
}
return nil // Delay clearing the set until we've programmed iptables.
})
if inputBuf.Len() > len(tableNameLine) {
// We've figured out that we need to make some changes, finish off the input then
// execute iptables-restore. iptables-restore input ends with a COMMIT.
inputBuf.WriteString("COMMIT\n")
// Annoying to have to copy the buffer here but reading from a buffer is
// destructive so if we want to trace out the contents after a failure, we have to
// take a copy.
input := inputBuf.String()
t.logCxt.WithField("iptablesInput", input).Debug("Writing to iptables")
var outputBuf, errBuf bytes.Buffer
cmd := t.newCmd(t.iptablesRestoreCmd, "--noflush", "--verbose")
cmd.SetStdin(&inputBuf)
cmd.SetStdout(&outputBuf)
cmd.SetStderr(&errBuf)
countNumRestoreCalls.Inc()
err := cmd.Run()
if err != nil {
t.logCxt.WithFields(log.Fields{
"output": outputBuf.String(),
"errorOutput": errBuf.String(),
"error": err,
"input": input,
}).Warn("Failed to execute ip(6)tables-restore command")
t.inSyncWithDataPlane = false
countNumRestoreErrors.Inc()
return err
}
}
// Now we've successfully updated iptables, clear the dirty sets. We do this even if we
// found there was nothing to do above, since we may have found out that a dirty chain
// was actually a no-op update.
t.dirtyChains = set.New()
t.dirtyInserts = set.New()
// Store off the updates.
for chainName, hashes := range newHashes {
if hashes == nil {
delete(t.chainToDataplaneHashes, chainName)
} else {
t.chainToDataplaneHashes[chainName] = hashes
}
}
return nil
}
func (t *Table) commentFrag(hash string) string {
return fmt.Sprintf(`-m comment --comment "%s%s"`, t.hashCommentPrefix, hash)
}
func deleteRule(chainName string, ruleNum int) string {
return fmt.Sprintf("-D %s %d", chainName, ruleNum)
}
func calculateRuleInsertHashes(chainName string, rules []Rule) []string {
chain := Chain{
Name: chainName,
Rules: rules,
}
return (&chain).RuleHashes()
}
func numEmptyStrings(strs []string) int {
count := 0
for _, s := range strs {
if s == "" {
count++
}
}
return count
}
| 1 | 15,090 | Can we rename 'refresh' to 'read' and 'update' to 'write'? Until I had read more of the code below, I couldn't tell the difference between 'update' and 'refresh'. | projectcalico-felix | go |
@@ -76,7 +76,7 @@ export default class VerdaccioProcess implements IServerProcess {
});
this.childFork.on('error', (err) => {
- console.log('error process', err);
+ // console.log('error process', err);
reject([err, this]);
});
| 1 | // @flow
import _ from 'lodash';
import rimRaf from 'rimraf';
import path from 'path';
import {fork} from 'child_process';
import {CREDENTIALS} from '../functional/config.functional';
import {HTTP_STATUS} from '../../src/lib/constants';
import type {IVerdaccioConfig, IServerBridge, IServerProcess} from '../types';
export default class VerdaccioProcess implements IServerProcess {
bridge: IServerBridge;
config: IVerdaccioConfig;
childFork: any;
isDebug: boolean;
silence: boolean;
cleanStore: boolean;
constructor(config: IVerdaccioConfig,
bridge: IServerBridge,
silence: boolean = true,
isDebug: boolean = false,
cleanStore: boolean = true) {
this.config = config;
this.bridge = bridge;
this.silence = silence;
this.isDebug = isDebug;
this.cleanStore = cleanStore;
}
init(verdaccioPath: string = '../../bin/verdaccio'): Promise<any> {
return new Promise((resolve, reject) => {
if(this.cleanStore) {
rimRaf(this.config.storagePath, (err) => {
if (_.isNil(err) === false) {
reject(err);
}
this._start(verdaccioPath, resolve, reject);
});
} else {
this._start(verdaccioPath, resolve, reject);
}
});
}
_start(verdaccioPath: string, resolve: Function, reject: Function) {
const verdaccioRegisterWrap: string = path.join(__dirname, verdaccioPath);
let childOptions = {
silent: this.silence
};
if (this.isDebug) {
const debugPort = parseInt(this.config.port, 10) + 5;
childOptions = Object.assign({}, childOptions, {
execArgv: [`--inspect=${debugPort}`]
});
}
const {configPath, port} = this.config;
// $FlowFixMe
this.childFork = fork(verdaccioRegisterWrap, ['-c', configPath, '-l', port], childOptions);
this.childFork.on('message', (msg) => {
if ('verdaccio_started' in msg) {
this.bridge.debug().status(HTTP_STATUS.OK).then((body) => {
this.bridge.auth(CREDENTIALS.user, CREDENTIALS.password)
.status(HTTP_STATUS.CREATED)
.body_ok(new RegExp(CREDENTIALS.user))
.then(() => {
resolve([this, body.pid]);
}, reject)
}, reject);
}
});
this.childFork.on('error', (err) => {
console.log('error process', err);
reject([err, this]);
});
this.childFork.on('disconnect', (err) => {
reject([err, this]);
});
this.childFork.on('exit', (err) => {
reject([err, this]);
});
}
stop(): void {
return this.childFork.kill('SIGINT');
}
}
| 1 | 18,484 | can we remove it ? | verdaccio-verdaccio | js |
@@ -228,4 +228,17 @@ NAString ComConvertTrafNameToNativeName(
return convertedName;
}
+NABoolean ComTrafReservedColName(
+ const NAString &colName)
+{
+
+ if ((colName == TRAF_SALT_COLNAME) ||
+ (colName == TRAF_SYSKEY_COLNAME))
+ return TRUE;
+ if ((memcmp(colName.data(), TRAF_DIVISION_COLNAME_PREFIX, strlen(TRAF_DIVISION_COLNAME_PREFIX)) == 0) &&
+ (colName.data()[colName.length()-1] == '_'))
+ return TRUE;
+
+ return FALSE;
+} | 1 | /* -*-C++-*-
*****************************************************************************
*
* File: ComMisc.cpp
* Description: Miscellaneous global functions
*
*
* Created: 11/07/09
* Language: C++
*
*
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
*
*
*****************************************************************************
*/
#include "Platform.h"
#include "ComOperators.h"
#include "ComASSERT.h"
#include "ComMisc.h"
#include "ComDistribution.h" // enumToLiteral, literalToEnum, literalAndEnumStruct
#include "CmpSeabaseDDL.h"
// define the enum-to-literal function
#define ComDefXLateE2L(E2L,eType,array) void E2L (const eType e, NAString &l) \
{ NABoolean found; char lit[100]; \
enumToLiteral (array, occurs(array), e, lit, found); \
ComASSERT(found); l = lit; }
// define the literal-to-enum function
#define ComDefXLateL2E(L2E,eType,array) eType L2E(const char * l) \
{ NABoolean found; \
eType result = (eType) literalToEnum (array, occurs(array), l, found); \
ComASSERT(found); \
return result; }
// Define both
#define ComDefXLateFuncs(L2E,E2L,eType,array) ComDefXLateL2E(L2E,eType,array);ComDefXLateE2L(E2L,eType,array)
// systemCatalog: if passed in, is the name of traf system catalog.
// default is TRAFODION.
NABoolean ComIsTrafodionReservedSchema(
const NAString &systemCatalog,
const NAString &catName,
const NAString &schName)
{
if (catName.isNull())
return FALSE;
NAString trafSysCat;
if (NOT systemCatalog.isNull())
trafSysCat = systemCatalog;
else
trafSysCat = TRAFODION_SYSCAT_LIT;
if ((catName == trafSysCat) &&
(
(schName == SEABASE_DTM_SCHEMA) ||
(schName == SEABASE_MD_SCHEMA) ||
(schName == SEABASE_PRIVMGR_SCHEMA) ||
(schName == SEABASE_REPOS_SCHEMA) ||
(schName == SEABASE_UDF_SCHEMA)
)
)
return TRUE;
return FALSE;
}
// schema names of pattern "_%_" are reserved for internal system schemas.
NABoolean ComIsTrafodionReservedSchemaName(
const NAString &schName)
{
if ((schName.data()[0] == '_') &&
(schName.data()[schName.length()-1] == '_'))
return TRUE;
return FALSE;
}
// schema names of pattern "_HV_ ... _" and "_HB_ ... _" are reserved to store
// external hive and hbase tables
NABoolean ComIsTrafodionExternalSchemaName (
const NAString &schName)
{
Int32 len (schName.length());
// check for HIVE
Int32 prefixLen = sizeof(HIVE_EXT_SCHEMA_PREFIX);
if (len > prefixLen &&
(schName(0,prefixLen-1) == HIVE_EXT_SCHEMA_PREFIX &&
schName(len-1) == '_' ))
return TRUE;
// check for HBASE
prefixLen = sizeof(HBASE_EXT_SCHEMA_PREFIX);
if (len > prefixLen &&
(schName(0,prefixLen-1) == HBASE_EXT_SCHEMA_PREFIX &&
schName(len-1) == '_' ))
return TRUE;
return FALSE;
}
// ----------------------------------------------------------------------------
// function: ComConvertNativeNameToTrafName
//
// this function converts the native HIVE or HBASE object name into its
// Trafodion external name format.
//
// params:
// catalogName - catalog name to identify HBASE or HIVE native table
// schemaName - external name of the HBASE or HIVE schema
// objectName - external name of the HBASE of HIVE table
//
// If it is not HIVE or HBASE, just return the qualified name
// ----------------------------------------------------------------------------
NAString ComConvertNativeNameToTrafName (
const NAString &catalogName,
const NAString &schemaName,
const NAString &objectName)
{
// generate new schema name
NAString tempSchemaName;
if (catalogName == HIVE_SYSTEM_CATALOG)
tempSchemaName += HIVE_EXT_SCHEMA_PREFIX;
else if(catalogName == HBASE_SYSTEM_CATALOG)
tempSchemaName += HBASE_EXT_SCHEMA_PREFIX;
else
return catalogName + NAString(".") +
schemaName + NAString(".") +
objectName;
ComAnsiNamePart externalAnsiName(schemaName, ComAnsiNamePart::EXTERNAL_FORMAT);
tempSchemaName += externalAnsiName.getInternalName();
tempSchemaName.append ("_");
// Catalog name is "TRAFODION"
NAString convertedName (CmpSeabaseDDL::getSystemCatalogStatic());
convertedName += ".";
// append transformed schema name, convert internal name to external format
ComAnsiNamePart internalAnsiName(tempSchemaName, ComAnsiNamePart::INTERNAL_FORMAT);
convertedName += internalAnsiName.getExternalName();
// object name is appended without change
convertedName += NAString(".") + objectName;
return convertedName;
}
// ----------------------------------------------------------------------------
// function: ComConvertTrafNameToNativeName
//
// this function converts the Trafodion external table name
// into its native name format. Both names are in external format.
//
// Example: TRAFODION."_HV_HIVE_".abc becomes HIVE.HIVE.abc
//
// params:
// catalogName - catalog name of the external table
// schemaName - schema name of the extenal table
// objectName - object name of the external table
//
// ----------------------------------------------------------------------------
NAString ComConvertTrafNameToNativeName(
const NAString &catalogName,
const NAString &schemaName,
const NAString &objectName)
{
NAString tempSchemaName;
ComAnsiNamePart externalAnsiSchemaName(schemaName, ComAnsiNamePart::EXTERNAL_FORMAT);
tempSchemaName += externalAnsiSchemaName.getInternalName();
NAString tempCatalogName;
NASubString prefix = tempSchemaName.subString(HIVE_EXT_SCHEMA_PREFIX, 0);
if ( prefix.length() > 0 ) {
tempSchemaName.remove(0, prefix.length());
tempSchemaName.remove(tempSchemaName.length()-1, 1); // remove the trailing "_"
tempCatalogName = HIVE_SYSTEM_CATALOG;
} else {
// do not reuse prefix here because it becomes immutable after the above
// subString() call.
NASubString prefix2 = tempSchemaName.subString(HBASE_EXT_SCHEMA_PREFIX, 0);
if ( prefix2.length() > 0 ) {
tempSchemaName.remove(0, prefix2.length());;
tempSchemaName.remove(tempSchemaName.length()-1, 1); // remove the trailing "_"
tempCatalogName = HBASE_SYSTEM_CATALOG;
}
}
NAString convertedName;
ComAnsiNamePart internalAnsiCatalogName(tempCatalogName, ComAnsiNamePart::INTERNAL_FORMAT);
convertedName += internalAnsiCatalogName.getExternalName();
convertedName += ".";
ComAnsiNamePart internalAnsiSchemaName(tempSchemaName, ComAnsiNamePart::INTERNAL_FORMAT);
convertedName += internalAnsiSchemaName.getExternalName();
convertedName += ".";
convertedName += objectName;
return convertedName;
}
| 1 | 10,932 | I take it that by the time we get here, colName has already been case-shifted to upper case? | apache-trafodion | cpp |
@@ -126,11 +126,14 @@ func ResponseHeaders(h *map[string]string) CallOption {
return CallOption{func(o *OutboundCall) { o.responseHeaders = h }}
}
-// TODO(abg): Example tests to document the different options
-
-// WithHeader adds a new header to the request.
+// WithHeader adds a new header to the request. Header keys are case
+// insensitive.
+//
+// _, err := client.GetValue(ctx, reqBody, yarpc.WithHeader("Token", "10"))
+// // ==> {"token": "10"}
//
-// resBody, err := client.GetValue(ctx, reqBody, yarpc.WithHeader("Token", "10"))
+// If multiple entries have the same normalized header name, newer entries
+// override older ones.
func WithHeader(k, v string) CallOption {
return CallOption{func(o *OutboundCall) {
o.headers = append(o.headers, keyValuePair{k: k, v: v}) | 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 yarpc
import (
"context"
"errors"
"sort"
"go.uber.org/yarpc/api/transport"
)
type keyValuePair struct{ k, v string }
// CallOption defines options that may be passed in at call sites to other
// services.
//
// These may be used to add or alter the request.
type CallOption struct{ apply func(*OutboundCall) }
// OutboundCall is an outgoing call. It holds per-call options for a request.
//
// Encoding authors may use OutboundCall to provide a CallOption-based request
// customization mechanism, including returning response headers through
// ResponseHeaders.
type OutboundCall struct {
// request attributes to fill if non-nil
headers []keyValuePair
shardKey *string
routingKey *string
routingDelegate *string
// If non-nil, response headers should be written here.
responseHeaders *map[string]string
}
// NewOutboundCall constructs a new OutboundCall with the given options.
func NewOutboundCall(options ...CallOption) *OutboundCall {
var call OutboundCall
for _, opt := range options {
opt.apply(&call)
}
return &call
}
// WriteToRequest fills the given request with request-specific options from
// the call.
//
// The context MAY be replaced by the OutboundCall.
func (c *OutboundCall) WriteToRequest(ctx context.Context, req *transport.Request) (context.Context, error) {
for _, h := range c.headers {
req.Headers = req.Headers.With(h.k, h.v)
}
if c.shardKey != nil {
req.ShardKey = *c.shardKey
}
if c.routingKey != nil {
req.RoutingKey = *c.routingKey
}
if c.routingDelegate != nil {
req.RoutingDelegate = *c.routingDelegate
}
// NB(abg): context and error are unused for now but we want to leave room
// for CallOptions which can fail or modify the context.
return ctx, nil
}
// ReadFromResponse reads information from the response for this call.
//
// This should be called only if the request is unary.
func (c *OutboundCall) ReadFromResponse(ctx context.Context, res *transport.Response) (context.Context, error) {
// We're not using ctx right now but we may in the future.
if c.responseHeaders != nil && res.Headers.Len() > 0 {
// We make a copy of the response headers because Headers.Items() must
// never be mutated.
headers := make(map[string]string, res.Headers.Len())
for k, v := range res.Headers.Items() {
headers[k] = v
}
*c.responseHeaders = headers
}
// NB(abg): context and error are unused for now but we want to leave room
// for CallOptions which can fail or modify the context.
return ctx, nil
}
// ResponseHeaders specifies that headers received in response to this request
// should replace the given map.
//
// Header keys in the map are normalized using the CanonicalizeHeaderKey
// function.
//
// var resHeaders map[string]string
// resBody, err := client.SetValue(ctx, key, value, yarpc.ResponseHeaders(&resHeaders))
// value, ok := resHeaders[yarpc.CanonicalizeHeaderKey("foo")]
//
// Note that the map is replaced completely. Entries it had before making the
// call will not be available afterwards.
//
// headers := map[string]string{"hello": "world"}
// resBody, err := client.SetValue(ctx, key, value, yarpc.ResponseHeaders(&headers))
// _, ok := headers["hello"]
// fmt.Println(ok) // false
func ResponseHeaders(h *map[string]string) CallOption {
return CallOption{func(o *OutboundCall) { o.responseHeaders = h }}
}
// TODO(abg): Example tests to document the different options
// WithHeader adds a new header to the request.
//
// resBody, err := client.GetValue(ctx, reqBody, yarpc.WithHeader("Token", "10"))
func WithHeader(k, v string) CallOption {
return CallOption{func(o *OutboundCall) {
o.headers = append(o.headers, keyValuePair{k: k, v: v})
}}
}
// WithShardKey sets the shard key for the request.
func WithShardKey(sk string) CallOption {
return CallOption{func(o *OutboundCall) { o.shardKey = &sk }}
}
// WithRoutingKey sets the routing key for the request.
func WithRoutingKey(rk string) CallOption {
return CallOption{func(o *OutboundCall) { o.routingKey = &rk }}
}
// WithRoutingDelegate sets the routing delegate for the request.
func WithRoutingDelegate(rd string) CallOption {
return CallOption{func(o *OutboundCall) { o.routingDelegate = &rd }}
}
// InboundCall holds information about the inbound call and its response.
//
// Encoding authors may use InboundCall to provide information about the
// incoming request on the Context and send response headers through
// WriteResponseHeader.
type InboundCall struct {
resHeaders []keyValuePair
req *transport.Request
}
type inboundCallKey struct{} // context key for *InboundCall
// NewInboundCall builds a new InboundCall with the given context.
//
// A request context is returned and must be used in place of the original.
func NewInboundCall(ctx context.Context) (context.Context, *InboundCall) {
call := &InboundCall{}
return context.WithValue(ctx, inboundCallKey{}, call), call
}
// getInboundCall returns the inbound call on this context or nil.
func getInboundCall(ctx context.Context) (*InboundCall, bool) {
call, ok := ctx.Value(inboundCallKey{}).(*InboundCall)
return call, ok
}
// ReadFromRequest reads information from the given request.
//
// This information may be queried on the context using functions like Caller,
// Service, Procedure, etc.
func (ic *InboundCall) ReadFromRequest(req *transport.Request) error {
// TODO(abg): Maybe we should copy attributes over so that changes to the
// Request don't change the output.
ic.req = req
return nil
}
// WriteToResponse writes response information from the InboundCall onto the
// given ResponseWriter.
//
// If used, this must be called before writing the response body to the
// ResponseWriter.
func (ic *InboundCall) WriteToResponse(resw transport.ResponseWriter) error {
var headers transport.Headers
for _, h := range ic.resHeaders {
headers = headers.With(h.k, h.v)
}
if headers.Len() > 0 {
resw.AddHeaders(headers)
}
return nil
}
// Call provides information about the current request inside handlers.
type Call struct{ ic *InboundCall }
// CallFromContext retrieves information about the current incoming request
// from the given context. Returns nil if the context is not a valid request
// context.
//
// The object is valid only as long as the request is ongoing.
func CallFromContext(ctx context.Context) *Call {
if ic, ok := getInboundCall(ctx); ok {
return &Call{ic}
}
return nil
}
// WriteResponseHeader writes headers to the response of this call.
func (c *Call) WriteResponseHeader(k, v string) error {
if c == nil {
return errors.New(
"failed to write response header: " +
"Call was nil, make sure CallFromContext was called with a request context")
}
c.ic.resHeaders = append(c.ic.resHeaders, keyValuePair{k: k, v: v})
return nil
}
// Caller returns the name of the service making this request.
func (c *Call) Caller() string {
if c == nil {
return ""
}
return c.ic.req.Caller
}
// Service returns the name of the service being called.
func (c *Call) Service() string {
if c == nil {
return ""
}
return c.ic.req.Service
}
// Procedure returns the name of the procedure being called.
func (c *Call) Procedure() string {
if c == nil {
return ""
}
return c.ic.req.Procedure
}
// Encoding returns the encoding for this request.
func (c *Call) Encoding() transport.Encoding {
if c == nil {
return ""
}
return c.ic.req.Encoding
}
// Header returns the value of the given request header provided with the
// request.
func (c *Call) Header(k string) string {
if c == nil {
return ""
}
if v, ok := c.ic.req.Headers.Get(k); ok {
return v
}
return ""
}
// HeaderNames returns a sorted list of the names of user defined headers
// provided with this request.
func (c *Call) HeaderNames() []string {
if c == nil {
return nil
}
var names []string
for k := range c.ic.req.Headers.Items() {
names = append(names, k)
}
sort.Strings(names)
return names
}
// ShardKey returns the shard key for this request.
func (c *Call) ShardKey() string {
if c == nil {
return ""
}
return c.ic.req.ShardKey
}
// RoutingKey returns the routing key for this request.
func (c *Call) RoutingKey() string {
if c == nil {
return ""
}
return c.ic.req.RoutingKey
}
// RoutingDelegate returns the routing delegate for this request.
func (c *Call) RoutingDelegate() string {
if c == nil {
return ""
}
return c.ic.req.RoutingDelegate
}
| 1 | 12,063 | Super clear desc - thx. | yarpc-yarpc-go | go |
@@ -3551,7 +3551,11 @@ void SwiftASTContext::LoadModule(swift::ModuleDecl *swift_module,
all_dlopen_errors.GetData());
};
- swift_module->collectLinkLibraries(addLinkLibrary);
+ swift_module->forAllVisibleModules(
+ {}, [&](swift::ModuleDecl::ImportedModule import) {
+ import.second->collectLinkLibraries(addLinkLibrary);
+ return true;
+ });
error = current_error;
}
| 1 | //===-- SwiftASTContext.cpp -------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "lldb/Symbol/SwiftASTContext.h"
// C++ Includes
#include <mutex> // std::once
#include <queue>
#include <set>
#include <sstream>
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/DebuggerClient.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/SearchPathOptions.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/Type.h"
#include "swift/AST/Types.h"
#include "swift/ASTSectionImporter/ASTSectionImporter.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/PrimarySpecificPaths.h"
#include "swift/Basic/SourceManager.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangImporterOptions.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Driver/Util.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/Utils.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Driver/Driver.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "swift/../../lib/IRGen/FixedTypeInfo.h"
#include "swift/../../lib/IRGen/GenEnum.h"
#include "swift/../../lib/IRGen/GenHeap.h"
#include "swift/../../lib/IRGen/IRGenModule.h"
#include "swift/../../lib/IRGen/TypeInfo.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "Plugins/ExpressionParser/Swift/SwiftDiagnostic.h"
#include "Plugins/ExpressionParser/Swift/SwiftUserExpression.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/DumpDataExtractor.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/ThreadSafeDenseMap.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/StringConvert.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/CleanUp.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "Plugins/Platform/MacOSX/PlatformDarwin.h"
#include "Plugins/SymbolFile/DWARF/DWARFASTParserSwift.h"
#define VALID_OR_RETURN(value) \
do { \
if (HasFatalErrors()) { \
return (value); \
} \
} while (0)
#define VALID_OR_RETURN_VOID() \
do { \
if (HasFatalErrors()) { \
return; \
} \
} while (0)
using namespace lldb;
using namespace lldb_private;
typedef lldb_private::ThreadSafeDenseMap<swift::ASTContext *, SwiftASTContext *>
ThreadSafeSwiftASTMap;
static ThreadSafeSwiftASTMap &GetASTMap() {
// The global destructor list will tear down all of the modules when the LLDB
// shared library is being unloaded and this needs to live beyond all of those
// and not be destructed before they have all gone away. So we will leak this
// list intentionally so we can avoid global destructor problems.
static ThreadSafeSwiftASTMap *g_map_ptr = NULL;
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_map_ptr = new ThreadSafeSwiftASTMap(); // NOTE: Intentional leak
});
return *g_map_ptr;
}
static inline swift::Type GetSwiftType(void *opaque_ptr) {
return swift::Type((swift::TypeBase *)opaque_ptr);
}
static inline swift::CanType GetCanonicalSwiftType(void *opaque_ptr) {
return ((swift::TypeBase *)opaque_ptr)->getCanonicalType();
}
static inline swift::Type GetSwiftType(CompilerType type) {
return swift::Type((swift::TypeBase *)type.GetOpaqueQualType());
}
static inline swift::CanType GetCanonicalSwiftType(CompilerType type) {
return ((swift::TypeBase *)type.GetOpaqueQualType())->getCanonicalType();
}
class SwiftEnumDescriptor;
typedef std::shared_ptr<SwiftEnumDescriptor> SwiftEnumDescriptorSP;
typedef llvm::DenseMap<lldb::opaque_compiler_type_t, SwiftEnumDescriptorSP>
EnumInfoCache;
typedef std::shared_ptr<EnumInfoCache> EnumInfoCacheSP;
typedef llvm::DenseMap<const swift::ASTContext *, EnumInfoCacheSP>
ASTEnumInfoCacheMap;
static EnumInfoCache *GetEnumInfoCache(const swift::ASTContext *a) {
static ASTEnumInfoCacheMap g_cache;
static std::mutex g_mutex;
std::lock_guard<std::mutex> locker(g_mutex);
ASTEnumInfoCacheMap::iterator pos = g_cache.find(a);
if (pos == g_cache.end()) {
g_cache.insert(
std::make_pair(a, std::shared_ptr<EnumInfoCache>(new EnumInfoCache())));
return g_cache.find(a)->second.get();
}
return pos->second.get();
}
namespace {
bool IsDirectory(const FileSpec &spec) {
return llvm::sys::fs::is_directory(spec.GetPath());
}
bool IsRegularFile(const FileSpec &spec) {
return llvm::sys::fs::is_regular_file(spec.GetPath());
}
}
llvm::LLVMContext &SwiftASTContext::GetGlobalLLVMContext() {
// TODO check with Sean. Do we really want this to be static across
// an LLDB managing multiple Swift processes?
static llvm::LLVMContext s_global_context;
return s_global_context;
}
llvm::ArrayRef<swift::VarDecl *> SwiftASTContext::GetStoredProperties(
swift::NominalTypeDecl *nominal) {
VALID_OR_RETURN(llvm::ArrayRef<swift::VarDecl *>());
// Check whether we already have the stored properties for this
// nominal type.
auto known = m_stored_properties.find(nominal);
if (known != m_stored_properties.end()) return known->second;
// Collect the stored properties from the AST and put them in the
// cache.
auto stored_properties = nominal->getStoredProperties();
auto &stored = m_stored_properties[nominal];
stored = std::vector<swift::VarDecl *>(stored_properties.begin(),
stored_properties.end());
return stored;
}
class SwiftEnumDescriptor {
public:
enum class Kind {
Empty, // no cases in this enum
CStyle, // no cases have payloads
AllPayload, // all cases have payloads
Mixed // some cases have payloads
};
struct ElementInfo {
lldb_private::ConstString name;
CompilerType payload_type;
bool has_payload : 1;
bool is_indirect : 1;
};
Kind GetKind() const { return m_kind; }
ConstString GetTypeName() { return m_type_name; }
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) = 0;
virtual size_t GetNumElements() {
return GetNumElementsWithPayload() + GetNumCStyleElements();
}
virtual size_t GetNumElementsWithPayload() = 0;
virtual size_t GetNumCStyleElements() = 0;
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) = 0;
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) = 0;
virtual ~SwiftEnumDescriptor() = default;
static SwiftEnumDescriptor *CreateDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl);
protected:
SwiftEnumDescriptor(swift::ASTContext *ast, swift::CanType swift_can_type,
swift::EnumDecl *enum_decl, SwiftEnumDescriptor::Kind k)
: m_kind(k), m_type_name() {
if (swift_can_type.getPointer()) {
if (auto nominal = swift_can_type->getAnyNominal()) {
swift::Identifier name(nominal->getName());
if (name.get())
m_type_name.SetCString(name.get());
}
}
}
private:
Kind m_kind;
ConstString m_type_name;
};
class SwiftEmptyEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftEmptyEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::Empty) {}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
return nullptr;
}
virtual size_t GetNumElementsWithPayload() { return 0; }
virtual size_t GetNumCStyleElements() { return 0; }
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
return nullptr;
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
return nullptr;
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::Empty;
}
virtual ~SwiftEmptyEnumDescriptor() = default;
};
namespace std {
template <> struct less<swift::ClusteredBitVector> {
bool operator()(const swift::ClusteredBitVector &lhs,
const swift::ClusteredBitVector &rhs) const {
int iL = lhs.size() - 1;
int iR = rhs.size() - 1;
for (; iL >= 0 && iR >= 0; --iL, --iR) {
bool bL = lhs[iL];
bool bR = rhs[iR];
if (bL and not bR)
return false;
if (bR and not bL)
return true;
}
return false;
}
};
}
static std::string Dump(const swift::ClusteredBitVector &bit_vector) {
std::string buffer;
llvm::raw_string_ostream ostream(buffer);
for (size_t i = 0; i < bit_vector.size(); i++) {
if (bit_vector[i])
ostream << '1';
else
ostream << '0';
if ((i % 4) == 3)
ostream << ' ';
}
ostream.flush();
return buffer;
}
class SwiftCStyleEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftCStyleEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::CStyle),
m_nopayload_elems_bitmask(), m_elements(), m_element_indexes() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("doing C-style enum layout for %s",
GetTypeName().AsCString());
SwiftASTContext *swift_ast_ctx = SwiftASTContext::GetSwiftASTContext(ast);
swift::irgen::IRGenModule &irgen_module = swift_ast_ctx->GetIRGenModule();
const swift::irgen::EnumImplStrategy &enum_impl_strategy =
swift::irgen::getEnumImplStrategy(irgen_module, swift_can_type);
llvm::ArrayRef<swift::irgen::EnumImplStrategy::Element>
elements_with_no_payload =
enum_impl_strategy.getElementsWithNoPayload();
const bool has_payload = false;
const bool is_indirect = false;
uint64_t case_counter = 0;
m_nopayload_elems_bitmask =
enum_impl_strategy.getBitMaskForNoPayloadElements();
if (log)
log->Printf("m_nopayload_elems_bitmask = %s",
Dump(m_nopayload_elems_bitmask).c_str());
for (auto enum_case : elements_with_no_payload) {
ConstString case_name(enum_case.decl->getName().str().data());
swift::ClusteredBitVector case_value =
enum_impl_strategy.getBitPatternForNoPayloadElement(enum_case.decl);
if (log)
log->Printf("case_name = %s, unmasked value = %s",
case_name.AsCString(), Dump(case_value).c_str());
case_value &= m_nopayload_elems_bitmask;
if (log)
log->Printf("case_name = %s, masked value = %s", case_name.AsCString(),
Dump(case_value).c_str());
std::unique_ptr<ElementInfo> elem_info(
new ElementInfo{case_name, CompilerType(), has_payload, is_indirect});
m_element_indexes.emplace(case_counter, elem_info.get());
case_counter++;
m_elements.emplace(case_value, std::move(elem_info));
}
}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf(
"C-style enum - inspecting data to find enum case for type %s",
GetTypeName().AsCString());
swift::ClusteredBitVector current_payload;
lldb::offset_t offset = 0;
for (size_t idx = 0; idx < data.GetByteSize(); idx++) {
uint64_t byte = data.GetU8(&offset);
current_payload.add(8, byte);
}
if (log) {
log->Printf("m_nopayload_elems_bitmask = %s",
Dump(m_nopayload_elems_bitmask).c_str());
log->Printf("current_payload = %s",
Dump(current_payload).c_str());
}
if (current_payload.size() != m_nopayload_elems_bitmask.size()) {
if (log)
log->Printf("sizes don't match; getting out with an error");
return nullptr;
}
current_payload &= m_nopayload_elems_bitmask;
if (log)
log->Printf("masked current_payload = %s",
Dump(current_payload).c_str());
auto iter = m_elements.find(current_payload), end = m_elements.end();
if (iter == end) {
if (log)
log->Printf("bitmask search failed");
return nullptr;
}
if (log)
log->Printf("bitmask search success - found case %s",
iter->second.get()->name.AsCString());
return iter->second.get();
}
virtual size_t GetNumElementsWithPayload() { return 0; }
virtual size_t GetNumCStyleElements() { return m_elements.size(); }
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
return nullptr;
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
if (idx >= m_element_indexes.size())
return nullptr;
return m_element_indexes[idx];
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::CStyle;
}
virtual ~SwiftCStyleEnumDescriptor() = default;
private:
swift::ClusteredBitVector m_nopayload_elems_bitmask;
std::map<swift::ClusteredBitVector, std::unique_ptr<ElementInfo>> m_elements;
std::map<uint64_t, ElementInfo *> m_element_indexes;
};
static CompilerType
GetFunctionArgumentTuple(const CompilerType &compiler_type) {
if (compiler_type.IsValid() &&
llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem())) {
swift::CanType swift_can_type(
GetCanonicalSwiftType(compiler_type.GetOpaqueQualType()));
auto func =
swift::dyn_cast_or_null<swift::AnyFunctionType>(
swift_can_type);
if (func) {
auto input = func.getInput();
// See comment in swift::AnyFunctionType for rationale here:
// A function can take either a tuple or a parentype, but if a parentype
// (i.e. (Foo)), then it will be reduced down to just Foo, so if the input
// is not a tuple, that must mean there is only 1 input.
auto tuple = swift::dyn_cast<swift::TupleType>(input);
if (tuple)
return CompilerType(compiler_type.GetTypeSystem(), tuple);
else
return CompilerType(compiler_type.GetTypeSystem(), input.getPointer());
}
}
return CompilerType();
}
class SwiftAllPayloadEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftAllPayloadEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::AllPayload),
m_tag_bits(), m_elements() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("doing ADT-style enum layout for %s",
GetTypeName().AsCString());
SwiftASTContext *swift_ast_ctx = SwiftASTContext::GetSwiftASTContext(ast);
swift::irgen::IRGenModule &irgen_module = swift_ast_ctx->GetIRGenModule();
const swift::irgen::EnumImplStrategy &enum_impl_strategy =
swift::irgen::getEnumImplStrategy(irgen_module, swift_can_type);
llvm::ArrayRef<swift::irgen::EnumImplStrategy::Element>
elements_with_payload = enum_impl_strategy.getElementsWithPayload();
m_tag_bits = enum_impl_strategy.getTagBitsForPayloads();
if (log)
log->Printf("tag_bits = %s", Dump(m_tag_bits).c_str());
auto module_ctx = enum_decl->getModuleContext();
const bool has_payload = true;
for (auto enum_case : elements_with_payload) {
ConstString case_name(enum_case.decl->getName().str().data());
swift::EnumElementDecl *case_decl = enum_case.decl;
assert(case_decl);
CompilerType case_type(
ast, swift_can_type->getTypeOfMember(module_ctx, case_decl, nullptr)
.getPointer());
case_type = GetFunctionArgumentTuple(case_type.GetFunctionReturnType());
const bool is_indirect = case_decl->isIndirect()
|| case_decl->getParentEnum()->isIndirect();
if (log)
log->Printf("case_name = %s, type = %s, is_indirect = %s",
case_name.AsCString(), case_type.GetTypeName().AsCString(),
is_indirect ? "yes" : "no");
std::unique_ptr<ElementInfo> elem_info(
new ElementInfo{case_name, case_type, has_payload, is_indirect});
m_elements.push_back(std::move(elem_info));
}
}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf(
"ADT-style enum - inspecting data to find enum case for type %s",
GetTypeName().AsCString());
if (m_elements.size() == 0) // no elements, just fail
{
if (log)
log->Printf("enum with no cases. getting out");
return nullptr;
}
if (m_elements.size() == 1) // one element, so it's gotta be it
{
if (log)
log->Printf("enum with one case. getting out easy with %s",
m_elements.front().get()->name.AsCString());
return m_elements.front().get();
}
swift::ClusteredBitVector current_payload;
lldb::offset_t offset = 0;
for (size_t idx = 0; idx < data.GetByteSize(); idx++) {
uint64_t byte = data.GetU8(&offset);
current_payload.add(8, byte);
}
if (log) {
log->Printf("tag_bits = %s", Dump(m_tag_bits).c_str());
log->Printf("current_payload = %s", Dump(current_payload).c_str());
}
if (current_payload.size() != m_tag_bits.size()) {
if (log)
log->Printf("sizes don't match; getting out with an error");
return nullptr;
}
size_t discriminator = 0;
size_t power_of_2 = 1;
auto enumerator = m_tag_bits.enumerateSetBits();
for (llvm::Optional<size_t> next = enumerator.findNext(); next.hasValue();
next = enumerator.findNext()) {
discriminator =
discriminator + (current_payload[next.getValue()] ? power_of_2 : 0);
power_of_2 <<= 1;
}
if (discriminator >= m_elements.size()) // discriminator too large, get out
{
if (log)
log->Printf("discriminator value of %" PRIu64 " too large, getting out",
(uint64_t)discriminator);
return nullptr;
} else {
auto ptr = m_elements[discriminator].get();
if (log) {
if (!ptr)
log->Printf("discriminator value of %" PRIu64
" acceptable, but null case matched - that's bad",
(uint64_t)discriminator);
else
log->Printf("discriminator value of %" PRIu64
" acceptable, case %s matched",
(uint64_t)discriminator, ptr->name.AsCString());
}
return ptr;
}
}
virtual size_t GetNumElementsWithPayload() { return m_elements.size(); }
virtual size_t GetNumCStyleElements() { return 0; }
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
if (idx >= m_elements.size())
return nullptr;
return m_elements[idx].get();
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
return nullptr;
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::AllPayload;
}
virtual ~SwiftAllPayloadEnumDescriptor() = default;
private:
swift::ClusteredBitVector m_tag_bits;
std::vector<std::unique_ptr<ElementInfo>> m_elements;
};
class SwiftMixedEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftMixedEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::Mixed),
m_non_payload_cases(ast, swift_can_type, enum_decl),
m_payload_cases(ast, swift_can_type, enum_decl) {}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
ElementInfo *elem_info = m_non_payload_cases.GetElementFromData(data);
return elem_info ? elem_info : m_payload_cases.GetElementFromData(data);
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::Mixed;
}
virtual size_t GetNumElementsWithPayload() {
return m_payload_cases.GetNumElementsWithPayload();
}
virtual size_t GetNumCStyleElements() {
return m_non_payload_cases.GetNumCStyleElements();
}
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
return m_payload_cases.GetElementWithPayloadAtIndex(idx);
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
return m_non_payload_cases.GetElementWithNoPayloadAtIndex(idx);
}
virtual ~SwiftMixedEnumDescriptor() = default;
private:
SwiftCStyleEnumDescriptor m_non_payload_cases;
SwiftAllPayloadEnumDescriptor m_payload_cases;
};
SwiftEnumDescriptor *
SwiftEnumDescriptor::CreateDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl) {
assert(ast);
assert(enum_decl);
assert(swift_can_type.getPointer());
SwiftASTContext *swift_ast_ctx = SwiftASTContext::GetSwiftASTContext(ast);
assert(swift_ast_ctx);
swift::irgen::IRGenModule &irgen_module = swift_ast_ctx->GetIRGenModule();
const swift::irgen::EnumImplStrategy &enum_impl_strategy =
swift::irgen::getEnumImplStrategy(irgen_module, swift_can_type);
llvm::ArrayRef<swift::irgen::EnumImplStrategy::Element>
elements_with_payload = enum_impl_strategy.getElementsWithPayload();
llvm::ArrayRef<swift::irgen::EnumImplStrategy::Element>
elements_with_no_payload = enum_impl_strategy.getElementsWithNoPayload();
if (elements_with_no_payload.size() == 0) {
// nothing with no payload.. empty or all payloads?
if (elements_with_payload.size() == 0)
return new SwiftEmptyEnumDescriptor(ast, swift_can_type, enum_decl);
else
return new SwiftAllPayloadEnumDescriptor(ast, swift_can_type, enum_decl);
} else {
// something with no payload.. mixed or C-style?
if (elements_with_payload.size() == 0)
return new SwiftCStyleEnumDescriptor(ast, swift_can_type, enum_decl);
else
return new SwiftMixedEnumDescriptor(ast, swift_can_type, enum_decl);
}
}
static SwiftEnumDescriptor *
GetEnumInfoFromEnumDecl(swift::ASTContext *ast, swift::CanType swift_can_type,
swift::EnumDecl *enum_decl) {
return SwiftEnumDescriptor::CreateDescriptor(ast, swift_can_type, enum_decl);
}
SwiftEnumDescriptor *SwiftASTContext::GetCachedEnumInfo(void *type) {
VALID_OR_RETURN(nullptr);
if (type) {
EnumInfoCache *enum_info_cache = GetEnumInfoCache(GetASTContext());
EnumInfoCache::const_iterator pos = enum_info_cache->find(type);
if (pos != enum_info_cache->end())
return pos->second.get();
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
if (!SwiftASTContext::IsFullyRealized(
CompilerType(GetASTContext(), swift_can_type)))
return nullptr;
SwiftEnumDescriptorSP enum_info_sp;
if (auto *enum_type = swift_can_type->getAs<swift::EnumType>()) {
enum_info_sp.reset(GetEnumInfoFromEnumDecl(
GetASTContext(), swift_can_type, enum_type->getDecl()));
} else if (auto *bound_enum_type =
swift_can_type->getAs<swift::BoundGenericEnumType>()) {
enum_info_sp.reset(GetEnumInfoFromEnumDecl(
GetASTContext(), swift_can_type, bound_enum_type->getDecl()));
}
if (enum_info_sp.get())
enum_info_cache->insert(std::make_pair(type, enum_info_sp));
return enum_info_sp.get();
}
return nullptr;
}
namespace {
static inline bool
SwiftASTContextSupportsLanguage(lldb::LanguageType language) {
return language == eLanguageTypeSwift;
}
static bool IsDeviceSupport(const char *path) {
// The old-style check, which we preserve for safety.
if (path && strstr(path, "iOS DeviceSupport"))
return true;
// The new-style check, which should cover more devices.
if (path)
if (const char *Developer_Xcode = strstr(path, "Developer"))
if (const char *DeviceSupport = strstr(Developer_Xcode, "DeviceSupport"))
if (strstr(DeviceSupport, "Symbols"))
return true;
// Don't look in the simulator runtime frameworks either. They either
// duplicate what the SDK has, or for older simulators conflict with them.
if (path && strstr(path, ".simruntime/Contents/Resources/"))
return true;
return false;
}
}
SwiftASTContext::SwiftASTContext(const char *triple, Target *target)
: TypeSystem(TypeSystem::eKindSwift), m_source_manager_ap(),
m_diagnostic_engine_ap(), m_ast_context_ap(), m_ir_gen_module_ap(),
m_compiler_invocation_ap(new swift::CompilerInvocation()),
m_dwarf_ast_parser_ap(), m_scratch_module(NULL), m_sil_module_ap(),
m_serialized_module_loader(NULL), m_clang_importer(NULL),
m_swift_module_cache(), m_mangled_name_to_type_map(),
m_type_to_mangled_name_map(), m_pointer_byte_size(0),
m_pointer_bit_align(0), m_void_function_type(), m_target_wp(),
m_process(NULL), m_platform_sdk_path(), m_resource_dir(),
m_ast_file_data_map(), m_initialized_language_options(false),
m_initialized_search_path_options(false),
m_initialized_clang_importer_options(false),
m_reported_fatal_error(false), m_fatal_errors(), m_negative_type_cache(),
m_extra_type_info_cache(), m_swift_type_map() {
// Set the clang modules cache path.
llvm::SmallString<128> path;
auto props = ModuleList::GetGlobalModuleListProperties();
props.GetClangModulesCachePath().GetPath(path);
m_compiler_invocation_ap->setClangModuleCachePath(path);
if (target)
m_target_wp = target->shared_from_this();
if (triple)
SetTriple(triple);
swift::IRGenOptions &ir_gen_opts =
m_compiler_invocation_ap->getIRGenOptions();
ir_gen_opts.OutputKind = swift::IRGenOutputKind::Module;
ir_gen_opts.UseJIT = true;
ir_gen_opts.DWARFVersion = swift::DWARFVersion;
// FIXME: lldb does not support resilience yet.
ir_gen_opts.EnableResilienceBypass = true;
}
SwiftASTContext::SwiftASTContext(const SwiftASTContext &rhs)
: TypeSystem(rhs.getKind()), m_source_manager_ap(),
m_diagnostic_engine_ap(), m_ast_context_ap(), m_ir_gen_module_ap(),
m_compiler_invocation_ap(new swift::CompilerInvocation()),
m_dwarf_ast_parser_ap(), m_scratch_module(NULL), m_sil_module_ap(),
m_serialized_module_loader(NULL), m_clang_importer(NULL),
m_swift_module_cache(), m_mangled_name_to_type_map(),
m_type_to_mangled_name_map(), m_pointer_byte_size(0),
m_pointer_bit_align(0), m_void_function_type(), m_target_wp(),
m_process(NULL), m_platform_sdk_path(), m_resource_dir(),
m_ast_file_data_map(), m_initialized_language_options(false),
m_initialized_search_path_options(false),
m_initialized_clang_importer_options(false),
m_reported_fatal_error(false), m_fatal_errors(), m_negative_type_cache(),
m_extra_type_info_cache(), m_swift_type_map() {
if (rhs.m_compiler_invocation_ap) {
std::string rhs_triple = rhs.GetTriple();
if (!rhs_triple.empty()) {
SetTriple(rhs_triple.c_str());
}
llvm::StringRef module_cache_path =
rhs.m_compiler_invocation_ap->getClangModuleCachePath();
m_compiler_invocation_ap->setClangModuleCachePath(module_cache_path);
}
swift::IRGenOptions &ir_gen_opts =
m_compiler_invocation_ap->getIRGenOptions();
ir_gen_opts.OutputKind = swift::IRGenOutputKind::Module;
ir_gen_opts.UseJIT = true;
TargetSP target_sp = rhs.m_target_wp.lock();
if (target_sp)
m_target_wp = target_sp;
m_platform_sdk_path = rhs.m_platform_sdk_path;
m_resource_dir = rhs.m_resource_dir;
swift::ASTContext *lhs_ast = GetASTContext();
swift::ASTContext *rhs_ast =
const_cast<SwiftASTContext &>(rhs).GetASTContext();
if (lhs_ast && rhs_ast) {
lhs_ast->SearchPathOpts = rhs_ast->SearchPathOpts;
}
GetClangImporter();
}
SwiftASTContext::~SwiftASTContext() {
if (m_ast_context_ap.get()) {
GetASTMap().Erase(m_ast_context_ap.get());
}
}
ConstString SwiftASTContext::GetPluginNameStatic() {
return ConstString("swift");
}
ConstString SwiftASTContext::GetPluginName() {
return ClangASTContext::GetPluginNameStatic();
}
uint32_t SwiftASTContext::GetPluginVersion() { return 1; }
static std::string &GetDefaultResourceDir() {
static std::string s_resource_dir;
return s_resource_dir;
}
/// Initialize the compiler invocation with it the search paths from a
/// serialized AST.
/// \returns true on success.
static bool DeserializeCompilerFlags(swift::CompilerInvocation &invocation,
StringRef section_data_ref, StringRef name,
llvm::raw_ostream &error) {
auto result = invocation.loadFromSerializedAST(section_data_ref);
if (result == swift::serialization::Status::Valid)
return true;
error << "While deserializing" << name << ":\n";
switch (result) {
case swift::serialization::Status::Valid:
llvm_unreachable("already checked");
case swift::serialization::Status::FormatTooOld:
error << "The swift module file format is too old to be used by the "
"version of the swift compiler in LLDB\n";
break;
case swift::serialization::Status::FormatTooNew:
error << "the swift module file format is too new to be used by this "
"version of the swift compiler in LLDB\n";
break;
case swift::serialization::Status::MissingDependency:
error << "the swift module file depends on another module that can't be "
"loaded\n";
break;
case swift::serialization::Status::MissingShadowedModule:
error << "the swift module file is an overlay for a clang module, which "
"can't be found\n";
break;
case swift::serialization::Status::FailedToLoadBridgingHeader:
error << "the swift module file depends on a bridging header that can't "
"be loaded\n";
break;
case swift::serialization::Status::Malformed:
error << "the swift module file is malformed\n";
break;
case swift::serialization::Status::MalformedDocumentation:
error << "the swift module documentation file is malformed in some way\n";
break;
case swift::serialization::Status::NameMismatch:
error << "the swift module file's name does not match the module it is "
"being loaded into\n";
break;
case swift::serialization::Status::TargetIncompatible:
error << "the swift module file was built for a different target "
"platform\n";
break;
case swift::serialization::Status::TargetTooNew:
error << "the swift module file was built for a target newer than the "
"current target\n";
break;
}
return false;
}
/// Retrieve the serialized AST data blobs and initialize the compiler
/// invocation with it the concatenated search paths form the blobs.
/// \returns true if an error was encountered.
static bool DeserializeAllCompilerFlags(SwiftASTContext &swift_ast,
Module &module,
llvm::raw_ostream &error,
bool &got_serialized_options) {
got_serialized_options = false;
auto &invocation = swift_ast.GetCompilerInvocation();
SymbolVendor *sym_vendor = module.GetSymbolVendor();
if (!sym_vendor)
return false;
auto ast_file_datas = sym_vendor->GetASTData(eLanguageTypeSwift);
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("Found %d AST file data entries for library: %s.",
(int)ast_file_datas.size(),
module.GetSpecificationDescription().c_str());
// If no N_AST symbols exist, this is not an error.
if (ast_file_datas.empty())
return false;
// An AST section consists of one or more AST modules, optionally
// with headers. Iterate over all AST modules.
for (auto ast_file_data_sp : ast_file_datas) {
llvm::StringRef buf((const char *)ast_file_data_sp->GetBytes(),
ast_file_data_sp->GetByteSize());
while (!buf.empty()) {
std::string last_sdk_path;
auto info = swift::serialization::validateSerializedAST(buf);
if ((info.status != swift::serialization::Status::Valid) ||
(info.bytes == 0) || (info.bytes > buf.size())) {
if (log)
log->Printf("Unable to load AST for module %s from library: %s.",
info.name.str().c_str(),
module.GetSpecificationDescription().c_str());
return true;
}
if (info.name.empty())
continue;
StringRef moduleData = buf.substr(0, info.bytes);
if (log)
last_sdk_path = invocation.getSDKPath();
got_serialized_options |=
DeserializeCompilerFlags(invocation, moduleData, info.name, error);
if (log && !last_sdk_path.empty() &&
invocation.getSDKPath() != last_sdk_path)
log->Printf("SDK path mismatch!\n"
"Was \"%s\", found \"%s\" in module %s.",
last_sdk_path.c_str(),
invocation.getSDKPath().str().c_str(),
info.name.str().c_str());
buf = buf.substr(info.bytes);
}
}
return false;
}
/// Return whether this module contains any serialized Swift ASTs.
bool HasSwiftModules(Module &module) {
SymbolVendor *sym_vendor = module.GetSymbolVendor();
if (!sym_vendor)
return false;
auto ast_file_datas = sym_vendor->GetASTData(eLanguageTypeSwift);
return !ast_file_datas.empty();
}
void SwiftASTContext::RemapClangImporterOptions(
const PathMappingList &path_map) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
auto &options = GetClangImporterOptions();
std::string remapped;
if (path_map.RemapPath(options.BridgingHeader, remapped)) {
if (log)
log->Printf("remapped %s -> %s", options.BridgingHeader.c_str(),
remapped.c_str());
options.BridgingHeader = remapped;
}
for (auto &arg_string : options.ExtraArgs) {
StringRef prefix;
StringRef arg = arg_string;
if (arg.consume_front("-I"))
prefix = "-I";
if (path_map.RemapPath(arg, remapped)) {
if (log)
log->Printf("remapped %s -> %s%s", arg.str().c_str(),
prefix.str().c_str(), remapped.c_str());
arg_string = prefix.str()+remapped;
}
}
}
lldb::TypeSystemSP SwiftASTContext::CreateInstance(lldb::LanguageType language,
Module &module,
Target *target) {
if (!SwiftASTContextSupportsLanguage(language))
return lldb::TypeSystemSP();
ArchSpec arch = module.GetArchitecture();
ObjectFile *objfile = module.GetObjectFile();
ArchSpec object_arch;
if (!objfile || !objfile->GetArchitecture(object_arch))
return TypeSystemSP();
lldb::CompUnitSP main_compile_unit_sp = module.GetCompileUnitAtIndex(0);
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (main_compile_unit_sp && !main_compile_unit_sp->Exists()) {
if (log) {
StreamString ss;
module.GetDescription(&ss);
log->Printf("Corresponding source not found for %s, loading module "
"%s is unlikely to succeed",
main_compile_unit_sp->GetCString(), ss.GetData());
}
}
std::shared_ptr<SwiftASTContext> swift_ast_sp(
target ? (new SwiftASTContextForExpressions(*target))
: new SwiftASTContext());
swift_ast_sp->GetLanguageOptions().DebuggerSupport = true;
swift_ast_sp->GetLanguageOptions().EnableAccessControl = false;
if (!arch.IsValid())
return TypeSystemSP();
llvm::Triple triple = arch.GetTriple();
if (triple.getOS() == llvm::Triple::UnknownOS) {
// cl_kernels are the only binaries that don't have an LC_MIN_VERSION_xxx
// load command. This avoids a Swift assertion.
#if defined(__APPLE__)
switch (triple.getArch()) {
default:
triple.setOS(llvm::Triple::MacOSX);
break;
case llvm::Triple::arm:
case llvm::Triple::armeb:
case llvm::Triple::aarch64:
case llvm::Triple::aarch64_be:
triple.setOS(llvm::Triple::IOS);
break;
}
#else
// Not an elegant hack on OS X, not an elegant hack elsewhere.
// But we shouldn't be claiming things are Mac binaries when they are
// not.
triple.setOS(HostInfo::GetArchitecture().GetTriple().getOS());
#endif
}
swift_ast_sp->SetTriple(triple.getTriple().c_str(), &module);
bool set_triple = false;
SymbolVendor *sym_vendor = module.GetSymbolVendor();
std::string resource_dir;
std::string target_triple;
if (sym_vendor) {
bool got_serialized_options;
llvm::SmallString<0> error;
llvm::raw_svector_ostream errs(error);
if (DeserializeAllCompilerFlags(*swift_ast_sp, module, errs,
got_serialized_options)) {
swift_ast_sp->m_fatal_errors.SetErrorString(error.str());
return swift_ast_sp;
}
// Some of the bits in the compiler options we keep separately, so we
// need to populate them from the serialized options:
llvm::StringRef serialized_triple =
swift_ast_sp->GetCompilerInvocation().getTargetTriple();
if (serialized_triple.empty()) {
if (log)
log->Printf("\tSerialized triple for %s was empty.",
module.GetSpecificationDescription().c_str());
} else {
if (log)
log->Printf("\tFound serialized triple for %s: %s.",
module.GetSpecificationDescription().c_str(),
serialized_triple.data());
swift_ast_sp->SetTriple(serialized_triple.data(), &module);
set_triple = true;
}
llvm::StringRef serialized_sdk_path =
swift_ast_sp->GetCompilerInvocation().getSDKPath();
if (serialized_sdk_path.empty()) {
if (log)
log->Printf("\tNo serialized SDK path.");
} else {
if (log)
log->Printf("\tGot serialized SDK path %s.",
serialized_sdk_path.data());
FileSpec sdk_spec(serialized_sdk_path.data(), false);
if (sdk_spec.Exists()) {
swift_ast_sp->SetPlatformSDKPath(serialized_sdk_path.data());
}
}
if (!got_serialized_options || !swift_ast_sp->GetPlatformSDKPath()) {
std::string platform_sdk_path;
if (sym_vendor->GetCompileOption("-sdk", platform_sdk_path)) {
FileSpec sdk_spec(platform_sdk_path.c_str(), false);
if (sdk_spec.Exists()) {
swift_ast_sp->SetPlatformSDKPath(platform_sdk_path.c_str());
}
if (sym_vendor->GetCompileOption("-target", target_triple)) {
llvm::StringRef parsed_triple(target_triple);
swift_ast_sp->SetTriple(target_triple.c_str(), &module);
set_triple = true;
}
}
}
if (sym_vendor->GetCompileOption("-resource-dir", resource_dir)) {
swift_ast_sp->SetResourceDir(resource_dir.c_str());
} else if (!GetDefaultResourceDir().empty()) {
// Use the first resource dir we found when setting up a target.
swift_ast_sp->SetResourceDir(GetDefaultResourceDir().c_str());
} else {
if (log)
log->Printf("No resource dir available for module's SwiftASTContext.");
}
if (!got_serialized_options) {
std::vector<std::string> framework_search_paths;
if (sym_vendor->GetCompileOptions("-F", framework_search_paths)) {
for (std::string &search_path : framework_search_paths) {
swift_ast_sp->AddFrameworkSearchPath(search_path.c_str());
}
}
std::vector<std::string> include_paths;
if (sym_vendor->GetCompileOptions("-I", include_paths)) {
for (std::string &search_path : include_paths) {
const FileSpec path_spec(search_path.c_str(), false);
if (path_spec.Exists()) {
static const ConstString s_hmap_extension("hmap");
if (IsDirectory(path_spec)) {
swift_ast_sp->AddModuleSearchPath(search_path.c_str());
} else if (IsRegularFile(path_spec) &&
path_spec.GetFileNameExtension() == s_hmap_extension) {
std::string argument("-I");
argument.append(search_path);
swift_ast_sp->AddClangArgument(argument.c_str());
}
}
}
}
std::vector<std::string> cc_options;
if (sym_vendor->GetCompileOptions("-Xcc", cc_options)) {
for (int i = 0; i < cc_options.size(); ++i) {
if (!cc_options[i].compare("-iquote") && i + 1 < cc_options.size()) {
swift_ast_sp->AddClangArgumentPair("-iquote",
cc_options[i + 1].c_str());
}
}
}
}
FileSpecList loaded_modules;
sym_vendor->GetLoadedModules(lldb::eLanguageTypeSwift, loaded_modules);
for (size_t mi = 0, me = loaded_modules.GetSize(); mi != me; ++mi) {
const FileSpec &loaded_module = loaded_modules.GetFileSpecAtIndex(mi);
if (loaded_module.Exists())
swift_ast_sp->AddModuleSearchPath(
loaded_module.GetDirectory().GetCString());
}
}
if (!set_triple) {
llvm::Triple llvm_triple(swift_ast_sp->GetTriple());
// LLVM wants this to be set to iOS or MacOSX; if we're working on
// a bare-boards type image, change the triple for LLVM's benefit.
if (llvm_triple.getVendor() == llvm::Triple::Apple &&
llvm_triple.getOS() == llvm::Triple::UnknownOS) {
if (llvm_triple.getArch() == llvm::Triple::arm ||
llvm_triple.getArch() == llvm::Triple::thumb) {
llvm_triple.setOS(llvm::Triple::IOS);
} else {
llvm_triple.setOS(llvm::Triple::MacOSX);
}
swift_ast_sp->SetTriple(llvm_triple.str().c_str(), &module);
}
}
// Apply source path remappings ofund in the module's dSYM.
swift_ast_sp->RemapClangImporterOptions(module.GetSourceMappingList());
if (!swift_ast_sp->GetClangImporter()) {
if (log) {
log->Printf("((Module*)%p) [%s]->GetSwiftASTContext() returning NULL "
"- couldn't create a ClangImporter",
&module,
module.GetFileSpec().GetFilename().AsCString("<anonymous>"));
}
return TypeSystemSP();
}
std::vector<std::string> module_names;
swift_ast_sp->RegisterSectionModules(module, module_names);
swift_ast_sp->ValidateSectionModules(module, module_names);
if (log) {
log->Printf("((Module*)%p) [%s]->GetSwiftASTContext() = %p", &module,
module.GetFileSpec().GetFilename().AsCString("<anonymous>"),
swift_ast_sp.get());
swift_ast_sp->DumpConfiguration(log);
}
return swift_ast_sp;
}
lldb::TypeSystemSP SwiftASTContext::CreateInstance(lldb::LanguageType language,
Target &target,
const char *extra_options) {
if (!SwiftASTContextSupportsLanguage(language))
return lldb::TypeSystemSP();
ArchSpec arch = target.GetArchitecture();
// Make an AST but don't set the triple yet. We need to try and detect
// if we have a iOS simulator...
std::shared_ptr<SwiftASTContextForExpressions> swift_ast_sp(
new SwiftASTContextForExpressions(target));
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("SwiftASTContext::CreateInstance(Target)");
if (!arch.IsValid())
return TypeSystemSP();
bool handled_sdk_path = false;
bool handled_resource_dir = false;
const size_t num_images = target.GetImages().GetSize();
// Set the SDK path and resource dir prior to doing search paths.
// Otherwise when we create search path options we put in the wrong SDK
// path.
FileSpec &target_sdk_spec = target.GetSDKPath();
if (target_sdk_spec && target_sdk_spec.Exists()) {
std::string platform_sdk_path(target_sdk_spec.GetPath());
swift_ast_sp->SetPlatformSDKPath(std::move(platform_sdk_path));
handled_sdk_path = true;
}
if (target.GetSwiftCreateModuleContextsInParallel()) {
// The first call to GetTypeSystemForLanguage() on a module will
// trigger the import (and thus most likely the rebuild) of all
// the Clang modules that were imported in this module. This can
// be a lot of work (potentially ten seconds per module), but it
// can be performed in parallel.
llvm::ThreadPool pool;
for (size_t mi = 0; mi != num_images; ++mi) {
auto module_sp = target.GetImages().GetModuleAtIndex(mi);
pool.async([=] {
module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift);
});
}
pool.wait();
}
Status module_error;
for (size_t mi = 0; mi != num_images; ++mi) {
ModuleSP module_sp = target.GetImages().GetModuleAtIndex(mi);
// Skip images without a serialized Swift AST. This avoids
// spurious warning messages.
if (!HasSwiftModules(*module_sp))
continue;
SwiftASTContext *module_swift_ast = llvm::dyn_cast_or_null<SwiftASTContext>(
module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift));
if (!module_swift_ast || module_swift_ast->HasFatalErrors() ||
!module_swift_ast->GetClangImporter()) {
// Make sure we warn about this module load failure, the one that
// comes from loading types often gets swallowed up and not seen,
// this is the only reliable point where we can show this.
// But only do it once per UUID so we don't overwhelm the user with
// warnings...
std::unordered_set<std::string> m_swift_warnings_issued;
UUID module_uuid(module_sp->GetUUID());
std::pair<std::unordered_set<std::string>::iterator, bool> result(
m_swift_warnings_issued.insert(module_uuid.GetAsString()));
if (result.second) {
StreamString ss;
module_sp->GetDescription(&ss, eDescriptionLevelBrief);
if (module_swift_ast->HasFatalErrors())
ss << ": "
<< module_swift_ast->GetFatalErrors().AsCString("unknown error");
target.GetDebugger().GetErrorFile()->Printf(
"warning: Swift error in module %s.\n"
"Debug info from this module will be unavailable in the "
"debugger.\n\n",
ss.GetData());
}
continue;
}
if (!handled_sdk_path) {
const char *platform_sdk_path = module_swift_ast->GetPlatformSDKPath();
if (platform_sdk_path) {
handled_sdk_path = true;
swift_ast_sp->SetPlatformSDKPath(platform_sdk_path);
}
}
if (!handled_resource_dir) {
const char *resource_dir = module_swift_ast->GetResourceDir();
if (resource_dir) {
handled_resource_dir = true;
swift_ast_sp->SetResourceDir(resource_dir);
if (GetDefaultResourceDir().empty()) {
// Tuck this away as a reasonable default resource dir
// for contexts that don't have one. The Swift parser
// will assert without one.
GetDefaultResourceDir() = resource_dir;
}
}
}
if (handled_sdk_path && handled_resource_dir)
break;
}
// First, prime the compiler with the options from the main executable:
bool got_serialized_options = false;
ModuleSP exe_module_sp(target.GetExecutableModule());
// If we're debugging a testsuite, then treat the main test bundle as the
// executable.
if (exe_module_sp && PlatformDarwin::IsUnitTestExecutable(*exe_module_sp)) {
ModuleSP unit_test_module =
PlatformDarwin::GetUnitTestModule(target.GetImages());
if (unit_test_module) {
exe_module_sp = unit_test_module;
}
}
// Attempt to deserialize the compiler flags from the AST.
if (exe_module_sp) {
llvm::SmallString<0> error;
llvm::raw_svector_ostream errs(error);
bool failed = DeserializeAllCompilerFlags(*swift_ast_sp, *exe_module_sp,
errs, got_serialized_options);
if (log && failed)
log->Printf(
"Attempt to load compiler options from serialized AST failed: %s",
error.c_str());
}
// Now if the user fully specified the triple, let that override the one
// we got from executable's options:
if (target.GetArchitecture().IsFullySpecifiedTriple()) {
swift_ast_sp->SetTriple(
target.GetArchitecture().GetTriple().str().c_str());
} else {
// Always run using the Host OS triple...
bool set_triple = false;
PlatformSP platform_sp(target.GetPlatform());
uint32_t major, minor, update;
if (platform_sp &&
!target.GetArchitecture().GetTriple().hasEnvironment() &&
platform_sp->GetOSVersion(major, minor, update,
target.GetProcessSP().get())) {
StreamString full_triple_name;
full_triple_name.PutCString(target.GetArchitecture().GetTriple().str());
if (major != UINT32_MAX) {
full_triple_name.Printf("%u", major);
if (minor != UINT32_MAX) {
full_triple_name.Printf(".%u", minor);
if (update != UINT32_MAX)
full_triple_name.Printf(".%u", update);
}
}
swift_ast_sp->SetTriple(full_triple_name.GetString().data());
set_triple = true;
}
if (!set_triple) {
ModuleSP exe_module_sp(target.GetExecutableModule());
if (exe_module_sp) {
Status exe_error;
SwiftASTContext *exe_swift_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(
exe_module_sp->GetTypeSystemForLanguage(
lldb::eLanguageTypeSwift));
if (exe_swift_ctx) {
swift_ast_sp->SetTriple(
exe_swift_ctx->GetLanguageOptions().Target.str().c_str());
}
}
}
}
const bool use_all_compiler_flags =
!got_serialized_options || target.GetUseAllCompilerFlags();
std::function<void(ModuleSP &&)> process_one_module =
[&target, &swift_ast_sp, use_all_compiler_flags](ModuleSP &&module_sp) {
const FileSpec &module_file = module_sp->GetFileSpec();
std::string module_path = module_file.GetPath();
// Add the containing framework to the framework search path. Don't
// do that if this is the executable module, since it might be
// buried in some framework that we don't care about.
if (use_all_compiler_flags &&
target.GetExecutableModulePointer() != module_sp.get()) {
size_t framework_offset = module_path.rfind(".framework/");
if (framework_offset != std::string::npos) {
// Sometimes the version of the framework that got loaded has been
// stripped and in that case, adding it to the framework search
// path will just short-cut a clang search that might otherwise
// find the needed headers. So don't add these paths.
std::string framework_path =
module_path.substr(0, framework_offset);
framework_path.append(".framework");
FileSpec path_spec(framework_path, true);
FileSpec headers_spec =
path_spec.CopyByAppendingPathComponent("Headers");
bool add_it = false;
if (headers_spec.Exists())
add_it = true;
if (!add_it) {
FileSpec module_spec =
path_spec.CopyByAppendingPathComponent("Modules");
if (module_spec.Exists())
add_it = true;
}
if (!add_it) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("process_one_module rejecting framework path"
" \"%s\" as it has no Headers "
"or Modules subdirectories.",
framework_path.c_str());
}
if (add_it) {
while (framework_offset && (module_path[framework_offset] != '/'))
framework_offset--;
if (module_path[framework_offset] == '/') {
// framework_offset now points to the '/';
std::string parent_path =
module_path.substr(0, framework_offset);
if (strncmp(parent_path.c_str(), "/System/Library",
strlen("/System/Library")) &&
!IsDeviceSupport(parent_path.c_str())) {
swift_ast_sp->AddFrameworkSearchPath(parent_path.c_str());
}
}
}
}
}
// Skip images without a serialized Swift AST.
if (!HasSwiftModules(*module_sp))
return;
SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
if (!sym_vendor)
return;
std::vector<std::string> module_names;
SymbolFile *sym_file = sym_vendor->GetSymbolFile();
if (!sym_file)
return;
Status sym_file_error;
SwiftASTContext *ast_context = llvm::dyn_cast_or_null<SwiftASTContext>(
sym_file->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift));
if (ast_context && !ast_context->HasErrors()) {
if (use_all_compiler_flags ||
target.GetExecutableModulePointer() == module_sp.get()) {
for (size_t msi = 0, mse = ast_context->GetNumModuleSearchPaths();
msi < mse; ++msi) {
const char *search_path =
ast_context->GetModuleSearchPathAtIndex(msi);
swift_ast_sp->AddModuleSearchPath(search_path);
}
for (size_t fsi = 0,
fse = ast_context->GetNumFrameworkSearchPaths();
fsi < fse; ++fsi) {
const char *search_path =
ast_context->GetFrameworkSearchPathAtIndex(fsi);
swift_ast_sp->AddFrameworkSearchPath(search_path);
}
std::string clang_argument;
for (size_t osi = 0, ose = ast_context->GetNumClangArguments();
osi < ose; ++osi) {
// Join multi-arg -D and -U options for uniquing.
clang_argument += ast_context->GetClangArgumentAtIndex(osi);
if (clang_argument == "-D" || clang_argument == "-U")
continue;
// Enable uniquing for -D and -U options.
bool force = true;
if (clang_argument.size() >= 2 && clang_argument[0] == '-' &&
(clang_argument[1] == 'D' || clang_argument[1] == 'U'))
force = false;
swift_ast_sp->AddClangArgument(clang_argument, force);
clang_argument.clear();
}
}
swift_ast_sp->RegisterSectionModules(*module_sp, module_names);
}
};
for (size_t mi = 0; mi != num_images; ++mi) {
process_one_module(target.GetImages().GetModuleAtIndex(mi));
}
FileSpecList &framework_search_paths = target.GetSwiftFrameworkSearchPaths();
FileSpecList &module_search_paths = target.GetSwiftModuleSearchPaths();
for (size_t fi = 0, fe = framework_search_paths.GetSize(); fi != fe; ++fi) {
swift_ast_sp->AddFrameworkSearchPath(
framework_search_paths.GetFileSpecAtIndex(fi).GetPath().c_str());
}
for (size_t mi = 0, me = module_search_paths.GetSize(); mi != me; ++mi) {
swift_ast_sp->AddModuleSearchPath(
module_search_paths.GetFileSpecAtIndex(mi).GetPath().c_str());
}
// Now fold any extra options we were passed. This has to be done BEFORE
// the ClangImporter is made by calling GetClangImporter or these options
// will be ignored.
if (extra_options) {
swift::CompilerInvocation &compiler_invocation =
swift_ast_sp->GetCompilerInvocation();
Args extra_args(extra_options);
llvm::ArrayRef<const char *> extra_args_ref(extra_args.GetArgumentVector(),
extra_args.GetArgumentCount());
compiler_invocation.parseArgs(extra_args_ref,
swift_ast_sp->GetDiagnosticEngine());
}
// Apply source path remappings ofund in the target settings.
swift_ast_sp->RemapClangImporterOptions(target.GetSourcePathMap());
// This needs to happen once all the import paths are set, or otherwise no
// modules will be found.
if (!swift_ast_sp->GetClangImporter()) {
if (log) {
log->Printf("((Target*)%p)->GetSwiftASTContext() returning NULL - "
"couldn't create a ClangImporter",
&target);
}
return TypeSystemSP();
}
if (log) {
log->Printf("((Target*)%p)->GetSwiftASTContext() = %p", &target,
swift_ast_sp.get());
swift_ast_sp->DumpConfiguration(log);
}
if (swift_ast_sp->HasFatalErrors()) {
swift_ast_sp->m_error.SetErrorStringWithFormat(
"Error creating target Swift AST context: %s",
swift_ast_sp->GetFatalErrors().AsCString());
return lldb::TypeSystemSP();
}
{
const bool can_create = true;
if (!swift_ast_sp->m_ast_context_ap->getStdlibModule(can_create)) {
// We need to be able to load the standard library!
return lldb::TypeSystemSP();
}
}
return swift_ast_sp;
}
void SwiftASTContext::EnumerateSupportedLanguages(
std::set<lldb::LanguageType> &languages_for_types,
std::set<lldb::LanguageType> &languages_for_expressions) {
static std::vector<lldb::LanguageType> s_supported_languages_for_types(
{lldb::eLanguageTypeSwift});
static std::vector<lldb::LanguageType> s_supported_languages_for_expressions(
{lldb::eLanguageTypeSwift});
languages_for_types.insert(s_supported_languages_for_types.begin(),
s_supported_languages_for_types.end());
languages_for_expressions.insert(
s_supported_languages_for_expressions.begin(),
s_supported_languages_for_expressions.end());
}
static lldb::TypeSystemSP CreateTypeSystemInstance(lldb::LanguageType language,
Module *module,
Target *target,
const char *extra_options) {
// This should be called with either a target or a module.
if (module) {
assert(!target);
assert(StringRef(extra_options).empty());
return SwiftASTContext::CreateInstance(language, *module);
} else if (target) {
assert(!module);
return SwiftASTContext::CreateInstance(language, *target, extra_options);
}
}
void SwiftASTContext::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), "swift AST context plug-in",
CreateTypeSystemInstance, EnumerateSupportedLanguages);
}
void SwiftASTContext::Terminate() {
PluginManager::UnregisterPlugin(CreateTypeSystemInstance);
}
bool SwiftASTContext::SupportsLanguage(lldb::LanguageType language) {
return SwiftASTContextSupportsLanguage(language);
}
Status SwiftASTContext::IsCompatible() { return GetFatalErrors(); }
Status SwiftASTContext::GetFatalErrors() {
Status error;
if (HasFatalErrors()) {
error = m_fatal_errors;
if (error.Success())
error.SetErrorString("unknown fatal error in swift AST context");
}
return error;
}
swift::IRGenOptions &SwiftASTContext::GetIRGenOptions() {
return m_compiler_invocation_ap->getIRGenOptions();
}
std::string SwiftASTContext::GetTriple() const {
return m_compiler_invocation_ap->getTargetTriple();
}
// Conditions a triple string to be safe for use with Swift.
// Right now this just strips the Haswell marker off the CPU name.
// TODO make Swift more robust
static std::string GetSwiftFriendlyTriple(const std::string &triple) {
static std::string s_x86_64h("x86_64h");
static std::string::size_type s_x86_64h_size = s_x86_64h.size();
if (0 == triple.compare(0, s_x86_64h_size, s_x86_64h)) {
std::string fixed_triple("x86_64");
fixed_triple.append(
triple.substr(s_x86_64h_size, triple.size() - s_x86_64h_size));
return fixed_triple;
}
return triple;
}
bool SwiftASTContext::SetTriple(const char *triple_cstr, Module *module) {
if (triple_cstr && triple_cstr[0]) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
// We can change our triple up until we create the swift::irgen::IRGenModule
if (m_ir_gen_module_ap.get() == NULL) {
std::string raw_triple(triple_cstr);
std::string triple = GetSwiftFriendlyTriple(raw_triple);
llvm::Triple llvm_triple(triple);
const unsigned unspecified = 0;
// If the OS version is unspecified, do fancy things
if (llvm_triple.getOSMajorVersion() == unspecified) {
// If a triple is "<arch>-apple-darwin" change it to be
// "<arch>-apple-macosx" otherwise the major and minor OS version we
// append below would be wrong.
if (llvm_triple.getVendor() == llvm::Triple::VendorType::Apple &&
llvm_triple.getOS() == llvm::Triple::OSType::Darwin) {
llvm_triple.setOS(llvm::Triple::OSType::MacOSX);
triple = llvm_triple.str();
}
// Append the min OS to the triple if we have a target
ModuleSP module_sp;
if (module == NULL) {
TargetSP target_sp(m_target_wp.lock());
if (target_sp) {
module_sp = target_sp->GetExecutableModule();
if (module_sp)
module = module_sp.get();
}
}
if (module) {
ObjectFile *objfile = module->GetObjectFile();
uint32_t versions[3];
if (objfile) {
uint32_t num_versions = objfile->GetMinimumOSVersion(versions, 3);
StreamString strm;
if (num_versions) {
for (uint32_t v = 0; v < 3; ++v) {
if (v < num_versions) {
if (versions[v] == UINT32_MAX)
versions[v] = 0;
} else
versions[v] = 0;
}
strm.Printf("%s%u.%u.%u", llvm_triple.getOSName().str().c_str(),
versions[0], versions[1], versions[2]);
llvm_triple.setOSName(strm.GetString());
triple = llvm_triple.str();
}
}
}
}
if (log)
log->Printf("%p: SwiftASTContext::SetTriple('%s') setting to '%s'%s",
this, triple_cstr, triple.c_str(),
m_target_wp.lock() ? " (target)" : "");
m_compiler_invocation_ap->setTargetTriple(triple);
// Every time the triple is changed the LangOpts must be
// updated too, because Swift default-initializes the
// EnableObjCInterop flag based on the triple.
GetLanguageOptions().EnableObjCInterop = llvm_triple.isOSDarwin();
return true;
} else {
if (log)
log->Printf("%p: SwiftASTContext::SetTriple('%s') ignoring triple "
"since the IRGenModule has already been created",
this, triple_cstr);
}
}
return false;
}
static std::string GetXcodeContentsPath() {
const char substr[] = ".app/Contents/";
// First, try based on the current shlib's location
{
FileSpec fspec;
if (HostInfo::GetLLDBPath(ePathTypeLLDBShlibDir, fspec)) {
std::string path_to_shlib = fspec.GetPath();
size_t pos = path_to_shlib.rfind(substr);
if (pos != std::string::npos) {
path_to_shlib.erase(pos + strlen(substr));
return path_to_shlib;
}
}
}
// Fall back to using xcrun
{
int status = 0;
int signo = 0;
std::string output;
const char *command = "xcrun -sdk macosx --show-sdk-path";
lldb_private::Status error = Host::RunShellCommand(
command, // shell command to run
NULL, // current working directory
&status, // Put the exit status of the process in here
&signo, // Put the signal that caused the process to exit in here
&output, // Get the output from the command and place it in this string
3); // Timeout in seconds to wait for shell program to finish
if (status == 0 && !output.empty()) {
size_t first_non_newline = output.find_last_not_of("\r\n");
if (first_non_newline != std::string::npos) {
output.erase(first_non_newline + 1);
}
size_t pos = output.rfind(substr);
if (pos != std::string::npos) {
output.erase(pos + strlen(substr));
return output;
}
}
}
return std::string();
}
static std::string GetCurrentToolchainPath() {
const char substr[] = ".xctoolchain/";
{
FileSpec fspec;
if (HostInfo::GetLLDBPath(ePathTypeLLDBShlibDir, fspec)) {
std::string path_to_shlib = fspec.GetPath();
size_t pos = path_to_shlib.rfind(substr);
if (pos != std::string::npos) {
path_to_shlib.erase(pos + strlen(substr));
return path_to_shlib;
}
}
}
return std::string();
}
static std::string GetCurrentCLToolsPath() {
const char substr[] = "/CommandLineTools/";
{
FileSpec fspec;
if (HostInfo::GetLLDBPath(ePathTypeLLDBShlibDir, fspec)) {
std::string path_to_shlib = fspec.GetPath();
size_t pos = path_to_shlib.rfind(substr);
if (pos != std::string::npos) {
path_to_shlib.erase(pos + strlen(substr));
return path_to_shlib;
}
}
}
return std::string();
}
namespace {
enum class SDKType {
MacOSX = 0,
iPhoneSimulator,
iPhoneOS,
AppleTVSimulator,
AppleTVOS,
WatchSimulator,
watchOS,
numSDKTypes,
unknown = -1
};
const char *const sdk_strings[] = {
"macosx", "iphonesimulator", "iphoneos", "appletvsimulator",
"appletvos", "watchsimulator", "watchos",
};
struct SDKEnumeratorInfo {
FileSpec found_path;
SDKType sdk_type;
uint32_t least_major;
uint32_t least_minor;
};
static bool SDKSupportsSwift(const FileSpec &sdk_path, SDKType desired_type) {
ConstString last_path_component = sdk_path.GetLastPathComponent();
if (last_path_component) {
const llvm::StringRef sdk_name_raw = last_path_component.GetStringRef();
std::string sdk_name_lower = sdk_name_raw.lower();
const llvm::StringRef sdk_name(sdk_name_lower);
llvm::StringRef version_part;
SDKType sdk_type = SDKType::unknown;
if (desired_type == SDKType::unknown) {
for (int i = (int)SDKType::MacOSX; i < (int)SDKType::numSDKTypes; ++i) {
if (sdk_name.startswith(sdk_strings[i])) {
version_part = sdk_name.drop_front(strlen(sdk_strings[i]));
sdk_type = (SDKType)i;
break;
}
}
// For non-Darwin SDKs assume Swift is supported
if (sdk_type == SDKType::unknown)
return true;
} else {
if (sdk_name.startswith(sdk_strings[(int)desired_type])) {
version_part =
sdk_name.drop_front(strlen(sdk_strings[(int)desired_type]));
sdk_type = desired_type;
} else {
return false;
}
}
const size_t major_dot_offset = version_part.find('.');
if (major_dot_offset == llvm::StringRef::npos)
return false;
const llvm::StringRef major_version =
version_part.slice(0, major_dot_offset);
const llvm::StringRef minor_part =
version_part.drop_front(major_dot_offset + 1);
const size_t minor_dot_offset = minor_part.find('.');
if (minor_dot_offset == llvm::StringRef::npos)
return false;
const llvm::StringRef minor_version = minor_part.slice(0, minor_dot_offset);
unsigned int major = 0;
unsigned int minor = 0;
if (major_version.getAsInteger(10, major))
return false;
if (minor_version.getAsInteger(10, minor))
return false;
switch (sdk_type) {
case SDKType::MacOSX:
if (major > 10 || (major == 10 && minor >= 10))
return true;
break;
case SDKType::iPhoneOS:
case SDKType::iPhoneSimulator:
if (major >= 8)
return true;
break;
case SDKType::AppleTVSimulator:
case SDKType::AppleTVOS:
if (major >= 9)
return true;
break;
case SDKType::WatchSimulator:
case SDKType::watchOS:
if (major >= 2)
return true;
break;
default:
return false;
}
}
return false;
}
FileSpec::EnumerateDirectoryResult
DirectoryEnumerator(void *baton, llvm::sys::fs::file_type file_type,
const FileSpec &spec) {
SDKEnumeratorInfo *enumerator_info = static_cast<SDKEnumeratorInfo *>(baton);
if (SDKSupportsSwift(spec, enumerator_info->sdk_type)) {
enumerator_info->found_path = spec;
return FileSpec::EnumerateDirectoryResult::eEnumerateDirectoryResultNext;
}
return FileSpec::EnumerateDirectoryResult::eEnumerateDirectoryResultNext;
};
static ConstString EnumerateSDKsForVersion(FileSpec sdks_spec, SDKType sdk_type,
uint32_t least_major,
uint32_t least_minor) {
if (!IsDirectory(sdks_spec))
return ConstString();
const bool find_directories = true;
const bool find_files = false;
const bool find_other = true; // include symlinks
SDKEnumeratorInfo enumerator_info;
enumerator_info.sdk_type = sdk_type;
enumerator_info.least_major = least_major;
enumerator_info.least_minor = least_minor;
FileSpec::EnumerateDirectory(sdks_spec.GetPath().c_str(), find_directories,
find_files, find_other, DirectoryEnumerator,
&enumerator_info);
if (IsDirectory(enumerator_info.found_path))
return ConstString(enumerator_info.found_path.GetPath());
else
return ConstString();
}
static ConstString GetSDKDirectory(SDKType sdk_type, uint32_t least_major,
uint32_t least_minor) {
if (sdk_type != SDKType::MacOSX) {
// Look inside Xcode for the required installed iOS SDK version
std::string sdks_path = GetXcodeContentsPath();
sdks_path.append("Developer/Platforms");
if (sdk_type == SDKType::iPhoneSimulator) {
sdks_path.append("/iPhoneSimulator.platform/");
} else if (sdk_type == SDKType::AppleTVSimulator) {
sdks_path.append("/AppleTVSimulator.platform/");
} else if (sdk_type == SDKType::AppleTVOS) {
sdks_path.append("/AppleTVOS.platform/");
} else if (sdk_type == SDKType::WatchSimulator) {
sdks_path.append("/WatchSimulator.platform/");
} else if (sdk_type == SDKType::watchOS) {
// For now, we need to be prepared to handle either capitalization of this
// path.
std::string WatchOS_candidate_path = sdks_path + "/WatchOS.platform/";
if (IsDirectory(FileSpec(WatchOS_candidate_path.c_str(), false))) {
sdks_path = WatchOS_candidate_path;
} else {
std::string watchOS_candidate_path = sdks_path + "/watchOS.platform/";
if (IsDirectory(FileSpec(watchOS_candidate_path.c_str(), false))) {
sdks_path = watchOS_candidate_path;
} else {
return ConstString();
}
}
} else {
sdks_path.append("/iPhoneOS.platform/");
}
sdks_path.append("Developer/SDKs/");
FileSpec sdks_spec(sdks_path.c_str(), false);
return EnumerateSDKsForVersion(sdks_spec, sdk_type, least_major,
least_major);
}
// The SDK type is Mac OS X
uint32_t major = 0;
uint32_t minor = 0;
uint32_t update = 0;
if (!HostInfo::GetOSVersion(major, minor, update))
return ConstString();
// If there are minimum requirements that exceed the current OS, apply those
if (least_major > major) {
major = least_major;
minor = least_minor;
} else if (least_major == major) {
if (least_minor > minor)
minor = least_minor;
}
typedef std::map<uint64_t, ConstString> SDKDirectoryCache;
static std::mutex g_mutex;
static SDKDirectoryCache g_sdk_cache;
std::lock_guard<std::mutex> locker(g_mutex);
const uint64_t major_minor = (uint64_t)major << 32 | (uint64_t)minor;
SDKDirectoryCache::iterator pos = g_sdk_cache.find(major_minor);
if (pos != g_sdk_cache.end())
return pos->second;
FileSpec fspec;
std::string xcode_contents_path;
if (xcode_contents_path.empty())
xcode_contents_path = GetXcodeContentsPath();
if (!xcode_contents_path.empty()) {
StreamString sdk_path;
sdk_path.Printf(
"%sDeveloper/Platforms/MacOSX.platform/Developer/SDKs/MacOSX%u.%u.sdk",
xcode_contents_path.c_str(), major, minor);
fspec.SetFile(sdk_path.GetString(), false);
if (fspec.Exists()) {
ConstString path(sdk_path.GetString());
// Cache results
g_sdk_cache[major_minor] = path;
return path;
} else if ((least_major != major) || (least_minor != minor)) {
// Try the required SDK
sdk_path.Clear();
sdk_path.Printf("%sDeveloper/Platforms/MacOSX.platform/Developer/SDKs/"
"MacOSX%u.%u.sdk",
xcode_contents_path.c_str(), least_major, least_minor);
fspec.SetFile(sdk_path.GetString(), false);
if (fspec.Exists()) {
ConstString path(sdk_path.GetString());
// Cache results
g_sdk_cache[major_minor] = path;
return path;
} else {
// Okay, we're going to do an exhaustive search for *any* SDK that has
// an adequate version.
std::string sdks_path = GetXcodeContentsPath();
sdks_path.append("Developer/Platforms/MacOSX.platform/Developer/SDKs");
FileSpec sdks_spec(sdks_path.c_str(), false);
ConstString sdk_path = EnumerateSDKsForVersion(
sdks_spec, sdk_type, least_major, least_major);
if (sdk_path) {
g_sdk_cache[major_minor] = sdk_path;
return sdk_path;
}
}
}
}
// Cache results
g_sdk_cache[major_minor] = ConstString();
return ConstString();
}
static ConstString GetResourceDir() {
static ConstString g_cached_resource_dir;
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
// First, check if there's something in our bundle
{
FileSpec swift_dir_spec;
if (HostInfo::GetLLDBPath(ePathTypeSwiftDir, swift_dir_spec)) {
if (log)
log->Printf("%s: trying ePathTypeSwiftDir: %s", __FUNCTION__,
swift_dir_spec.GetCString());
// We can't just check for the Swift directory, because that
// always exists. We have to look for "clang" inside that.
FileSpec swift_clang_dir_spec = swift_dir_spec;
swift_clang_dir_spec.AppendPathComponent("clang");
if (IsDirectory(swift_clang_dir_spec)) {
g_cached_resource_dir = ConstString(swift_dir_spec.GetPath());
if (log)
log->Printf("%s: found Swift resource dir via "
"ePathTypeSwiftDir': %s",
__FUNCTION__, g_cached_resource_dir.AsCString());
return;
}
}
}
// Nothing in our bundle. Are we in a toolchain that has its own Swift
// compiler resource dir?
{
std::string xcode_toolchain_path = GetCurrentToolchainPath();
if (log)
log->Printf("%s: trying toolchain path: %s", __FUNCTION__,
xcode_toolchain_path.c_str());
if (!xcode_toolchain_path.empty()) {
xcode_toolchain_path.append("usr/lib/swift");
if (log)
log->Printf("%s: trying toolchain-based lib path: %s", __FUNCTION__,
xcode_toolchain_path.c_str());
if (IsDirectory(FileSpec(xcode_toolchain_path, false))) {
g_cached_resource_dir = ConstString(xcode_toolchain_path);
if (log)
log->Printf("%s: found Swift resource dir via "
"toolchain path + 'usr/lib/swift': %s",
__FUNCTION__, g_cached_resource_dir.AsCString());
return;
}
}
}
// We're not in a toolchain that has one. Use the Xcode default toolchain.
{
std::string xcode_contents_path = GetXcodeContentsPath();
if (log)
log->Printf("%s: trying Xcode path: %s", __FUNCTION__,
xcode_contents_path.c_str());
if (!xcode_contents_path.empty()) {
xcode_contents_path.append("Developer/Toolchains/"
"XcodeDefault.xctoolchain"
"/usr/lib/swift");
if (log)
log->Printf("%s: trying Xcode-based lib path: %s", __FUNCTION__,
xcode_contents_path.c_str());
if (IsDirectory(FileSpec(xcode_contents_path, false))) {
g_cached_resource_dir = ConstString(xcode_contents_path);
if (log)
log->Printf("%s: found Swift resource dir via "
"Xcode contents path + default toolchain "
"relative dir: %s",
__FUNCTION__, g_cached_resource_dir.AsCString());
return;
}
}
}
// We're not in Xcode. We might be in the command-line tools.
{
std::string cl_tools_path = GetCurrentCLToolsPath();
if (log)
log->Printf("%s: trying command-line tools path: %s", __FUNCTION__,
cl_tools_path.c_str());
if (!cl_tools_path.empty()) {
cl_tools_path.append("usr/lib/swift");
if (log)
log->Printf("%s: trying command-line tools-based lib "
"path: %s",
__FUNCTION__, cl_tools_path.c_str());
if (IsDirectory(FileSpec(cl_tools_path, false))) {
g_cached_resource_dir = ConstString(cl_tools_path);
if (log)
log->Printf("%s: found Swift resource dir via "
"command-line tools path + "
"usr/lib/swift: %s",
__FUNCTION__, g_cached_resource_dir.AsCString());
return;
}
}
}
// We might be in the build-dir configuration for a build-script-driven
// LLDB build, which has the Swift build dir as a sibling directory
// to the lldb build dir. This looks much different than the install-
// dir layout that the previous checks would try.
{
FileSpec faux_swift_dir_spec;
if (HostInfo::GetLLDBPath(ePathTypeSwiftDir, faux_swift_dir_spec)) {
// We can't use a C++11 stdlib regex feature here because it
// doesn't work on Ubuntu 14.04 x86_64. Once we don't care
// about supporting that anymore, let's pull the code below
// back in since it is a simpler implementation using
// std::regex.
#if 0
// Let's try to regex this.
// We're looking for /some/path/lldb-{os}-{arch}, and want to
// build the following:
// /some/path/swift-{os}-{arch}/lib/swift/{os}/{arch}
// In a match, these are the following assignments for
// backrefs:
// $1 - first part of path before swift build dir
// $2 - the host OS path separator character
// $3 - all the stuff that should come after changing
// lldb to swift for the lib dir.
auto match_regex =
std::regex("^(.+([/\\\\]))lldb-(.+)$");
const std::string replace_format = "$1swift-$3";
const std::string faux_swift_dir =
faux_swift_dir_spec.GetCString();
const std::string build_tree_resource_dir =
std::regex_replace(faux_swift_dir, match_regex,
replace_format);
#else
std::string build_tree_resource_dir;
const std::string faux_swift_dir =
faux_swift_dir_spec.GetCString();
// Find something that matches lldb- (particularly,
// the last one).
const std::string lldb_dash("lldb-");
auto lldb_pos = faux_swift_dir.rfind(lldb_dash);
if ((lldb_pos != std::string::npos) &&
(lldb_pos > 0) &&
((faux_swift_dir[lldb_pos - 1] == '\\') ||
(faux_swift_dir[lldb_pos - 1] == '/')))
{
// We found something that matches ^.+[/\\]lldb-.+$
std::ostringstream stream;
// Take everything before lldb- (the path leading up to
// the lldb dir).
stream << faux_swift_dir.substr(0, lldb_pos);
// replace lldb- with swift-.
stream << "swift-";
// and now tack on the same components from after
// the lldb- part.
stream << faux_swift_dir.substr(lldb_pos +
lldb_dash.length());
const std::string build_tree_resource_dir = stream.str();
if (log)
log->Printf("%s: trying ePathTypeSwiftDir regex-based "
"build dir: %s",
__FUNCTION__,
build_tree_resource_dir.c_str());
FileSpec swift_resource_dir_spec(
build_tree_resource_dir.c_str(), false);
if (IsDirectory(swift_resource_dir_spec))
{
g_cached_resource_dir =
ConstString(swift_resource_dir_spec.GetPath());
if (log)
log->Printf("%s: found Swift resource dir via "
"ePathTypeSwiftDir + inferred "
"build-tree dir: %s", __FUNCTION__,
g_cached_resource_dir.AsCString());
return;
}
}
#endif
}
}
// We failed to find a reasonable Swift resource dir.
if (log)
log->Printf("%s: failed to find a Swift resource dir", __FUNCTION__);
});
return g_cached_resource_dir;
}
} // anonymous namespace
swift::CompilerInvocation &SwiftASTContext::GetCompilerInvocation() {
return *m_compiler_invocation_ap;
}
swift::SourceManager &SwiftASTContext::GetSourceManager() {
if (m_source_manager_ap.get() == NULL)
m_source_manager_ap.reset(new swift::SourceManager());
return *m_source_manager_ap;
}
swift::LangOptions &SwiftASTContext::GetLanguageOptions() {
return GetCompilerInvocation().getLangOptions();
}
swift::DiagnosticEngine &SwiftASTContext::GetDiagnosticEngine() {
if (m_diagnostic_engine_ap.get() == NULL)
m_diagnostic_engine_ap.reset(
new swift::DiagnosticEngine(GetSourceManager()));
return *m_diagnostic_engine_ap;
}
// This code comes from CompilerInvocation.cpp (setRuntimeResourcePath)
static void ConfigureResourceDirs(swift::CompilerInvocation &invocation,
FileSpec resource_dir, llvm::Triple triple) {
// Make sure the triple is right:
invocation.setTargetTriple(triple.str());
invocation.setRuntimeResourcePath(resource_dir.GetPath().c_str());
}
swift::SILOptions &SwiftASTContext::GetSILOptions() {
return GetCompilerInvocation().getSILOptions();
}
bool SwiftASTContext::TargetHasNoSDK() {
llvm::Triple triple(GetTriple());
switch (triple.getOS()) {
case llvm::Triple::OSType::MacOSX:
case llvm::Triple::OSType::Darwin:
case llvm::Triple::OSType::IOS:
return false;
default:
return true;
}
}
swift::ClangImporterOptions &SwiftASTContext::GetClangImporterOptions() {
swift::ClangImporterOptions &clang_importer_options =
GetCompilerInvocation().getClangImporterOptions();
if (!m_initialized_clang_importer_options) {
m_initialized_clang_importer_options = true;
// Set the Clang module search path.
llvm::SmallString<128> path;
auto props = ModuleList::GetGlobalModuleListProperties();
props.GetClangModulesCachePath().GetPath(path);
clang_importer_options.ModuleCachePath = path.str();
FileSpec clang_dir_spec;
if (HostInfo::GetLLDBPath(ePathTypeClangDir, clang_dir_spec))
clang_importer_options.OverrideResourceDir =
std::move(clang_dir_spec.GetPath());
clang_importer_options.DebuggerSupport = true;
}
return clang_importer_options;
}
swift::SearchPathOptions &SwiftASTContext::GetSearchPathOptions() {
swift::SearchPathOptions &search_path_opts =
GetCompilerInvocation().getSearchPathOptions();
if (!m_initialized_search_path_options) {
m_initialized_search_path_options = true;
bool set_sdk = false;
bool set_resource_dir = false;
if (!search_path_opts.SDKPath.empty()) {
FileSpec provided_sdk_path(search_path_opts.SDKPath, false);
if (provided_sdk_path.Exists()) {
// We don't check whether the SDK supports swift because we figure if
// someone is passing this to us on the command line (e.g., for the
// REPL), they probably know what they're doing.
set_sdk = true;
}
} else if (!m_platform_sdk_path.empty()) {
FileSpec platform_sdk(m_platform_sdk_path.c_str(), false);
if (platform_sdk.Exists() &&
SDKSupportsSwift(platform_sdk, SDKType::unknown)) {
search_path_opts.SDKPath = m_platform_sdk_path.c_str();
set_sdk = true;
}
}
llvm::Triple triple(GetTriple());
if (!m_resource_dir.empty()) {
FileSpec resource_dir(m_resource_dir.c_str(), false);
if (resource_dir.Exists()) {
ConfigureResourceDirs(GetCompilerInvocation(), resource_dir, triple);
set_resource_dir = true;
}
}
auto is_simulator = [&]() -> bool {
return triple.getEnvironment() == llvm::Triple::Simulator ||
!triple.getArchName().startswith("arm");
};
if (!set_sdk) {
switch (triple.getOS()) {
case llvm::Triple::OSType::MacOSX:
case llvm::Triple::OSType::Darwin:
search_path_opts.SDKPath = GetSDKDirectory(SDKType::MacOSX, 10, 10)
.AsCString("");
break;
case llvm::Triple::OSType::IOS:
search_path_opts.SDKPath =
is_simulator()
? GetSDKDirectory(SDKType::iPhoneSimulator, 8, 0).AsCString("")
: GetSDKDirectory(SDKType::iPhoneOS, 8, 0).AsCString("");
break;
case llvm::Triple::OSType::TvOS:
search_path_opts.SDKPath =
is_simulator()
? GetSDKDirectory(SDKType::AppleTVSimulator, 9, 0).AsCString("")
: GetSDKDirectory(SDKType::AppleTVOS, 9, 0).AsCString("");
break;
case llvm::Triple::OSType::WatchOS:
search_path_opts.SDKPath =
is_simulator()
? GetSDKDirectory(SDKType::WatchSimulator, 2, 0).AsCString("")
: GetSDKDirectory(SDKType::watchOS, 2, 0).AsCString("");
break;
default:
// Explicitly leave the SDKPath blank on other platforms.
break;
}
}
if (!set_resource_dir) {
FileSpec resource_dir(::GetResourceDir().AsCString(""), false);
if (resource_dir.Exists())
ConfigureResourceDirs(GetCompilerInvocation(), resource_dir, triple);
}
}
return search_path_opts;
}
namespace lldb_private {
class ANSIColorStringStream : public llvm::raw_string_ostream {
public:
ANSIColorStringStream(bool colorize)
: llvm::raw_string_ostream(m_buffer), m_colorize(colorize) {}
/// Changes the foreground color of text that will be output from this point
/// forward.
/// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
/// change only the bold attribute, and keep colors untouched
/// @param Bold bold/brighter text, default false
/// @param BG if true change the background, default: change foreground
/// @returns itself so it can be used within << invocations
virtual raw_ostream &changeColor(enum Colors colors, bool bold = false,
bool bg = false) {
if (llvm::sys::Process::ColorNeedsFlush())
flush();
const char *colorcode;
if (colors == SAVEDCOLOR)
colorcode = llvm::sys::Process::OutputBold(bg);
else
colorcode = llvm::sys::Process::OutputColor(colors, bold, bg);
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
}
return *this;
}
/// Resets the colors to terminal defaults. Call this when you are done
/// outputting colored text, or before program exit.
virtual raw_ostream &resetColor() {
if (llvm::sys::Process::ColorNeedsFlush())
flush();
const char *colorcode = llvm::sys::Process::ResetColor();
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
}
return *this;
}
/// Reverses the forground and background colors.
virtual raw_ostream &reverseColor() {
if (llvm::sys::Process::ColorNeedsFlush())
flush();
const char *colorcode = llvm::sys::Process::OutputReverse();
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
}
return *this;
}
/// This function determines if this stream is connected to a "tty" or
/// "console" window. That is, the output would be displayed to the user
/// rather than being put on a pipe or stored in a file.
virtual bool is_displayed() const { return m_colorize; }
/// This function determines if this stream is displayed and supports colors.
virtual bool has_colors() const { return m_colorize; }
protected:
std::string m_buffer;
bool m_colorize;
};
class StoringDiagnosticConsumer : public swift::DiagnosticConsumer {
public:
StoringDiagnosticConsumer(SwiftASTContext &ast_context)
: m_ast_context(ast_context), m_diagnostics(), m_num_errors(0),
m_colorize(false) {
m_ast_context.GetDiagnosticEngine().resetHadAnyError();
m_ast_context.GetDiagnosticEngine().addConsumer(*this);
}
~StoringDiagnosticConsumer() {
m_ast_context.GetDiagnosticEngine().takeConsumers();
}
virtual void handleDiagnostic(swift::SourceManager &source_mgr,
swift::SourceLoc source_loc,
swift::DiagnosticKind kind,
llvm::StringRef formatString,
llvm::ArrayRef<swift::DiagnosticArgument> formatArgs,
const swift::DiagnosticInfo &info) {
llvm::StringRef bufferName = "<anonymous>";
unsigned bufferID = 0;
std::pair<unsigned, unsigned> line_col = {0, 0};
llvm::SmallString<256> text;
{
llvm::raw_svector_ostream out(text);
swift::DiagnosticEngine::formatDiagnosticText(out,
formatString,
formatArgs);
}
if (source_loc.isValid()) {
bufferID = source_mgr.findBufferContainingLoc(source_loc);
bufferName = source_mgr.getBufferIdentifierForLoc(source_loc);
line_col = source_mgr.getLineAndColumn(source_loc);
}
if (line_col.first != 0) {
ANSIColorStringStream os(m_colorize);
// Determine what kind of diagnostic we're emitting, and whether we want
// to use its fixits:
bool use_fixits = false;
llvm::SourceMgr::DiagKind source_mgr_kind;
switch (kind) {
default:
case swift::DiagnosticKind::Error:
source_mgr_kind = llvm::SourceMgr::DK_Error;
use_fixits = true;
break;
case swift::DiagnosticKind::Warning:
source_mgr_kind = llvm::SourceMgr::DK_Warning;
break;
case swift::DiagnosticKind::Note:
source_mgr_kind = llvm::SourceMgr::DK_Note;
break;
}
// Translate ranges.
llvm::SmallVector<llvm::SMRange, 2> ranges;
for (auto R : info.Ranges)
ranges.push_back(getRawRange(source_mgr, R));
// Translate fix-its.
llvm::SmallVector<llvm::SMFixIt, 2> fix_its;
for (swift::DiagnosticInfo::FixIt F : info.FixIts)
fix_its.push_back(getRawFixIt(source_mgr, F));
// Display the diagnostic.
auto message = source_mgr.GetMessage(source_loc, source_mgr_kind, text,
ranges, fix_its);
source_mgr.getLLVMSourceMgr().PrintMessage(os, message);
// Use the llvm::raw_string_ostream::str() accessor as it will flush
// the stream into our "message" and return us a reference to "message".
std::string &message_ref = os.str();
if (message_ref.empty())
m_diagnostics.push_back(RawDiagnostic(
text.str(), kind, bufferName, bufferID, line_col.first,
line_col.second,
use_fixits ? info.FixIts
: llvm::ArrayRef<swift::Diagnostic::FixIt>()));
else
m_diagnostics.push_back(RawDiagnostic(
message_ref, kind, bufferName, bufferID, line_col.first,
line_col.second,
use_fixits ? info.FixIts
: llvm::ArrayRef<swift::Diagnostic::FixIt>()));
} else {
m_diagnostics.push_back(RawDiagnostic(
text.str(), kind, bufferName, bufferID, line_col.first,
line_col.second, llvm::ArrayRef<swift::Diagnostic::FixIt>()));
}
if (kind == swift::DiagnosticKind::Error)
m_num_errors++;
}
void Clear() {
m_ast_context.GetDiagnosticEngine().resetHadAnyError();
m_diagnostics.clear();
m_num_errors = 0;
}
unsigned NumErrors() {
if (m_num_errors)
return m_num_errors;
else if (m_ast_context.GetASTContext()->hadError())
return 1;
else
return 0;
}
static DiagnosticSeverity SeverityForKind(swift::DiagnosticKind kind) {
switch (kind) {
case swift::DiagnosticKind::Error:
return eDiagnosticSeverityError;
case swift::DiagnosticKind::Warning:
return eDiagnosticSeverityWarning;
case swift::DiagnosticKind::Note:
return eDiagnosticSeverityRemark;
}
llvm_unreachable("Unhandled DiagnosticKind in switch.");
}
void PrintDiagnostics(DiagnosticManager &diagnostic_manager,
uint32_t bufferID = UINT32_MAX, uint32_t first_line = 0,
uint32_t last_line = UINT32_MAX,
uint32_t line_offset = 0) {
bool added_one_diagnostic = false;
for (const RawDiagnostic &diagnostic : m_diagnostics) {
// We often make expressions and wrap them in some code.
// When we see errors we want the line numbers to be correct so
// we correct them below. LLVM stores in SourceLoc objects as character
// offsets so there is no way to get LLVM to move its error line numbers
// around by adjusting the source location, we must do it manually. We
// also want to use the same error formatting as LLVM and Clang, so we
// must muck with the string.
const DiagnosticSeverity severity = SeverityForKind(diagnostic.kind);
const DiagnosticOrigin origin = eDiagnosticOriginSwift;
if (first_line > 0 && bufferID != UINT32_MAX &&
diagnostic.bufferID == bufferID && !diagnostic.bufferName.empty()) {
// Make sure the error line is in range
if (diagnostic.line >= first_line && diagnostic.line <= last_line) {
// Need to remap the error/warning to a different line
StreamString match;
match.Printf("%s:%u:", diagnostic.bufferName.str().c_str(),
diagnostic.line);
const size_t match_len = match.GetString().size();
size_t match_pos = diagnostic.description.find(match.GetString());
if (match_pos != std::string::npos) {
// We have some <file>:<line>:" instances that need to be updated
StreamString fixed_description;
size_t start_pos = 0;
do {
if (match_pos > start_pos)
fixed_description.Printf(
"%s", diagnostic.description.substr(start_pos, match_pos)
.c_str());
fixed_description.Printf("%s:%u:",
diagnostic.bufferName.str().c_str(),
diagnostic.line - first_line +
line_offset + 1);
start_pos = match_pos + match_len;
match_pos =
diagnostic.description.find(match.GetString(), start_pos);
} while (match_pos != std::string::npos);
// Append any last remainging text
if (start_pos < diagnostic.description.size())
fixed_description.Printf(
"%s",
diagnostic.description.substr(start_pos,
diagnostic.description.size() -
start_pos)
.c_str());
SwiftDiagnostic *new_diagnostic =
new SwiftDiagnostic(fixed_description.GetString().data(),
severity, origin, bufferID);
for (auto fixit : diagnostic.fixits)
new_diagnostic->AddFixIt(fixit);
diagnostic_manager.AddDiagnostic(new_diagnostic);
added_one_diagnostic = true;
continue;
}
}
}
}
// In general, we don't want to see diagnostics from outside of the source
// text range of the actual user expression. But if we didn't find any
// diagnostics in the text range, it's probably because the source range was
// not specified correctly, and we don't want to lose legit errors because
// of that. So in that case we'll add them all here:
if (!added_one_diagnostic) {
// This will report diagnostic errors from outside the expression's source
// range. Those are not interesting to users, so we only emit them in
// debug builds.
for (const RawDiagnostic &diagnostic : m_diagnostics) {
const DiagnosticSeverity severity = SeverityForKind(diagnostic.kind);
const DiagnosticOrigin origin = eDiagnosticOriginSwift;
diagnostic_manager.AddDiagnostic(diagnostic.description.c_str(),
severity, origin);
}
}
}
bool GetColorize() const { return m_colorize; }
bool SetColorize(bool b) {
const bool old = m_colorize;
m_colorize = b;
return old;
}
private:
// We don't currently use lldb_private::Diagostic or any of the lldb
// DiagnosticManager machinery to store diagnostics as they occur. Instead,
// we store them in raw form using this struct, then transcode them to
// SwiftDiagnostics in PrintDiagnostic.
struct RawDiagnostic {
RawDiagnostic(std::string in_desc, swift::DiagnosticKind in_kind,
llvm::StringRef in_bufferName, unsigned in_bufferID,
uint32_t in_line, uint32_t in_column,
llvm::ArrayRef<swift::Diagnostic::FixIt> in_fixits)
: description(in_desc), kind(in_kind), bufferName(in_bufferName),
bufferID(in_bufferID), line(in_line), column(in_column) {
for (auto fixit : in_fixits) {
fixits.push_back(fixit);
}
}
std::string description;
swift::DiagnosticKind kind;
const llvm::StringRef bufferName;
unsigned bufferID;
uint32_t line;
uint32_t column;
std::vector<swift::DiagnosticInfo::FixIt> fixits;
};
typedef std::vector<RawDiagnostic> RawDiagnosticBuffer;
SwiftASTContext &m_ast_context;
RawDiagnosticBuffer m_diagnostics;
unsigned m_num_errors = 0;
bool m_colorize;
};
}
swift::ASTContext *SwiftASTContext::GetASTContext() {
if (m_ast_context_ap.get() == NULL) {
m_ast_context_ap.reset(
swift::ASTContext::get(GetLanguageOptions(), GetSearchPathOptions(),
GetSourceManager(), GetDiagnosticEngine()));
m_diagnostic_consumer_ap.reset(new StoringDiagnosticConsumer(*this));
if (getenv("LLDB_SWIFT_DUMP_DIAGS")) {
// NOTE: leaking a swift::PrintingDiagnosticConsumer() here, but this only
// gets enabled when the above environment variable is set.
GetDiagnosticEngine().addConsumer(
*new swift::PrintingDiagnosticConsumer());
}
// Install the serialized module loader
std::unique_ptr<swift::ModuleLoader> serialized_module_loader_ap(
swift::SerializedModuleLoader::create(*m_ast_context_ap));
if (serialized_module_loader_ap) {
m_serialized_module_loader =
(swift::SerializedModuleLoader *)serialized_module_loader_ap.get();
m_ast_context_ap->addModuleLoader(std::move(serialized_module_loader_ap));
}
GetASTMap().Insert(m_ast_context_ap.get(), this);
}
VALID_OR_RETURN(nullptr);
return m_ast_context_ap.get();
}
swift::SerializedModuleLoader *SwiftASTContext::GetSerializeModuleLoader() {
VALID_OR_RETURN(nullptr);
GetASTContext();
return m_serialized_module_loader;
}
swift::ClangImporter *SwiftASTContext::GetClangImporter() {
VALID_OR_RETURN(nullptr);
if (m_clang_importer == NULL) {
swift::ASTContext *ast_ctx = GetASTContext();
if (!ast_ctx) {
return nullptr;
}
// Install the Clang module loader
TargetSP target_sp(m_target_wp.lock());
if (true /*target_sp*/) {
// PlatformSP platform_sp = target_sp->GetPlatform();
if (true /*platform_sp*/) {
if (!ast_ctx->SearchPathOpts.SDKPath.empty() || TargetHasNoSDK()) {
swift::ClangImporterOptions &clang_importer_options =
GetClangImporterOptions();
if (!clang_importer_options.OverrideResourceDir.empty()) {
std::unique_ptr<swift::ModuleLoader> clang_importer_ap(
swift::ClangImporter::create(*m_ast_context_ap,
clang_importer_options));
if (clang_importer_ap) {
const bool isClang = true;
m_clang_importer =
(swift::ClangImporter *)clang_importer_ap.get();
m_ast_context_ap->addModuleLoader(std::move(clang_importer_ap),
isClang);
}
}
}
}
}
}
return m_clang_importer;
}
bool SwiftASTContext::AddModuleSearchPath(const char *path) {
VALID_OR_RETURN(false);
if (path && path[0]) {
swift::ASTContext *ast = GetASTContext();
std::string path_str(path);
bool add_search_path = true;
for (auto path : ast->SearchPathOpts.ImportSearchPaths) {
if (path == path_str) {
add_search_path = false;
break;
}
}
if (add_search_path) {
ast->SearchPathOpts.ImportSearchPaths.push_back(path);
return true;
}
}
return false;
}
bool SwiftASTContext::AddFrameworkSearchPath(const char *path) {
VALID_OR_RETURN(false);
if (path && path[0]) {
swift::ASTContext *ast = GetASTContext();
std::string path_str(path);
bool add_search_path = true;
for (const auto &swift_path : ast->SearchPathOpts.FrameworkSearchPaths) {
if (swift_path.Path == path_str) {
add_search_path = false;
break;
}
}
if (add_search_path) {
ast->SearchPathOpts.FrameworkSearchPaths.push_back({path, /*isSystem=*/false});
return true;
}
}
return false;
}
bool SwiftASTContext::AddClangArgument(std::string clang_arg, bool force) {
if (!clang_arg.empty()) {
swift::ClangImporterOptions &importer_options = GetClangImporterOptions();
bool add_hmap = true;
if (!force) {
for (std::string &arg : importer_options.ExtraArgs) {
if (!arg.compare(clang_arg)) {
add_hmap = false;
break;
}
}
}
if (add_hmap) {
importer_options.ExtraArgs.push_back(clang_arg);
return true;
}
}
return false;
}
bool SwiftASTContext::AddClangArgumentPair(const char *clang_arg_1,
const char *clang_arg_2) {
if (clang_arg_1 && clang_arg_2 && clang_arg_1[0] && clang_arg_2[0]) {
swift::ClangImporterOptions &importer_options = GetClangImporterOptions();
bool add_hmap = true;
for (ssize_t ai = 0, ae = importer_options.ExtraArgs.size() -
1; // -1 because we look at the next one too
ai < ae;
++ai) {
if (!importer_options.ExtraArgs[ai].compare(clang_arg_1) &&
!importer_options.ExtraArgs[ai + 1].compare(clang_arg_2)) {
add_hmap = false;
break;
}
}
if (add_hmap) {
importer_options.ExtraArgs.push_back(clang_arg_1);
importer_options.ExtraArgs.push_back(clang_arg_2);
return true;
}
}
return false;
}
size_t SwiftASTContext::GetNumModuleSearchPaths() const {
VALID_OR_RETURN(0);
if (m_ast_context_ap.get())
return m_ast_context_ap->SearchPathOpts.ImportSearchPaths.size();
return 0;
}
const char *SwiftASTContext::GetModuleSearchPathAtIndex(size_t idx) const {
VALID_OR_RETURN(nullptr);
if (m_ast_context_ap.get()) {
if (idx < m_ast_context_ap->SearchPathOpts.ImportSearchPaths.size())
return m_ast_context_ap->SearchPathOpts.ImportSearchPaths[idx].c_str();
}
return NULL;
}
size_t SwiftASTContext::GetNumFrameworkSearchPaths() const {
VALID_OR_RETURN(0);
if (m_ast_context_ap.get())
return m_ast_context_ap->SearchPathOpts.FrameworkSearchPaths.size();
return 0;
}
const char *SwiftASTContext::GetFrameworkSearchPathAtIndex(size_t idx) const {
VALID_OR_RETURN(nullptr);
if (m_ast_context_ap.get()) {
if (idx < m_ast_context_ap->SearchPathOpts.FrameworkSearchPaths.size())
return m_ast_context_ap->SearchPathOpts.FrameworkSearchPaths[idx].Path.c_str();
}
return NULL;
}
size_t SwiftASTContext::GetNumClangArguments() {
swift::ClangImporterOptions &importer_options = GetClangImporterOptions();
return importer_options.ExtraArgs.size();
}
const char *SwiftASTContext::GetClangArgumentAtIndex(size_t idx) {
swift::ClangImporterOptions &importer_options = GetClangImporterOptions();
if (idx < importer_options.ExtraArgs.size())
return importer_options.ExtraArgs[idx].c_str();
return NULL;
}
swift::ModuleDecl *
SwiftASTContext::GetCachedModule(const ConstString &module_name) {
VALID_OR_RETURN(nullptr);
SwiftModuleMap::const_iterator iter =
m_swift_module_cache.find(module_name.GetCString());
if (iter != m_swift_module_cache.end())
return iter->second;
return NULL;
}
swift::ModuleDecl *
SwiftASTContext::CreateModule(const ConstString &module_basename,
Status &error) {
VALID_OR_RETURN(nullptr);
if (module_basename) {
swift::ModuleDecl *module = GetCachedModule(module_basename);
if (module) {
error.SetErrorStringWithFormat("module already exists for '%s'",
module_basename.GetCString());
return NULL;
}
swift::ASTContext *ast = GetASTContext();
if (ast) {
swift::Identifier module_id(
ast->getIdentifier(module_basename.GetCString()));
module = swift::ModuleDecl::create(module_id, *ast);
if (module) {
m_swift_module_cache[module_basename.GetCString()] = module;
return module;
} else {
error.SetErrorStringWithFormat("invalid swift AST (NULL)");
}
} else {
error.SetErrorStringWithFormat("invalid swift AST (NULL)");
}
} else {
error.SetErrorStringWithFormat("invalid module name (empty)");
}
return NULL;
}
void SwiftASTContext::CacheModule(swift::ModuleDecl *module) {
VALID_OR_RETURN_VOID();
if (!module)
return;
auto ID = module->getName().get();
if (nullptr == ID || 0 == ID[0])
return;
if (m_swift_module_cache.find(ID) != m_swift_module_cache.end())
return;
m_swift_module_cache.insert({ID, module});
}
swift::ModuleDecl *
SwiftASTContext::GetModule(const ConstString &module_basename, Status &error) {
VALID_OR_RETURN(nullptr);
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule('%s')", this,
module_basename.AsCString("<no name>"));
if (module_basename) {
swift::ModuleDecl *module = GetCachedModule(module_basename);
if (module)
return module;
if (swift::ASTContext *ast = GetASTContext()) {
typedef std::pair<swift::Identifier, swift::SourceLoc> ModuleNameSpec;
llvm::StringRef module_basename_sref(module_basename.GetCString());
ModuleNameSpec name_pair(ast->getIdentifier(module_basename_sref),
swift::SourceLoc());
if (HasFatalErrors()) {
error.SetErrorStringWithFormat("failed to get module '%s' from AST "
"context:\nAST context is in a fatal "
"error state",
module_basename.GetCString());
printf("error in SwiftASTContext::GetModule(%s): AST context is in a "
"fatal error stat",
module_basename.GetCString());
return nullptr;
}
ClearDiagnostics();
module = ast->getModuleByName(module_basename_sref);
if (HasErrors()) {
DiagnosticManager diagnostic_manager;
PrintDiagnostics(diagnostic_manager);
error.SetErrorStringWithFormat(
"failed to get module '%s' from AST context:\n%s",
module_basename.GetCString(),
diagnostic_manager.GetString().data());
#ifdef LLDB_CONFIGURATION_DEBUG
printf("error in SwiftASTContext::GetModule(%s): '%s'",
module_basename.GetCString(),
diagnostic_manager.GetString().data());
#endif
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule('%s') -- error: %s",
this, module_basename.GetCString(),
diagnostic_manager.GetString().data());
} else if (module) {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule('%s') -- found %s",
this, module_basename.GetCString(),
module->getName().str().str().c_str());
m_swift_module_cache[module_basename.GetCString()] = module;
return module;
} else {
if (log)
log->Printf(
"((SwiftASTContext*)%p)->GetModule('%s') -- failed with no error",
this, module_basename.GetCString());
error.SetErrorStringWithFormat(
"failed to get module '%s' from AST context",
module_basename.GetCString());
}
} else {
if (log)
log->Printf(
"((SwiftASTContext*)%p)->GetModule('%s') -- invalid ASTContext",
this, module_basename.GetCString());
error.SetErrorString("invalid swift::ASTContext");
}
} else {
if (log)
log->Printf(
"((SwiftASTContext*)%p)->GetModule('%s') -- empty module name", this,
module_basename.GetCString());
error.SetErrorString("invalid module name (empty)");
}
return NULL;
}
swift::ModuleDecl *SwiftASTContext::GetModule(const FileSpec &module_spec,
Status &error) {
VALID_OR_RETURN(nullptr);
ConstString module_basename(module_spec.GetFileNameStrippingExtension());
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule((FileSpec)'%s')", this,
module_spec.GetPath().c_str());
if (module_basename) {
SwiftModuleMap::const_iterator iter =
m_swift_module_cache.find(module_basename.GetCString());
if (iter != m_swift_module_cache.end())
return iter->second;
if (module_spec.Exists()) {
swift::ASTContext *ast = GetASTContext();
if (!GetClangImporter()) {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule((FileSpec)'%s') -- no "
"ClangImporter so giving up",
this, module_spec.GetPath().c_str());
error.SetErrorStringWithFormat("couldn't get a ClangImporter");
return nullptr;
}
std::string module_directory(module_spec.GetDirectory().GetCString());
bool add_search_path = true;
for (auto path : ast->SearchPathOpts.ImportSearchPaths) {
if (path == module_directory) {
add_search_path = false;
break;
}
}
// Add the search path if needed so we can find the module by basename
if (add_search_path)
ast->SearchPathOpts.ImportSearchPaths.push_back(
std::move(module_directory));
typedef std::pair<swift::Identifier, swift::SourceLoc> ModuleNameSpec;
llvm::StringRef module_basename_sref(module_basename.GetCString());
ModuleNameSpec name_pair(ast->getIdentifier(module_basename_sref),
swift::SourceLoc());
swift::ModuleDecl *module =
ast->getModule(llvm::ArrayRef<ModuleNameSpec>(name_pair));
if (module) {
if (log)
log->Printf(
"((SwiftASTContext*)%p)->GetModule((FileSpec)'%s') -- found %s",
this, module_spec.GetPath().c_str(),
module->getName().str().str().c_str());
m_swift_module_cache[module_basename.GetCString()] = module;
return module;
} else {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule((FileSpec)'%s') -- "
"couldn't get from AST context",
this, module_spec.GetPath().c_str());
error.SetErrorStringWithFormat(
"failed to get module '%s' from AST context",
module_basename.GetCString());
}
} else {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetModule((FileSpec)'%s') -- "
"doesn't exist",
this, module_spec.GetPath().c_str());
error.SetErrorStringWithFormat("module '%s' doesn't exist",
module_spec.GetPath().c_str());
}
} else {
if (log)
log->Printf(
"((SwiftASTContext*)%p)->GetModule((FileSpec)'%s') -- no basename",
this, module_spec.GetPath().c_str());
error.SetErrorStringWithFormat("no module basename in '%s'",
module_spec.GetPath().c_str());
}
return NULL;
}
swift::ModuleDecl *
SwiftASTContext::FindAndLoadModule(const ConstString &module_basename,
Process &process, Status &error) {
VALID_OR_RETURN(nullptr);
swift::ModuleDecl *swift_module = GetModule(module_basename, error);
if (!swift_module)
return nullptr;
LoadModule(swift_module, process, error);
return swift_module;
}
swift::ModuleDecl *
SwiftASTContext::FindAndLoadModule(const FileSpec &module_spec,
Process &process, Status &error) {
VALID_OR_RETURN(nullptr);
swift::ModuleDecl *swift_module = GetModule(module_spec, error);
if (!swift_module)
return nullptr;
LoadModule(swift_module, process, error);
return swift_module;
}
bool SwiftASTContext::LoadOneImage(Process &process, FileSpec &link_lib_spec,
Status &error) {
VALID_OR_RETURN(false);
error.Clear();
PlatformSP platform_sp = process.GetTarget().GetPlatform();
if (platform_sp)
return platform_sp->LoadImage(&process, FileSpec(), link_lib_spec, error) !=
LLDB_INVALID_IMAGE_TOKEN;
else
return false;
}
static void
GetLibrarySearchPaths(std::vector<std::string> &paths,
const swift::SearchPathOptions &search_path_opts) {
paths.clear();
paths.resize(search_path_opts.LibrarySearchPaths.size() + 1);
std::copy(search_path_opts.LibrarySearchPaths.begin(),
search_path_opts.LibrarySearchPaths.end(), paths.begin());
paths.push_back(search_path_opts.RuntimeLibraryPath);
}
void SwiftASTContext::LoadModule(swift::ModuleDecl *swift_module,
Process &process, Status &error) {
VALID_OR_RETURN_VOID();
Status current_error;
auto addLinkLibrary = [&](swift::LinkLibrary link_lib) {
Status load_image_error;
StreamString all_dlopen_errors;
const char *library_name = link_lib.getName().data();
if (library_name == NULL || library_name[0] == '\0') {
error.SetErrorString("Empty library name passed to addLinkLibrary");
return;
}
SwiftLanguageRuntime *runtime = process.GetSwiftLanguageRuntime();
if (runtime && runtime->IsInLibraryNegativeCache(library_name))
return;
swift::LibraryKind library_kind = link_lib.getKind();
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("\nLoading link library \"%s\" of kind: %d.", library_name,
library_kind);
switch (library_kind) {
case swift::LibraryKind::Framework: {
// First make sure the library isn't already loaded. Since this is a
// framework, we make sure the file name and the framework name are the
// same, and that we are contained in FileName.framework with no other
// intervening frameworks. We can get more restrictive if this gives
// false positives.
ConstString library_cstr(library_name);
std::string framework_name(library_name);
framework_name.append(".framework");
// Lookup the module by file basename and make sure that basename has
// "<basename>.framework" in the path.
ModuleSpec module_spec;
module_spec.GetFileSpec().GetFilename() = library_cstr;
lldb_private::ModuleList matching_module_list;
bool module_already_loaded = false;
if (process.GetTarget().GetImages().FindModules(module_spec,
matching_module_list)) {
matching_module_list.ForEach(
[&module_already_loaded, &module_spec,
&framework_name](const ModuleSP &module_sp) -> bool {
module_already_loaded = module_spec.GetFileSpec().GetPath().find(
framework_name) != std::string::npos;
return module_already_loaded ==
false; // Keep iterating if we didn't find the right module
});
}
// If we already have this library loaded, don't try and load it again.
if (module_already_loaded) {
if (log)
log->Printf("Skipping load of %s as it is already loaded.",
framework_name.c_str());
return;
}
for (auto module : process.GetTarget().GetImages().Modules()) {
FileSpec module_file = module->GetFileSpec();
if (module_file.GetFilename() == library_cstr) {
std::string module_path = module_file.GetPath();
size_t framework_offset = module_path.rfind(framework_name);
if (framework_offset != std::string::npos) {
// The Framework is already loaded, so we don't need to try to load
// it again.
if (log)
log->Printf("Skipping load of %s as it is already loaded.",
framework_name.c_str());
return;
}
}
}
std::string framework_path("@rpath/");
framework_path.append(library_name);
framework_path.append(".framework/");
framework_path.append(library_name);
FileSpec framework_spec(framework_path.c_str(), false);
if (LoadOneImage(process, framework_spec, load_image_error)) {
if (log)
log->Printf("Found framework at: %s.", framework_path.c_str());
return;
} else
all_dlopen_errors.Printf("Looking for \"%s\", error: %s\n",
framework_path.c_str(),
load_image_error.AsCString());
// And then in the various framework search paths.
std::unordered_set<std::string> seen_paths;
for (const auto &framework_search_dir :
swift_module->getASTContext().SearchPathOpts.FrameworkSearchPaths) {
// The framework search dir as it comes from the AST context often has
// duplicate entries, don't try to load along the same path twice.
std::pair<std::unordered_set<std::string>::iterator, bool>
insert_result = seen_paths.insert(framework_search_dir.Path);
if (!insert_result.second)
continue;
framework_path = framework_search_dir.Path;
framework_path.append("/");
framework_path.append(library_name);
framework_path.append(".framework/");
framework_path.append(library_name);
framework_spec.SetFile(framework_path.c_str(), false);
if (LoadOneImage(process, framework_spec, load_image_error)) {
if (log)
log->Printf("Found framework at: %s.", framework_path.c_str());
return;
} else
all_dlopen_errors.Printf("Looking for \"%s\"\n, error: %s\n",
framework_path.c_str(),
load_image_error.AsCString());
}
// Maybe we were told to add a link library that exists in the system. I
// tried just specifying Foo.framework/Foo and letting the system search
// figure that out, but if DYLD_FRAMEWORK_FALLBACK_PATH is set
// (e.g. in Xcode's test scheme) then these aren't found. So for now I
// dial them in explicitly:
std::string system_path("/System/Library/Frameworks/");
system_path.append(library_name);
system_path.append(".framework/");
system_path.append(library_name);
framework_spec.SetFile(system_path.c_str(), true);
if (LoadOneImage(process, framework_spec, load_image_error))
return;
else
all_dlopen_errors.Printf("Looking for \"%s\"\n, error: %s\n",
framework_path.c_str(),
load_image_error.AsCString());
} break;
case swift::LibraryKind::Library: {
std::vector<std::string> search_paths;
GetLibrarySearchPaths(search_paths,
swift_module->getASTContext().SearchPathOpts);
if (LoadLibraryUsingPaths(process, library_name, search_paths, true,
all_dlopen_errors))
return;
} break;
}
// If we get here, we aren't going to find this image, so add it to a
// negative cache:
if (runtime)
runtime->AddToLibraryNegativeCache(library_name);
current_error.SetErrorStringWithFormat(
"Failed to load linked library %s of module %s - errors:\n%s\n",
library_name, swift_module->getName().str().str().c_str(),
all_dlopen_errors.GetData());
};
swift_module->collectLinkLibraries(addLinkLibrary);
error = current_error;
}
bool SwiftASTContext::LoadLibraryUsingPaths(
Process &process, llvm::StringRef library_name,
std::vector<std::string> &search_paths, bool check_rpath,
StreamString &all_dlopen_errors) {
VALID_OR_RETURN(false);
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES));
SwiftLanguageRuntime *runtime = process.GetSwiftLanguageRuntime();
if (!runtime) {
all_dlopen_errors.PutCString(
"Can't load Swift libraries without a language runtime.");
return false;
}
if (ConstString::Equals(runtime->GetStandardLibraryBaseName(),
ConstString(library_name))) {
// Never dlopen the standard library. Some binaries statically link to the
// Swift standard library and dlopening it here will cause ObjC runtime
// conflicts.
// If you want to run Swift expressions you have to arrange to load the
// Swift standard library by hand before doing so.
if (log)
log->Printf("Skipping swift standard library \"%s\" - we don't hand load "
"that one.",
runtime->GetStandardLibraryBaseName().AsCString());
return true;
}
PlatformSP platform_sp(process.GetTarget().GetPlatform());
std::string library_fullname;
if (platform_sp) {
library_fullname =
platform_sp->GetFullNameForDylib(ConstString(library_name)).AsCString();
} else // This is the old way, and we shouldn't use it except on Mac OS
{
#ifdef __APPLE__
library_fullname = "lib";
library_fullname.append(library_name);
library_fullname.append(".dylib");
#else
return false;
#endif
}
ModuleSpec module_spec;
module_spec.GetFileSpec().GetFilename().SetCString(library_fullname.c_str());
lldb_private::ModuleList matching_module_list;
if (process.GetTarget().GetImages().FindModules(module_spec,
matching_module_list) > 0) {
if (log)
log->Printf("Skipping module %s as it is already loaded.",
library_fullname.c_str());
return true;
}
FileSpec library_spec;
std::string library_path;
std::unordered_set<std::string> seen_paths;
Status load_image_error;
for (const std::string &library_search_dir : search_paths) {
// The library search dir as it comes from the AST context often has
// duplicate entries, don't try to load along the same path twice.
std::pair<std::unordered_set<std::string>::iterator, bool> insert_result =
seen_paths.insert(library_search_dir);
if (!insert_result.second)
continue;
library_path = library_search_dir;
library_path.append("/");
library_path.append(library_fullname);
library_spec.SetFile(library_path.c_str(), false);
if (LoadOneImage(process, library_spec, load_image_error)) {
if (log)
log->Printf("Found library at: %s.", library_path.c_str());
return true;
} else
all_dlopen_errors.Printf("Looking for \"%s\"\n, error: %s\n",
library_path.c_str(),
load_image_error.AsCString());
}
if (check_rpath) {
// Let our RPATH help us out when finding the right library
library_path = "@rpath/";
library_path += library_fullname;
FileSpec link_lib_spec(library_path.c_str(), false);
if (LoadOneImage(process, link_lib_spec, load_image_error)) {
if (log)
log->Printf("Found library at: %s.", library_path.c_str());
return true;
} else
all_dlopen_errors.Printf("Looking for \"%s\", error: %s\n",
library_path.c_str(),
load_image_error.AsCString());
}
return false;
}
void SwiftASTContext::LoadExtraDylibs(Process &process, Status &error) {
VALID_OR_RETURN_VOID();
error.Clear();
swift::IRGenOptions &irgen_options = GetIRGenOptions();
for (const swift::LinkLibrary &link_lib : irgen_options.LinkLibraries) {
// We don't have to do frameworks here, they actually record their link
// libraries properly.
if (link_lib.getKind() == swift::LibraryKind::Library) {
const char *library_name = link_lib.getName().data();
StreamString errors;
std::vector<std::string> search_paths;
GetLibrarySearchPaths(search_paths,
m_compiler_invocation_ap->getSearchPathOptions());
bool success = LoadLibraryUsingPaths(process, library_name, search_paths,
false, errors);
if (!success) {
error.SetErrorString(errors.GetData());
}
}
}
}
bool SwiftASTContext::RegisterSectionModules(
Module &module, std::vector<std::string> &module_names) {
VALID_OR_RETURN(false);
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
swift::SerializedModuleLoader *sml = GetSerializeModuleLoader();
if (sml) {
SectionList *section_list = module.GetSectionList();
if (section_list) {
SectionSP section_sp(
section_list->FindSectionByType(eSectionTypeSwiftModules, true));
if (section_sp) {
DataExtractor section_data;
if (section_sp->GetSectionData(section_data)) {
llvm::StringRef section_data_ref(
(const char *)section_data.GetDataStart(),
section_data.GetByteSize());
llvm::SmallVector<std::string, 4> llvm_modules;
if (swift::parseASTSection(sml, section_data_ref, llvm_modules)) {
for (auto module_name : llvm_modules)
module_names.push_back(module_name);
return true;
}
}
} else {
if (m_ast_file_data_map.find(&module) != m_ast_file_data_map.end())
return true;
SymbolVendor *sym_vendor = module.GetSymbolVendor();
if (sym_vendor) {
// Grab all the AST blobs from the symbol vendor.
auto ast_file_datas = sym_vendor->GetASTData(eLanguageTypeSwift);
if (log)
log->Printf("SwiftASTContext::%s() retrieved %zu AST Data blobs "
"from the symbol vendor.",
__FUNCTION__, ast_file_datas.size());
// Add each of the AST blobs to the vector of AST blobs for the
// module.
auto &ast_vector = GetASTVectorForModule(&module);
ast_vector.insert(ast_vector.end(), ast_file_datas.begin(),
ast_file_datas.end());
// Retrieve the module names from the AST blobs retrieved from the
// symbol vendor.
size_t parse_fail_count = 0;
size_t ast_number = 0;
for (auto ast_file_data_sp : ast_file_datas) {
// Parse the AST section info from the AST blob.
++ast_number;
llvm::StringRef section_data_ref(
(const char *)ast_file_data_sp->GetBytes(),
ast_file_data_sp->GetByteSize());
llvm::SmallVector<std::string, 4> llvm_modules;
if (swift::parseASTSection(sml, section_data_ref, llvm_modules)) {
// Collect the LLVM module names referenced by the AST.
for (auto module_name : llvm_modules)
module_names.push_back(module_name);
if (log)
log->Printf("SwiftASTContext::%s() - parsed %zu llvm modules "
"from Swift AST section %zu of %zu.",
__FUNCTION__, llvm_modules.size(), ast_number,
ast_file_datas.size());
} else {
// Keep track of the fact that we failed to parse the AST
// section info.
if (log)
log->Printf("SwiftASTContext::%s() - failed to parse AST "
"section %zu of %zu.",
__FUNCTION__, ast_number, ast_file_datas.size());
++parse_fail_count;
}
}
if (!ast_file_datas.empty() && (parse_fail_count == 0)) {
// We found AST data entries and we successfully parsed all of
// them.
return true;
}
}
}
}
}
return false;
}
void SwiftASTContext::ValidateSectionModules(
Module &module, const std::vector<std::string> &module_names) {
VALID_OR_RETURN_VOID();
Status error;
for (const std::string &module_name : module_names)
if (!GetModule(ConstString(module_name.c_str()), error))
module.ReportWarning("unable to load swift module '%s' (%s)",
module_name.c_str(), error.AsCString());
}
swift::Identifier SwiftASTContext::GetIdentifier(const char *name) {
VALID_OR_RETURN(swift::Identifier());
return GetASTContext()->getIdentifier(llvm::StringRef(name));
}
swift::Identifier SwiftASTContext::GetIdentifier(const llvm::StringRef &name) {
VALID_OR_RETURN(swift::Identifier());
return GetASTContext()->getIdentifier(name);
}
ConstString SwiftASTContext::GetMangledTypeName(swift::TypeBase *type_base) {
VALID_OR_RETURN(ConstString());
auto iter = m_type_to_mangled_name_map.find(type_base),
end = m_type_to_mangled_name_map.end();
if (iter != end)
return ConstString(iter->second);
swift::Type swift_type(type_base);
bool has_archetypes = swift_type->hasArchetype();
if (!has_archetypes) {
swift::Mangle::ASTMangler mangler(true);
std::string s = mangler.mangleTypeForDebugger(swift_type, nullptr, nullptr);
if (!s.empty()) {
ConstString mangled_cs(s.c_str());
CacheDemangledType(mangled_cs.AsCString(), type_base);
return mangled_cs;
}
}
return ConstString();
}
void SwiftASTContext::CacheDemangledType(const char *name,
swift::TypeBase *found_type) {
VALID_OR_RETURN_VOID();
m_type_to_mangled_name_map.insert(std::make_pair(found_type, name));
m_mangled_name_to_type_map.insert(std::make_pair(name, found_type));
}
void SwiftASTContext::CacheDemangledTypeFailure(const char *name) {
VALID_OR_RETURN_VOID();
m_negative_type_cache.Insert(name);
}
CompilerType
SwiftASTContext::GetTypeFromMangledTypename(const char *mangled_typename,
Status &error) {
VALID_OR_RETURN(CompilerType());
if (mangled_typename
&& SwiftLanguageRuntime::IsSwiftMangledName(mangled_typename)) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s')",
this, mangled_typename);
swift::ASTContext *ast_ctx = GetASTContext();
if (!ast_ctx) {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s') "
"-- null Swift AST Context",
this, mangled_typename);
error.SetErrorString("null Swift AST Context");
return CompilerType();
}
error.Clear();
// If we were to crash doing this, remember what type caused it
llvm::PrettyStackTraceFormat PST("error finding type for %s",
mangled_typename);
ConstString mangled_name(mangled_typename);
swift::TypeBase *found_type =
m_mangled_name_to_type_map.lookup(mangled_name.GetCString());
if (found_type) {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s') "
"-- found in the positive cache",
this, mangled_typename);
return CompilerType(ast_ctx, found_type);
}
if (m_negative_type_cache.Lookup(mangled_name.GetCString())) {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s') "
"-- found in the negative cache",
this, mangled_typename);
return CompilerType();
}
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s') -- "
"not cached, searching",
this, mangled_typename);
std::string swift_error;
found_type = swift::ide::getTypeFromMangledSymbolname(
*ast_ctx, mangled_typename, swift_error)
.getPointer();
if (found_type) {
CacheDemangledType(mangled_name.GetCString(), found_type);
CompilerType result_type(ast_ctx, found_type);
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s') "
"-- found %s",
this, mangled_typename,
result_type.GetTypeName().GetCString());
return result_type;
} else {
if (log)
log->Printf("((SwiftASTContext*)%p)->GetTypeFromMangledTypename('%s') "
"-- error: %s",
this, mangled_typename, swift_error.c_str());
error.SetErrorStringWithFormat("type for typename '%s' was not found",
mangled_typename);
CacheDemangledTypeFailure(mangled_name.GetCString());
return CompilerType();
}
}
error.SetErrorStringWithFormat("typename '%s' is not a valid Swift mangled "
"typename, it should begin with _T",
mangled_typename);
return CompilerType();
}
CompilerType SwiftASTContext::GetVoidFunctionType() {
VALID_OR_RETURN(CompilerType());
if (!m_void_function_type) {
swift::ASTContext *ast = GetASTContext();
swift::Type empty_tuple_type(swift::TupleType::getEmpty(*ast));
m_void_function_type = CompilerType(
ast, swift::FunctionType::get(empty_tuple_type, empty_tuple_type));
}
return m_void_function_type;
}
static CompilerType ValueDeclToType(swift::ValueDecl *decl,
swift::ASTContext *ast) {
if (decl) {
switch (decl->getKind()) {
case swift::DeclKind::TypeAlias: {
swift::TypeAliasDecl *alias_decl = swift::cast<swift::TypeAliasDecl>(decl);
if (alias_decl->hasInterfaceType()) {
swift::Type swift_type =
swift::NameAliasType::get(
alias_decl, swift::Type(),
swift::SubstitutionMap(),
alias_decl->getUnderlyingTypeLoc().getType());
return CompilerType(ast, swift_type.getPointer());
}
break;
}
case swift::DeclKind::Enum:
case swift::DeclKind::Struct:
case swift::DeclKind::Protocol:
case swift::DeclKind::Class: {
swift::NominalTypeDecl *nominal_decl = swift::cast<swift::NominalTypeDecl>(decl);
if (nominal_decl->hasInterfaceType()) {
swift::Type swift_type = nominal_decl->getDeclaredType();
return CompilerType(ast, swift_type.getPointer());
}
} break;
default:
break;
}
}
return CompilerType();
}
CompilerType SwiftASTContext::FindQualifiedType(const char *qualified_name) {
VALID_OR_RETURN(CompilerType());
if (qualified_name && qualified_name[0]) {
const char *dot_pos = strchr(qualified_name, '.');
if (dot_pos) {
ConstString module_name(qualified_name, dot_pos - qualified_name);
swift::ModuleDecl *swift_module = GetCachedModule(module_name);
if (swift_module) {
swift::ModuleDecl::AccessPathTy access_path;
llvm::SmallVector<swift::ValueDecl *, 4> decls;
const char *module_type_name = dot_pos + 1;
swift_module->lookupValue(access_path, GetIdentifier(module_type_name),
swift::NLKind::UnqualifiedLookup, decls);
for (auto decl : decls) {
CompilerType type = ValueDeclToType(decl, GetASTContext());
if (type)
return type;
}
}
}
}
return CompilerType();
}
static CompilerType DeclToType(swift::Decl *decl, swift::ASTContext *ast) {
if (swift::ValueDecl *value_decl =
swift::dyn_cast_or_null<swift::ValueDecl>(decl))
return ValueDeclToType(value_decl, ast);
return CompilerType();
}
static SwiftASTContext::TypeOrDecl DeclToTypeOrDecl(swift::ASTContext *ast,
swift::Decl *decl) {
if (decl) {
switch (decl->getKind()) {
case swift::DeclKind::Import:
case swift::DeclKind::Extension:
case swift::DeclKind::PatternBinding:
case swift::DeclKind::TopLevelCode:
case swift::DeclKind::GenericTypeParam:
case swift::DeclKind::AssociatedType:
case swift::DeclKind::EnumElement:
case swift::DeclKind::EnumCase:
case swift::DeclKind::IfConfig:
case swift::DeclKind::Param:
case swift::DeclKind::Module:
case swift::DeclKind::MissingMember:
break;
case swift::DeclKind::InfixOperator:
case swift::DeclKind::PrefixOperator:
case swift::DeclKind::PostfixOperator:
case swift::DeclKind::PrecedenceGroup:
return decl;
case swift::DeclKind::TypeAlias: {
swift::TypeAliasDecl *alias_decl =
swift::cast<swift::TypeAliasDecl>(decl);
if (alias_decl->hasInterfaceType()) {
swift::Type swift_type =
swift::NameAliasType::get(
alias_decl, swift::Type(),
swift::SubstitutionMap(),
alias_decl->getUnderlyingTypeLoc().getType());
return CompilerType(ast, swift_type.getPointer());
}
} break;
case swift::DeclKind::Enum:
case swift::DeclKind::Struct:
case swift::DeclKind::Class:
case swift::DeclKind::Protocol: {
swift::NominalTypeDecl *nominal_decl =
swift::cast<swift::NominalTypeDecl>(decl);
if (nominal_decl->hasInterfaceType()) {
swift::Type swift_type = nominal_decl->getDeclaredType();
return CompilerType(ast, swift_type.getPointer());
}
} break;
case swift::DeclKind::Func:
case swift::DeclKind::Var:
return decl;
case swift::DeclKind::Subscript:
case swift::DeclKind::Constructor:
case swift::DeclKind::Destructor:
break;
}
}
return CompilerType();
}
size_t
SwiftASTContext::FindContainedTypeOrDecl(llvm::StringRef name,
TypeOrDecl container_type_or_decl,
TypesOrDecls &results, bool append) {
VALID_OR_RETURN(0);
if (!append)
results.clear();
size_t size_before = results.size();
CompilerType container_type = container_type_or_decl.Apply<CompilerType>(
[](CompilerType type) -> CompilerType { return type; },
[this](swift::Decl *decl) -> CompilerType {
return DeclToType(decl, GetASTContext());
});
if (false == name.empty() &&
llvm::dyn_cast_or_null<SwiftASTContext>(container_type.GetTypeSystem())) {
swift::Type swift_type(GetSwiftType(container_type));
if (!swift_type)
return 0;
swift::CanType swift_can_type(swift_type->getCanonicalType());
swift::NominalType *nominal_type =
swift_can_type->getAs<swift::NominalType>();
if (!nominal_type)
return 0;
swift::NominalTypeDecl *nominal_decl = nominal_type->getDecl();
llvm::ArrayRef<swift::ValueDecl *> decls =
nominal_decl->lookupDirect(
swift::DeclName(m_ast_context_ap->getIdentifier(name)));
for (auto decl : decls)
results.emplace(DeclToTypeOrDecl(GetASTContext(), decl));
}
return results.size() - size_before;
}
CompilerType SwiftASTContext::FindType(const char *name,
swift::ModuleDecl *swift_module) {
VALID_OR_RETURN(CompilerType());
std::set<CompilerType> search_results;
FindTypes(name, swift_module, search_results, false);
if (search_results.empty())
return CompilerType();
else
return *search_results.begin();
}
llvm::Optional<SwiftASTContext::TypeOrDecl>
SwiftASTContext::FindTypeOrDecl(const char *name,
swift::ModuleDecl *swift_module) {
VALID_OR_RETURN(llvm::Optional<SwiftASTContext::TypeOrDecl>());
TypesOrDecls search_results;
FindTypesOrDecls(name, swift_module, search_results, false);
if (search_results.empty())
return llvm::Optional<SwiftASTContext::TypeOrDecl>();
else
return *search_results.begin();
}
size_t SwiftASTContext::FindTypes(const char *name,
swift::ModuleDecl *swift_module,
std::set<CompilerType> &results,
bool append) {
VALID_OR_RETURN(0);
if (!append)
results.clear();
size_t before = results.size();
TypesOrDecls types_or_decls_results;
FindTypesOrDecls(name, swift_module, types_or_decls_results);
for (const auto &result : types_or_decls_results) {
CompilerType type = result.Apply<CompilerType>(
[](CompilerType type) -> CompilerType { return type; },
[this](swift::Decl *decl) -> CompilerType {
if (swift::ValueDecl *value_decl =
swift::dyn_cast_or_null<swift::ValueDecl>(decl)) {
if (value_decl->hasInterfaceType()) {
swift::Type swift_type = value_decl->getInterfaceType();
swift::MetatypeType *meta_type =
swift_type->getAs<swift::MetatypeType>();
swift::ASTContext *ast = GetASTContext();
if (meta_type)
return CompilerType(ast,
meta_type->getInstanceType().getPointer());
else
return CompilerType(ast, swift_type.getPointer());
}
}
return CompilerType();
});
results.emplace(type);
}
return results.size() - before;
}
size_t SwiftASTContext::FindTypesOrDecls(const char *name,
swift::ModuleDecl *swift_module,
TypesOrDecls &results, bool append) {
VALID_OR_RETURN(0);
if (!append)
results.clear();
size_t before = results.size();
if (name && name[0] && swift_module) {
swift::ModuleDecl::AccessPathTy access_path;
llvm::SmallVector<swift::ValueDecl *, 4> value_decls;
swift::Identifier identifier(GetIdentifier(name));
if (strchr(name, '.'))
swift_module->lookupValue(access_path, identifier,
swift::NLKind::QualifiedLookup, value_decls);
else
swift_module->lookupValue(access_path, identifier,
swift::NLKind::UnqualifiedLookup, value_decls);
if (identifier.isOperator()) {
swift::OperatorDecl *op_decl =
swift_module->lookupPrefixOperator(identifier);
if (op_decl)
results.emplace(DeclToTypeOrDecl(GetASTContext(), op_decl));
if ((op_decl = swift_module->lookupInfixOperator(identifier)))
results.emplace(DeclToTypeOrDecl(GetASTContext(), op_decl));
if ((op_decl = swift_module->lookupPostfixOperator(identifier)))
results.emplace(DeclToTypeOrDecl(GetASTContext(), op_decl));
}
if (swift::PrecedenceGroupDecl *pg_decl =
swift_module->lookupPrecedenceGroup(identifier))
results.emplace(DeclToTypeOrDecl(GetASTContext(), pg_decl));
for (auto decl : value_decls)
results.emplace(DeclToTypeOrDecl(GetASTContext(), decl));
}
return results.size() - before;
}
size_t SwiftASTContext::FindType(const char *name,
std::set<CompilerType> &results, bool append) {
VALID_OR_RETURN(0);
if (!append)
results.clear();
auto iter = m_swift_module_cache.begin(), end = m_swift_module_cache.end();
size_t count = 0;
std::function<void(swift::ModuleDecl *)> lookup_func =
[this, name, &results, &count](swift::ModuleDecl *module) -> void {
CompilerType candidate(this->FindType(name, module));
if (candidate) {
++count;
results.insert(candidate);
}
};
for (; iter != end; iter++)
lookup_func(iter->second);
if (m_scratch_module)
lookup_func(m_scratch_module);
return count;
}
CompilerType SwiftASTContext::FindFirstType(const char *name,
const ConstString &module_name) {
VALID_OR_RETURN(CompilerType());
if (name && name[0]) {
if (module_name) {
return FindType(name, GetCachedModule(module_name));
} else {
std::set<CompilerType> types;
FindType(name, types);
if (!types.empty())
return *types.begin();
}
}
return CompilerType();
}
CompilerType SwiftASTContext::ImportType(CompilerType &type, Status &error) {
VALID_OR_RETURN(CompilerType());
if (m_ast_context_ap.get() == NULL)
return CompilerType();
SwiftASTContext *swift_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem());
if (swift_ast_ctx == nullptr) {
error.SetErrorString("Can't import clang type into a Swift ASTContext.");
return CompilerType();
} else if (swift_ast_ctx == this) {
// This is the same AST context, so the type is already imported...
return type;
}
// For now we're going to do this all using mangled names. If we find that is
// too slow, we can use the TypeBase * in the CompilerType to match this to
// the version of the type we got from the mangled name in the original
// swift::ASTContext.
ConstString mangled_name(type.GetMangledTypeName());
if (mangled_name) {
swift::TypeBase *our_type_base =
m_mangled_name_to_type_map.lookup(mangled_name.GetCString());
if (our_type_base)
return CompilerType(m_ast_context_ap.get(), our_type_base);
else {
Status error;
CompilerType our_type(
GetTypeFromMangledTypename(mangled_name.GetCString(), error));
if (error.Success())
return our_type;
}
}
return CompilerType();
}
swift::IRGenDebugInfoKind SwiftASTContext::GetGenerateDebugInfo() {
return GetIRGenOptions().DebugInfoKind;
}
swift::PrintOptions SwiftASTContext::GetUserVisibleTypePrintingOptions(
bool print_help_if_available) {
swift::PrintOptions print_options;
print_options.SynthesizeSugarOnTypes = true;
print_options.VarInitializers = true;
print_options.TypeDefinitions = true;
print_options.PrintGetSetOnRWProperties = true;
print_options.SkipImplicit = false;
print_options.PreferTypeRepr = true;
print_options.FunctionDefinitions = true;
print_options.FullyQualifiedTypesIfAmbiguous = true;
print_options.FullyQualifiedTypes = true;
print_options.ExplodePatternBindingDecls = false;
print_options.PrintDocumentationComments =
print_options.PrintRegularClangComments = print_help_if_available;
return print_options;
}
void SwiftASTContext::SetGenerateDebugInfo(swift::IRGenDebugInfoKind b) {
GetIRGenOptions().DebugInfoKind = b;
}
llvm::TargetOptions *SwiftASTContext::getTargetOptions() {
if (m_target_options_ap.get() == NULL) {
m_target_options_ap.reset(new llvm::TargetOptions());
}
return m_target_options_ap.get();
}
swift::ModuleDecl *SwiftASTContext::GetScratchModule() {
VALID_OR_RETURN(nullptr);
if (m_scratch_module == nullptr)
m_scratch_module = swift::ModuleDecl::create(
GetASTContext()->getIdentifier("__lldb_scratch_module"),
*GetASTContext());
return m_scratch_module;
}
swift::SILModule *SwiftASTContext::GetSILModule() {
VALID_OR_RETURN(nullptr);
if (m_sil_module_ap.get() == NULL)
m_sil_module_ap = swift::SILModule::createEmptyModule(GetScratchModule(),
GetSILOptions());
return m_sil_module_ap.get();
}
swift::irgen::IRGenerator &
SwiftASTContext::GetIRGenerator(swift::IRGenOptions &opts,
swift::SILModule &module) {
if (m_ir_generator_ap.get() == nullptr) {
m_ir_generator_ap.reset(new swift::irgen::IRGenerator(opts, module));
}
return *m_ir_generator_ap.get();
}
swift::irgen::IRGenModule &SwiftASTContext::GetIRGenModule() {
VALID_OR_RETURN(*m_ir_gen_module_ap);
if (m_ir_gen_module_ap.get() == NULL) {
// Make sure we have a good ClangImporter.
GetClangImporter();
swift::IRGenOptions &ir_gen_opts = GetIRGenOptions();
std::string error_str;
std::string triple = GetTriple();
const llvm::Target *llvm_target =
llvm::TargetRegistry::lookupTarget(triple, error_str);
llvm::CodeGenOpt::Level optimization_level = llvm::CodeGenOpt::Level::None;
// Create a target machine.
llvm::TargetMachine *target_machine = llvm_target->createTargetMachine(
triple,
"generic", // cpu
"", // features
*getTargetOptions(),
llvm::Reloc::Static, // TODO verify with Sean, Default went away
llvm::None, optimization_level);
if (target_machine) {
// Set the module's string representation.
const llvm::DataLayout data_layout = target_machine->createDataLayout();
llvm::Triple llvm_triple(triple);
swift::SILModule *sil_module = GetSILModule();
if (sil_module != nullptr) {
swift::irgen::IRGenerator &ir_generator =
GetIRGenerator(ir_gen_opts, *sil_module);
swift::PrimarySpecificPaths PSPs =
GetCompilerInvocation()
.getFrontendOptions()
.InputsAndOutputs.getPrimarySpecificPathsForAtMostOnePrimary();
m_ir_gen_module_ap.reset(new swift::irgen::IRGenModule(
ir_generator, ir_generator.createTargetMachine(), nullptr,
GetGlobalLLVMContext(), ir_gen_opts.ModuleName, PSPs.OutputFilename,
PSPs.MainInputFilenameForDebugInfo));
llvm::Module *llvm_module = m_ir_gen_module_ap->getModule();
llvm_module->setDataLayout(data_layout.getStringRepresentation());
llvm_module->setTargetTriple(triple);
}
}
}
return *m_ir_gen_module_ap;
}
CompilerType
SwiftASTContext::CreateTupleType(const std::vector<CompilerType> &elements) {
VALID_OR_RETURN(CompilerType());
Status error;
if (elements.size() == 0)
return CompilerType(GetASTContext(), GetASTContext()->TheEmptyTupleType);
else {
std::vector<swift::TupleTypeElt> tuple_elems;
for (const CompilerType &type : elements) {
if (auto swift_type = GetSwiftType(type))
tuple_elems.push_back(swift::TupleTypeElt(swift_type));
else
return CompilerType();
}
llvm::ArrayRef<swift::TupleTypeElt> fields(tuple_elems);
return CompilerType(
GetASTContext(),
swift::TupleType::get(fields, *GetASTContext()).getPointer());
}
}
CompilerType
SwiftASTContext::CreateTupleType(const std::vector<TupleElement> &elements) {
VALID_OR_RETURN(CompilerType());
Status error;
if (elements.size() == 0)
return CompilerType(GetASTContext(), GetASTContext()->TheEmptyTupleType);
else {
std::vector<swift::TupleTypeElt> tuple_elems;
for (const TupleElement &element : elements) {
if (auto swift_type = GetSwiftType(element.element_type)) {
if (element.element_name.IsEmpty())
tuple_elems.push_back(swift::TupleTypeElt(swift_type));
else
tuple_elems.push_back(swift::TupleTypeElt(
swift_type, m_ast_context_ap->getIdentifier(
element.element_name.GetCString())));
} else
return CompilerType();
}
llvm::ArrayRef<swift::TupleTypeElt> fields(tuple_elems);
return CompilerType(
GetASTContext(),
swift::TupleType::get(fields, *GetASTContext()).getPointer());
}
}
CompilerType SwiftASTContext::CreateFunctionType(CompilerType arg_type,
CompilerType ret_type,
bool throws) {
VALID_OR_RETURN(CompilerType());
if (!llvm::dyn_cast_or_null<SwiftASTContext>(arg_type.GetTypeSystem()) ||
!llvm::dyn_cast_or_null<SwiftASTContext>(ret_type.GetTypeSystem()))
return CompilerType();
swift::FunctionType::ExtInfo ext_info;
if (throws)
ext_info = ext_info.withThrows();
return CompilerType(GetASTContext(), swift::FunctionType::get(
GetSwiftType(arg_type),
GetSwiftType(ret_type), ext_info));
}
CompilerType SwiftASTContext::GetErrorType() {
VALID_OR_RETURN(CompilerType());
swift::ASTContext *swift_ctx = GetASTContext();
if (swift_ctx) {
// Getting the error type requires the Stdlib module be loaded, but doesn't
// cause it to be loaded.
// Do that here:
swift_ctx->getStdlibModule(true);
swift::NominalTypeDecl *error_type_decl = GetASTContext()->getErrorDecl();
if (error_type_decl) {
auto error_type = error_type_decl->getDeclaredType().getPointer();
return CompilerType(GetASTContext(), error_type);
}
}
return CompilerType();
}
CompilerType SwiftASTContext::GetNSErrorType(Status &error) {
VALID_OR_RETURN(CompilerType());
return GetTypeFromMangledTypename(SwiftLanguageRuntime::GetCurrentMangledName("_TtC10Foundation7NSError").c_str(), error);
}
CompilerType SwiftASTContext::CreateMetatypeType(CompilerType instance_type) {
VALID_OR_RETURN(CompilerType());
if (llvm::dyn_cast_or_null<SwiftASTContext>(instance_type.GetTypeSystem()))
return CompilerType(GetASTContext(),
swift::MetatypeType::get(GetSwiftType(instance_type),
*GetASTContext()));
return CompilerType();
}
SwiftASTContext *SwiftASTContext::GetSwiftASTContext(swift::ASTContext *ast) {
SwiftASTContext *swift_ast = GetASTMap().Lookup(ast);
return swift_ast;
}
uint32_t SwiftASTContext::GetPointerByteSize() {
VALID_OR_RETURN(0);
if (m_pointer_byte_size == 0) {
swift::ASTContext *ast = GetASTContext();
m_pointer_byte_size = CompilerType(ast, ast->TheRawPointerType.getPointer())
.GetByteSize(nullptr);
}
return m_pointer_byte_size;
}
uint32_t SwiftASTContext::GetPointerBitAlignment() {
VALID_OR_RETURN(0);
if (m_pointer_bit_align == 0) {
swift::ASTContext *ast = GetASTContext();
m_pointer_bit_align = CompilerType(ast, ast->TheRawPointerType.getPointer())
.GetAlignedBitSize();
}
return m_pointer_bit_align;
}
bool SwiftASTContext::HasErrors() {
if (m_diagnostic_consumer_ap.get())
return (
static_cast<StoringDiagnosticConsumer *>(m_diagnostic_consumer_ap.get())
->NumErrors() != 0);
else
return false;
}
bool SwiftASTContext::HasFatalErrors(swift::ASTContext *ast_context) {
return (ast_context && ast_context->Diags.hasFatalErrorOccurred());
}
void SwiftASTContext::ClearDiagnostics() {
assert(!HasFatalErrors() && "Never clear a fatal diagnostic!");
if (m_diagnostic_consumer_ap.get())
static_cast<StoringDiagnosticConsumer *>(m_diagnostic_consumer_ap.get())
->Clear();
}
bool SwiftASTContext::SetColorizeDiagnostics(bool b) {
if (m_diagnostic_consumer_ap.get())
return static_cast<StoringDiagnosticConsumer *>(
m_diagnostic_consumer_ap.get())
->SetColorize(b);
return false;
}
void SwiftASTContext::PrintDiagnostics(DiagnosticManager &diagnostic_manager,
uint32_t bufferID, uint32_t first_line,
uint32_t last_line,
uint32_t line_offset) {
// If this is a fatal error, copy the error into the AST context's fatal error
// field, and then put it to the stream, otherwise just dump the diagnostics
// to the stream.
// N.B. you cannot use VALID_OR_RETURN_VOID here since that exits if you have
// fatal errors, which are what we are trying to print here.
if (!m_ast_context_ap.get()) {
SymbolFile *sym_file = GetSymbolFile();
if (sym_file) {
ConstString name
= sym_file->GetObjectFile()->GetModule()->GetObjectName();
m_fatal_errors.SetErrorStringWithFormat(
"Null context for %s.", name.AsCString());
} else {
m_fatal_errors.SetErrorString("Unknown fatal error occurred.");
}
return;
}
if (m_ast_context_ap->Diags.hasFatalErrorOccurred() &&
!m_reported_fatal_error) {
DiagnosticManager fatal_diagnostics;
if (m_diagnostic_consumer_ap.get())
static_cast<StoringDiagnosticConsumer *>(m_diagnostic_consumer_ap.get())
->PrintDiagnostics(fatal_diagnostics, bufferID, first_line, last_line,
line_offset);
if (fatal_diagnostics.Diagnostics().size())
m_fatal_errors.SetErrorString(fatal_diagnostics.GetString().data());
else
m_fatal_errors.SetErrorString("Unknown fatal error occurred.");
m_reported_fatal_error = true;
for (const DiagnosticList::value_type &fatal_diagnostic :
fatal_diagnostics.Diagnostics()) {
// FIXME: need to add a CopyDiagnostic operation for copying diagnostics
// from one manager to another.
diagnostic_manager.AddDiagnostic(
fatal_diagnostic->GetMessage(), fatal_diagnostic->GetSeverity(),
fatal_diagnostic->getKind(), fatal_diagnostic->GetCompilerID());
}
} else {
if (m_diagnostic_consumer_ap.get())
static_cast<StoringDiagnosticConsumer *>(m_diagnostic_consumer_ap.get())
->PrintDiagnostics(diagnostic_manager, bufferID, first_line,
last_line, line_offset);
}
}
void SwiftASTContext::ModulesDidLoad(ModuleList &module_list) {
ClearModuleDependentCaches();
}
void SwiftASTContext::ClearModuleDependentCaches() {
m_negative_type_cache.Clear();
m_extra_type_info_cache.Clear();
}
void SwiftASTContext::DumpConfiguration(Log *log) {
VALID_OR_RETURN_VOID();
if (!log)
return;
log->Printf("(SwiftASTContext*)%p:", this);
if (!m_ast_context_ap)
log->Printf(" (no AST context)");
log->Printf(" Architecture : %s",
m_ast_context_ap->LangOpts.Target.getTriple().c_str());
log->Printf(" SDK path : %s",
m_ast_context_ap->SearchPathOpts.SDKPath.c_str());
log->Printf(" Runtime resource path : %s",
m_ast_context_ap->SearchPathOpts.RuntimeResourcePath.c_str());
log->Printf(" Runtime library path : %s",
m_ast_context_ap->SearchPathOpts.RuntimeLibraryPath.c_str());
log->Printf(
" Runtime library import path : %s",
m_ast_context_ap->SearchPathOpts.RuntimeLibraryImportPath.c_str());
log->Printf(" Framework search paths : (%llu items)",
(unsigned long long)
m_ast_context_ap->SearchPathOpts.FrameworkSearchPaths.size());
for (const auto &framework_search_path :
m_ast_context_ap->SearchPathOpts.FrameworkSearchPaths) {
log->Printf(" %s", framework_search_path.Path.c_str());
}
log->Printf(" Import search paths : (%llu items)",
(unsigned long long)
m_ast_context_ap->SearchPathOpts.ImportSearchPaths.size());
for (std::string &import_search_path :
m_ast_context_ap->SearchPathOpts.ImportSearchPaths) {
log->Printf(" %s", import_search_path.c_str());
}
swift::ClangImporterOptions &clang_importer_options =
GetClangImporterOptions();
log->Printf(" Extra clang arguments : (%llu items)",
(unsigned long long)clang_importer_options.ExtraArgs.size());
for (std::string &extra_arg : clang_importer_options.ExtraArgs) {
log->Printf(" %s", extra_arg.c_str());
}
}
bool SwiftASTContext::HasTarget() const {
lldb::TargetWP empty_wp;
// If either call to "std::weak_ptr::owner_before(...) value returns true,
// this indicates that m_section_wp once contained (possibly still does) a
// reference to a valid shared pointer. This helps us know if we had a valid
// reference to a target which is now invalid because the target was deleted.
return empty_wp.owner_before(m_target_wp) ||
m_target_wp.owner_before(empty_wp);
}
bool SwiftASTContext::CheckProcessChanged() {
if (HasTarget()) {
TargetSP target_sp(m_target_wp.lock());
if (target_sp) {
Process *process = target_sp->GetProcessSP().get();
if (m_process == NULL) {
if (process)
m_process = process;
} else {
if (m_process != process)
return true;
}
}
}
return false;
}
void SwiftASTContext::AddDebuggerClient(
swift::DebuggerClient *debugger_client) {
m_debugger_clients.push_back(
std::unique_ptr<swift::DebuggerClient>(debugger_client));
}
SwiftASTContext::ExtraTypeInformation::ExtraTypeInformation()
: m_flags(false, false) {}
SwiftASTContext::ExtraTypeInformation::ExtraTypeInformation(
swift::CanType swift_can_type)
: m_flags(false, false) {
static ConstString g_rawValue("rawValue");
swift::ASTContext &ast_ctx = swift_can_type->getASTContext();
SwiftASTContext *swift_ast = SwiftASTContext::GetSwiftASTContext(&ast_ctx);
if (swift_ast) {
swift::ProtocolDecl *option_set =
ast_ctx.getProtocol(swift::KnownProtocolKind::OptionSet);
if (option_set) {
if (auto nominal_decl =
swift_can_type.getNominalOrBoundGenericNominal()) {
for (swift::ProtocolDecl *protocol_decl :
nominal_decl->getAllProtocols()) {
if (protocol_decl == option_set) {
for (swift::VarDecl *stored_property :
nominal_decl->getStoredProperties()) {
swift::Identifier name = stored_property->getName();
if (name.str() == g_rawValue.GetStringRef()) {
m_flags.m_is_trivial_option_set = true;
break;
}
}
}
}
}
}
}
if (auto metatype_type = swift::dyn_cast_or_null<swift::MetatypeType>(
swift_can_type)) {
if (!metatype_type->hasRepresentation() ||
(swift::MetatypeRepresentation::Thin ==
metatype_type->getRepresentation()))
m_flags.m_is_zero_size = true;
} else if (auto enum_decl = swift_can_type->getEnumOrBoundGenericEnum()) {
size_t num_nopayload = 0, num_payload = 0;
for (auto the_case : enum_decl->getAllElements()) {
if (the_case->getArgumentInterfaceType()) {
num_payload = 1;
break;
} else {
if (++num_nopayload > 1)
break;
}
}
if (num_nopayload == 1 && num_payload == 0)
m_flags.m_is_zero_size = true;
} else if (auto struct_decl =
swift_can_type->getStructOrBoundGenericStruct()) {
bool has_storage = false;
auto members = struct_decl->getMembers();
for (const auto &member : members) {
if (swift::VarDecl *var_decl =
swift::dyn_cast<swift::VarDecl>(member)) {
if (!var_decl->isStatic() && var_decl->hasStorage()) {
has_storage = true;
break;
}
}
}
m_flags.m_is_zero_size = !has_storage;
} else if (auto tuple_type = swift::dyn_cast_or_null<swift::TupleType>(
swift_can_type)) {
m_flags.m_is_zero_size = (tuple_type->getNumElements() == 0);
}
}
SwiftASTContext::ExtraTypeInformation
SwiftASTContext::GetExtraTypeInformation(void *type) {
if (!type)
return ExtraTypeInformation();
swift::CanType swift_can_type;
void *swift_can_type_ptr = nullptr;
if (auto swift_type = GetSwiftType(type)) {
swift_can_type = swift_type->getCanonicalType();
swift_can_type_ptr = swift_can_type.getPointer();
}
if (!swift_can_type_ptr)
return ExtraTypeInformation();
ExtraTypeInformation eti;
if (!m_extra_type_info_cache.Lookup(swift_can_type_ptr, eti)) {
ExtraTypeInformation extra_info(swift_can_type);
m_extra_type_info_cache.Insert(swift_can_type_ptr, extra_info);
return extra_info;
} else {
return eti;
}
}
bool SwiftASTContext::DeclContextIsStructUnionOrClass(void *opaque_decl_ctx) {
return false;
}
ConstString SwiftASTContext::DeclContextGetName(void *opaque_decl_ctx) {
return ConstString();
}
ConstString
SwiftASTContext::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
return ConstString();
}
bool SwiftASTContext::DeclContextIsClassMethod(
void *opaque_decl_ctx, lldb::LanguageType *language_ptr,
bool *is_instance_method_ptr, ConstString *language_object_name_ptr) {
return false;
}
///////////
////////////////////
///////////
bool SwiftASTContext::IsArrayType(void *type, CompilerType *element_type_ptr,
uint64_t *size, bool *is_incomplete) {
VALID_OR_RETURN(false);
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
swift::BoundGenericStructType *struct_type =
swift_can_type->getAs<swift::BoundGenericStructType>();
if (struct_type) {
swift::StructDecl *struct_decl = struct_type->getDecl();
if (strcmp(struct_decl->getName().get(), "Array") != 0)
return false;
if (!struct_decl->getModuleContext()->isStdlibModule())
return false;
const llvm::ArrayRef<swift::Type> &args = struct_type->getGenericArgs();
if (args.size() != 1)
return false;
if (is_incomplete)
*is_incomplete = true;
if (size)
*size = 0;
if (element_type_ptr)
*element_type_ptr =
CompilerType(GetASTContext(), args[0].getPointer());
return true;
}
return false;
}
bool SwiftASTContext::IsAggregateType(void *type) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
auto referent_type = swift_can_type->getReferenceStorageReferent();
return (referent_type->is<swift::TupleType>() ||
referent_type->is<swift::BuiltinVectorType>() ||
referent_type->getAnyNominal());
}
return false;
}
bool SwiftASTContext::IsVectorType(void *type, CompilerType *element_type,
uint64_t *size) {
return false;
}
bool SwiftASTContext::IsRuntimeGeneratedType(void *type) { return false; }
bool SwiftASTContext::IsCharType(void *type) { return false; }
bool SwiftASTContext::IsCompleteType(void *type) { return true; }
bool SwiftASTContext::IsConst(void *type) { return false; }
bool SwiftASTContext::IsCStringType(void *type, uint32_t &length) {
return false;
}
bool SwiftASTContext::IsFunctionType(void *type, bool *is_variadic_ptr) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
return true;
case swift::TypeKind::SILFunction:
return false; // TODO: is this correct?
default:
return false;
}
}
return false;
}
// Used to detect "Homogeneous Floating-point Aggregates"
uint32_t SwiftASTContext::IsHomogeneousAggregate(void *type,
CompilerType *base_type_ptr) {
return 0;
}
size_t SwiftASTContext::GetNumberOfFunctionArguments(void *type) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
auto func =
swift::dyn_cast_or_null<swift::AnyFunctionType>(
swift_can_type);
if (func) {
auto input = func.getInput();
// See comment in swift::AnyFunctionType for rationale here:
// A function can take either a tuple or a parentype, but if a parentype
// (i.e. (Foo)), then it will be reduced down to just Foo, so if the input
// is not a tuple, that must mean there is only 1 input.
auto tuple = swift::dyn_cast<swift::TupleType>(input);
if (tuple)
return tuple->getNumElements();
else
return 1;
}
}
return 0;
}
CompilerType SwiftASTContext::GetFunctionArgumentAtIndex(void *type,
const size_t index) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
auto func =
swift::dyn_cast<swift::AnyFunctionType>(
swift_can_type);
if (func) {
auto input = func.getInput();
// See comment in swift::AnyFunctionType for rationale here:
// A function can take either a tuple or a parentype, but if a parentype
// (i.e. (Foo)), then it will be reduced down to just Foo, so if the input
// is not a tuple, that must mean there is only 1 input.
auto tuple = swift::dyn_cast<swift::TupleType>(input);
if (tuple) {
if (index < tuple->getNumElements())
return CompilerType(GetASTContext(),
tuple->getElementType(index));
} else
return CompilerType(GetASTContext(), input);
}
}
return CompilerType();
}
bool SwiftASTContext::IsFunctionPointerType(void *type) {
return IsFunctionType(type, nullptr); // FIXME: think about this
}
bool SwiftASTContext::IsBlockPointerType(
void *type, CompilerType *function_pointer_type_ptr) {
return false;
}
bool SwiftASTContext::IsIntegerType(void *type, bool &is_signed) {
return (GetTypeInfo(type, nullptr) & eTypeIsInteger);
}
bool SwiftASTContext::IsPointerType(void *type, CompilerType *pointee_type) {
VALID_OR_RETURN(false);
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
auto referent_type = swift_can_type->getReferenceStorageReferent();
return (referent_type->is<swift::BuiltinRawPointerType>() ||
referent_type->is<swift::BuiltinNativeObjectType>() ||
referent_type->is<swift::BuiltinUnsafeValueBufferType>() ||
referent_type->is<swift::BuiltinUnknownObjectType>() ||
referent_type->is<swift::BuiltinBridgeObjectType>());
}
if (pointee_type)
pointee_type->Clear();
return false;
}
bool SwiftASTContext::IsPointerOrReferenceType(void *type,
CompilerType *pointee_type) {
return IsPointerType(type, pointee_type) ||
IsReferenceType(type, pointee_type, nullptr);
}
bool SwiftASTContext::ShouldTreatScalarValueAsAddress(
lldb::opaque_compiler_type_t type) {
return Flags(GetTypeInfo(type, nullptr))
.AnySet(eTypeInstanceIsPointer | eTypeIsReference);
}
bool SwiftASTContext::IsReferenceType(void *type, CompilerType *pointee_type,
bool *is_rvalue) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::InOut:
case swift::TypeKind::LValue:
if (pointee_type)
*pointee_type = GetNonReferenceType(type);
return true;
default:
break;
}
}
if (pointee_type)
pointee_type->Clear();
return false;
}
bool SwiftASTContext::IsFloatingPointType(void *type, uint32_t &count,
bool &is_complex) {
if (type) {
if (GetTypeInfo(type, nullptr) & eTypeIsFloat) {
count = 1;
is_complex = false;
return true;
}
}
count = 0;
is_complex = false;
return false;
}
bool SwiftASTContext::IsDefined(void *type) {
if (!type)
return false;
return true;
}
bool SwiftASTContext::IsPolymorphicClass(void *type) { return false; }
bool SwiftASTContext::IsPossibleDynamicType(void *type,
CompilerType *dynamic_pointee_type,
bool check_cplusplus,
bool check_objc, bool check_swift) {
VALID_OR_RETURN(false);
if (type && check_swift) {
// FIXME: use the dynamic_pointee_type
Flags type_flags(GetTypeInfo(type, nullptr));
if (type_flags.AnySet(eTypeIsArchetype | eTypeIsClass | eTypeIsProtocol))
return true;
if (type_flags.AnySet(eTypeIsStructUnion | eTypeIsEnumeration |
eTypeIsTuple)) {
CompilerType compiler_type(GetASTContext(), GetCanonicalSwiftType(type));
return !SwiftASTContext::IsFullyRealized(compiler_type);
}
auto can_type = GetCanonicalSwiftType(type).getPointer();
if (can_type == GetASTContext()->TheRawPointerType.getPointer())
return true;
if (can_type == GetASTContext()->TheUnknownObjectType.getPointer())
return true;
if (can_type == GetASTContext()->TheNativeObjectType.getPointer())
return true;
if (can_type == GetASTContext()->TheBridgeObjectType.getPointer())
return true;
}
if (dynamic_pointee_type)
dynamic_pointee_type->Clear();
return false;
}
bool SwiftASTContext::IsScalarType(void *type) {
if (!type)
return false;
return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
}
bool SwiftASTContext::IsTypedefType(void *type) {
if (!type)
return false;
swift::Type swift_type(GetSwiftType(type));
return swift::isa<swift::NameAliasType>(swift_type.getPointer());
}
bool SwiftASTContext::IsVoidType(void *type) {
VALID_OR_RETURN(false);
if (!type)
return false;
return type == GetASTContext()->TheEmptyTupleType.getPointer();
}
bool SwiftASTContext::IsArchetypeType(const CompilerType &compiler_type) {
if (!compiler_type.IsValid())
return false;
if (llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem())) {
swift::Type swift_type(GetSwiftType(compiler_type));
return swift_type->is<swift::ArchetypeType>();
}
return false;
}
bool SwiftASTContext::IsSelfArchetypeType(const CompilerType &compiler_type) {
if (!compiler_type.IsValid())
return false;
if (llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem())) {
if (swift::isa<swift::ArchetypeType>(
(swift::TypeBase *)compiler_type.GetOpaqueQualType())) {
// Hack: Just assume if we have an archetype as the type of 'self',
// it's going to be a protocol 'Self' type.
return true;
}
}
return false;
}
bool SwiftASTContext::IsPossibleZeroSizeType(
const CompilerType &compiler_type) {
if (!compiler_type.IsValid())
return false;
if (auto ast = llvm::dyn_cast_or_null<SwiftASTContext>(
compiler_type.GetTypeSystem()))
return ast
->GetExtraTypeInformation(
GetCanonicalSwiftType(compiler_type).getPointer())
.m_flags.m_is_zero_size;
return false;
}
bool SwiftASTContext::IsErrorType(const CompilerType &compiler_type) {
if (compiler_type.IsValid() &&
llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem())) {
ProtocolInfo protocol_info;
if (GetProtocolTypeInfo(compiler_type, protocol_info))
return protocol_info.m_is_errortype;
return false;
}
return false;
}
CompilerType
SwiftASTContext::GetReferentType(const CompilerType &compiler_type) {
VALID_OR_RETURN(CompilerType());
if (compiler_type.IsValid() &&
llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem())) {
swift::CanType swift_can_type(GetCanonicalSwiftType(compiler_type));
swift::TypeBase *swift_type = swift_can_type.getPointer();
if (swift_type && llvm::isa<swift::WeakStorageType>(swift_type))
return compiler_type;
auto ref_type = swift_can_type->getReferenceStorageReferent();
return CompilerType(GetASTContext(), ref_type);
}
return CompilerType();
}
bool SwiftASTContext::IsTrivialOptionSetType(
const CompilerType &compiler_type) {
if (compiler_type.IsValid() &&
llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem()))
return GetExtraTypeInformation(compiler_type.GetOpaqueQualType())
.m_flags.m_is_trivial_option_set;
return false;
}
bool SwiftASTContext::IsFullyRealized(const CompilerType &compiler_type) {
if (!compiler_type.IsValid())
return false;
if (auto ast = llvm::dyn_cast_or_null<SwiftASTContext>(
compiler_type.GetTypeSystem())) {
swift::CanType swift_can_type(GetCanonicalSwiftType(compiler_type));
if (swift::isa<swift::MetatypeType>(swift_can_type))
return true;
return !swift_can_type->hasArchetype() && !swift_can_type->hasTypeParameter();
}
return false;
}
bool SwiftASTContext::GetProtocolTypeInfo(const CompilerType &type,
ProtocolInfo &protocol_info) {
if (auto ast =
llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem())) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
if (!swift_can_type.isExistentialType())
return false;
swift::ExistentialLayout layout = swift_can_type.getExistentialLayout();
protocol_info.m_is_class_only = layout.requiresClass();
protocol_info.m_num_protocols = layout.getProtocols().size();
protocol_info.m_is_objc = layout.isObjC();
protocol_info.m_is_anyobject = layout.isAnyObject();
protocol_info.m_is_errortype = layout.isErrorExistential();
if (layout.superclass) {
protocol_info.m_superclass =
CompilerType(ast->GetASTContext(), layout.superclass.getPointer());
}
unsigned num_witness_tables = 0;
for (auto protoTy : layout.getProtocols()) {
if (!protoTy->getDecl()->isObjC())
num_witness_tables++;
}
if (layout.isErrorExistential()) {
// Error existential -- instance pointer only
protocol_info.m_num_payload_words = 0;
protocol_info.m_num_storage_words = 1;
} else if (layout.requiresClass()) {
// Class-constrained existential -- instance pointer plus witness tables
protocol_info.m_num_payload_words = 0;
protocol_info.m_num_storage_words = 1 + num_witness_tables;
} else {
// Opaque existential -- three words of inline storage, metadata and
// witness tables
protocol_info.m_num_payload_words = swift::NumWords_ValueBuffer;
protocol_info.m_num_storage_words =
swift::NumWords_ValueBuffer + 1 + num_witness_tables;
}
return true;
}
return false;
}
SwiftASTContext::TypeAllocationStrategy
SwiftASTContext::GetAllocationStrategy(const CompilerType &type) {
if (auto ast =
llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem())) {
const swift::irgen::TypeInfo *type_info =
ast->GetSwiftTypeInfo(type.GetOpaqueQualType());
if (!type_info)
return TypeAllocationStrategy::eUnknown;
switch (type_info->getFixedPacking(ast->GetIRGenModule())) {
case swift::irgen::FixedPacking::OffsetZero:
return TypeAllocationStrategy::eInline;
case swift::irgen::FixedPacking::Allocate:
return TypeAllocationStrategy::ePointer;
case swift::irgen::FixedPacking::Dynamic:
return TypeAllocationStrategy::eDynamic;
default:
break;
}
}
return TypeAllocationStrategy::eUnknown;
}
bool SwiftASTContext::IsBeingDefined(void *type) { return false; }
bool SwiftASTContext::IsObjCObjectPointerType(const CompilerType &type,
CompilerType *class_type_ptr) {
if (!type)
return false;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
if (type_kind == swift::TypeKind::BuiltinNativeObject ||
type_kind == swift::TypeKind::BuiltinUnknownObject)
return true;
if (class_type_ptr)
class_type_ptr->Clear();
return false;
}
//----------------------------------------------------------------------
// Type Completion
//----------------------------------------------------------------------
bool SwiftASTContext::GetCompleteType(void *type) { return true; }
ConstString SwiftASTContext::GetTypeName(void *type) {
std::string type_name;
if (type) {
swift::Type swift_type(GetSwiftType(type));
swift::Type normalized_type =
swift_type.transform([](swift::Type type) -> swift::Type {
if (swift::SyntaxSugarType *syntax_sugar_type =
swift::dyn_cast<swift::SyntaxSugarType>(type.getPointer())) {
return syntax_sugar_type->getSinglyDesugaredType();
}
if (swift::DictionaryType *dictionary_type =
swift::dyn_cast<swift::DictionaryType>(type.getPointer())) {
return dictionary_type->getSinglyDesugaredType();
}
return type;
});
swift::PrintOptions print_options;
print_options.FullyQualifiedTypes = true;
print_options.SynthesizeSugarOnTypes = false;
type_name = normalized_type.getString(print_options);
}
return ConstString(type_name);
}
ConstString SwiftASTContext::GetDisplayTypeName(void *type) {
std::string type_name(GetTypeName(type).AsCString(""));
if (type) {
swift::Type swift_type(GetSwiftType(type));
swift::PrintOptions print_options;
print_options.FullyQualifiedTypes = false;
print_options.SynthesizeSugarOnTypes = true;
print_options.FullyQualifiedTypesIfAmbiguous = true;
type_name = swift_type.getString(print_options);
}
return ConstString(type_name);
}
ConstString SwiftASTContext::GetTypeSymbolName(void *type) {
swift::Type swift_type(GetSwiftType(type));
return GetTypeName(swift_type->getWithoutParens().getPointer());
}
ConstString SwiftASTContext::GetMangledTypeName(void *type) {
return GetMangledTypeName(GetSwiftType(type).getPointer());
}
uint32_t
SwiftASTContext::GetTypeInfo(void *type,
CompilerType *pointee_or_element_clang_type) {
VALID_OR_RETURN(0);
if (!type)
return 0;
if (pointee_or_element_clang_type)
pointee_or_element_clang_type->Clear();
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
uint32_t swift_flags = eTypeIsSwift;
switch (type_kind) {
case swift::TypeKind::DependentMember:
case swift::TypeKind::Error:
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::Module:
case swift::TypeKind::TypeVariable:
break;
case swift::TypeKind::UnboundGeneric:
swift_flags |= eTypeIsGeneric;
break;
case swift::TypeKind::GenericFunction:
swift_flags |= eTypeIsGeneric;
case swift::TypeKind::Function:
swift_flags |=
eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar | eTypeInstanceIsPointer;
break;
case swift::TypeKind::BuiltinInteger:
swift_flags |=
eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar | eTypeIsInteger;
break;
case swift::TypeKind::BuiltinFloat:
swift_flags |=
eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar | eTypeIsFloat;
break;
case swift::TypeKind::BuiltinRawPointer:
swift_flags |= eTypeIsBuiltIn | eTypeHasChildren | eTypeIsPointer |
eTypeIsScalar | eTypeHasValue;
break;
case swift::TypeKind::BuiltinNativeObject:
swift_flags |= eTypeIsBuiltIn | eTypeHasChildren | eTypeIsPointer |
eTypeIsScalar | eTypeHasValue;
break;
case swift::TypeKind::BuiltinUnknownObject:
swift_flags |= eTypeIsBuiltIn | eTypeHasChildren | eTypeIsPointer |
eTypeIsScalar | eTypeHasValue | eTypeIsObjC;
break;
case swift::TypeKind::BuiltinBridgeObject:
swift_flags |= eTypeIsBuiltIn | eTypeHasChildren | eTypeIsPointer |
eTypeIsScalar | eTypeHasValue | eTypeIsObjC;
break;
case swift::TypeKind::BuiltinUnsafeValueBuffer:
swift_flags |=
eTypeIsBuiltIn | eTypeIsPointer | eTypeIsScalar | eTypeHasValue;
break;
case swift::TypeKind::BuiltinVector:
// TODO: OR in eTypeIsFloat or eTypeIsInteger as needed
return eTypeIsBuiltIn | eTypeHasChildren | eTypeIsVector;
break;
case swift::TypeKind::Tuple:
swift_flags |= eTypeHasChildren | eTypeIsTuple;
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
swift_flags |=
CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetTypeInfo(pointee_or_element_clang_type);
break;
case swift::TypeKind::BoundGenericEnum:
swift_flags |= eTypeIsGeneric | eTypeIsBound;
case swift::TypeKind::Enum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info) {
if (cached_enum_info->GetNumElementsWithPayload() == 0)
swift_flags |= eTypeHasValue | eTypeIsEnumeration;
else
swift_flags |= eTypeHasValue | eTypeIsEnumeration | eTypeHasChildren;
} else
swift_flags |= eTypeIsEnumeration;
} break;
case swift::TypeKind::BoundGenericStruct:
swift_flags |= eTypeIsGeneric | eTypeIsBound;
case swift::TypeKind::Struct:
swift_flags |= eTypeHasChildren | eTypeIsStructUnion;
break;
case swift::TypeKind::BoundGenericClass:
swift_flags |= eTypeIsGeneric | eTypeIsBound;
case swift::TypeKind::Class:
swift_flags |= eTypeHasChildren | eTypeIsClass | eTypeHasValue |
eTypeInstanceIsPointer;
break;
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition:
swift_flags |= eTypeHasChildren | eTypeIsStructUnion | eTypeIsProtocol;
break;
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
swift_flags |= eTypeIsMetatype | eTypeHasValue;
break;
case swift::TypeKind::Archetype:
swift_flags |=
eTypeHasValue | eTypeIsScalar | eTypeIsPointer | eTypeIsArchetype;
break;
case swift::TypeKind::LValue:
if (pointee_or_element_clang_type)
*pointee_or_element_clang_type = GetNonReferenceType(type);
swift_flags |= eTypeHasChildren | eTypeIsReference | eTypeHasValue;
break;
case swift::TypeKind::InOut:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return swift_flags;
}
lldb::LanguageType SwiftASTContext::GetMinimumLanguage(void *type) {
if (!type)
return lldb::eLanguageTypeC;
return lldb::eLanguageTypeSwift;
}
lldb::TypeClass SwiftASTContext::GetTypeClass(void *type) {
VALID_OR_RETURN(lldb::eTypeClassInvalid);
if (!type)
return lldb::eTypeClassInvalid;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
return lldb::eTypeClassOther;
case swift::TypeKind::BuiltinInteger:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinFloat:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinRawPointer:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinNativeObject:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinUnsafeValueBuffer:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinUnknownObject:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinBridgeObject:
return lldb::eTypeClassBuiltin;
case swift::TypeKind::BuiltinVector:
return lldb::eTypeClassVector;
case swift::TypeKind::Tuple:
return lldb::eTypeClassArray;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetTypeClass();
case swift::TypeKind::GenericTypeParam:
return lldb::eTypeClassOther;
case swift::TypeKind::DependentMember:
return lldb::eTypeClassOther;
case swift::TypeKind::Enum:
return lldb::eTypeClassUnion;
case swift::TypeKind::Struct:
return lldb::eTypeClassStruct;
case swift::TypeKind::Class:
return lldb::eTypeClassClass;
case swift::TypeKind::Protocol:
return lldb::eTypeClassOther;
case swift::TypeKind::Metatype:
return lldb::eTypeClassOther;
case swift::TypeKind::Module:
return lldb::eTypeClassOther;
case swift::TypeKind::Archetype:
return lldb::eTypeClassOther;
case swift::TypeKind::Function:
return lldb::eTypeClassFunction;
case swift::TypeKind::GenericFunction:
return lldb::eTypeClassFunction;
case swift::TypeKind::ProtocolComposition:
return lldb::eTypeClassOther;
case swift::TypeKind::LValue:
return lldb::eTypeClassReference;
case swift::TypeKind::UnboundGeneric:
return lldb::eTypeClassOther;
case swift::TypeKind::BoundGenericClass:
return lldb::eTypeClassClass;
case swift::TypeKind::BoundGenericEnum:
return lldb::eTypeClassUnion;
case swift::TypeKind::BoundGenericStruct:
return lldb::eTypeClassStruct;
case swift::TypeKind::TypeVariable:
return lldb::eTypeClassOther;
case swift::TypeKind::ExistentialMetatype:
return lldb::eTypeClassOther;
case swift::TypeKind::DynamicSelf:
return lldb::eTypeClassOther;
case swift::TypeKind::SILBox:
return lldb::eTypeClassOther;
case swift::TypeKind::SILFunction:
return lldb::eTypeClassFunction;
case swift::TypeKind::SILBlockStorage:
return lldb::eTypeClassOther;
case swift::TypeKind::InOut:
return lldb::eTypeClassOther;
case swift::TypeKind::Unresolved:
return lldb::eTypeClassOther;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return lldb::eTypeClassOther;
}
unsigned SwiftASTContext::GetTypeQualifiers(void *type) { return 0; }
//----------------------------------------------------------------------
// Creating related types
//----------------------------------------------------------------------
CompilerType SwiftASTContext::GetArrayElementType(void *type,
uint64_t *stride) {
VALID_OR_RETURN(CompilerType());
CompilerType element_type;
if (type) {
swift::CanType swift_type(GetCanonicalSwiftType(type));
// There are a couple of structs that mean "Array" in Swift:
// Array<T>
// NativeArray<T>
// Slice<T>
// Treat them as arrays for convenience sake.
swift::BoundGenericStructType *boundGenericStructType(
swift_type->getAs<swift::BoundGenericStructType>());
if (boundGenericStructType) {
auto args = boundGenericStructType->getGenericArgs();
swift::StructDecl *decl = boundGenericStructType->getDecl();
if (args.size() == 1 &&
decl->getModuleContext()->isStdlibModule()) {
const char *declname = decl->getName().get();
if (0 == strcmp(declname, "NativeArray") ||
0 == strcmp(declname, "Array") || 0 == strcmp(declname, "ArraySlice"))
element_type = CompilerType(GetASTContext(), args[0].getPointer());
}
}
}
return element_type;
}
CompilerType SwiftASTContext::GetCanonicalType(void *type) {
VALID_OR_RETURN(CompilerType());
if (type)
return CompilerType(GetASTContext(),
GetCanonicalSwiftType(type).getPointer());
return CompilerType();
}
CompilerType SwiftASTContext::GetInstanceType(void *type) {
VALID_OR_RETURN(CompilerType());
if (!type)
return CompilerType();
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
switch (swift_can_type->getKind()) {
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype: {
auto metatype_type =
swift::dyn_cast<swift::AnyMetatypeType>(swift_can_type);
if (metatype_type)
return CompilerType(GetASTContext(),
metatype_type.getInstanceType().getPointer());
return CompilerType();
}
default:
break;
}
return CompilerType(GetASTContext(), GetSwiftType(type));
}
CompilerType SwiftASTContext::GetFullyUnqualifiedType(void *type) {
VALID_OR_RETURN(CompilerType());
return CompilerType(GetASTContext(), GetSwiftType(type));
}
int SwiftASTContext::GetFunctionArgumentCount(void *type) {
return GetNumberOfFunctionArguments(type);
}
CompilerType SwiftASTContext::GetFunctionArgumentTypeAtIndex(void *type,
size_t idx) {
return GetFunctionArgumentAtIndex(type, idx);
}
CompilerType SwiftASTContext::GetFunctionReturnType(void *type) {
VALID_OR_RETURN(CompilerType());
if (type) {
auto func = swift::dyn_cast<swift::AnyFunctionType>(
GetCanonicalSwiftType(type));
if (func)
return CompilerType(GetASTContext(), func.getResult().getPointer());
}
return CompilerType();
}
size_t SwiftASTContext::GetNumMemberFunctions(void *type) {
size_t num_functions = 0;
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
auto nominal_decl = swift_can_type.getAnyNominal();
if (nominal_decl) {
auto iter = nominal_decl->getMembers().begin();
auto end = nominal_decl->getMembers().end();
for (; iter != end; iter++) {
switch (iter->getKind()) {
case swift::DeclKind::Constructor:
case swift::DeclKind::Destructor:
case swift::DeclKind::Func:
num_functions += 1;
break;
default:
break;
}
}
}
}
return num_functions;
}
TypeMemberFunctionImpl SwiftASTContext::GetMemberFunctionAtIndex(void *type,
size_t idx) {
VALID_OR_RETURN(TypeMemberFunctionImpl());
std::string name("");
CompilerType result_type;
MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
swift::AbstractFunctionDecl *the_decl_we_care_about = nullptr;
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
auto nominal_decl = swift_can_type.getAnyNominal();
if (nominal_decl) {
auto iter = nominal_decl->getMembers().begin();
auto end = nominal_decl->getMembers().end();
for (; iter != end; iter++) {
auto decl_kind = iter->getKind();
switch (decl_kind) {
case swift::DeclKind::Constructor:
case swift::DeclKind::Destructor:
case swift::DeclKind::Func: {
if (idx == 0) {
swift::AbstractFunctionDecl *abstract_func_decl =
llvm::dyn_cast_or_null<swift::AbstractFunctionDecl>(*iter);
if (abstract_func_decl) {
switch (decl_kind) {
case swift::DeclKind::Constructor:
name.clear();
kind = lldb::eMemberFunctionKindConstructor;
the_decl_we_care_about = abstract_func_decl;
break;
case swift::DeclKind::Destructor:
name.clear();
kind = lldb::eMemberFunctionKindDestructor;
the_decl_we_care_about = abstract_func_decl;
break;
case swift::DeclKind::Func:
default: // I know that this can only be one of three kinds
// since I am here..
{
swift::FuncDecl *func_decl =
llvm::dyn_cast<swift::FuncDecl>(*iter);
if (func_decl) {
if (func_decl->getName().empty())
name.clear();
else
name.assign(func_decl->getName().get());
if (func_decl->isStatic())
kind = lldb::eMemberFunctionKindStaticMethod;
else
kind = lldb::eMemberFunctionKindInstanceMethod;
the_decl_we_care_about = func_decl;
}
}
}
result_type =
CompilerType(GetASTContext(),
abstract_func_decl->getInterfaceType().getPointer());
}
} else
--idx;
} break;
default:
break;
}
}
}
}
if (type && the_decl_we_care_about && (kind != eMemberFunctionKindUnknown))
return TypeMemberFunctionImpl(
result_type, CompilerDecl(this, the_decl_we_care_about), name, kind);
return TypeMemberFunctionImpl();
}
CompilerType SwiftASTContext::GetLValueReferenceType(void *type) {
VALID_OR_RETURN(CompilerType());
if (type)
return CompilerType(GetASTContext(),
swift::LValueType::get(GetSwiftType(type)));
return CompilerType();
}
CompilerType SwiftASTContext::GetRValueReferenceType(void *type) {
return CompilerType();
}
CompilerType SwiftASTContext::GetNonReferenceType(void *type) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
swift::LValueType *lvalue = swift_can_type->getAs<swift::LValueType>();
if (lvalue)
return CompilerType(GetASTContext(),
lvalue->getObjectType().getPointer());
swift::InOutType *inout = swift_can_type->getAs<swift::InOutType>();
if (inout)
return CompilerType(GetASTContext(),
inout->getObjectType().getPointer());
}
return CompilerType();
}
CompilerType SwiftASTContext::GetPointeeType(void *type) {
return CompilerType();
}
CompilerType SwiftASTContext::GetPointerType(void *type) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::Type swift_type(::GetSwiftType(type));
const swift::TypeKind type_kind = swift_type->getKind();
if (type_kind == swift::TypeKind::BuiltinRawPointer)
return CompilerType(GetASTContext(), swift_type);
}
return CompilerType();
}
CompilerType SwiftASTContext::GetTypedefedType(void *type) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::Type swift_type(::GetSwiftType(type));
swift::NameAliasType *name_alias_type =
swift::dyn_cast<swift::NameAliasType>(swift_type.getPointer());
if (name_alias_type) {
return CompilerType(GetASTContext(),
name_alias_type->getSinglyDesugaredType());
}
}
return CompilerType();
}
CompilerType
SwiftASTContext::GetUnboundType(lldb::opaque_compiler_type_t type) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
swift::BoundGenericType *bound_generic_type =
swift_can_type->getAs<swift::BoundGenericType>();
if (bound_generic_type) {
swift::NominalTypeDecl *nominal_type_decl = bound_generic_type->getDecl();
if (nominal_type_decl)
return CompilerType(GetASTContext(),
nominal_type_decl->getDeclaredType());
}
}
return CompilerType(GetASTContext(), GetSwiftType(type));
}
//----------------------------------------------------------------------
// Create related types using the current type's AST
//----------------------------------------------------------------------
CompilerType SwiftASTContext::GetBasicTypeFromAST(lldb::BasicType basic_type) {
return CompilerType();
}
CompilerType SwiftASTContext::GetIntTypeFromBitSize(size_t bit_size,
bool is_signed) {
return CompilerType();
}
CompilerType SwiftASTContext::GetFloatTypeFromBitSize(size_t bit_size) {
return CompilerType();
}
//----------------------------------------------------------------------
// Exploring the type
//----------------------------------------------------------------------
const swift::irgen::TypeInfo *
SwiftASTContext::GetSwiftTypeInfo(swift::Type container_type,
swift::VarDecl *item_decl) {
VALID_OR_RETURN(nullptr);
if (container_type && item_decl) {
auto &irgen_module = GetIRGenModule();
swift::CanType container_can_type(
GetCanonicalSwiftType(container_type.getPointer()));
swift::SILType lowered_container_type =
irgen_module.getLoweredType(container_can_type);
swift::SILType lowered_field_type =
lowered_container_type.getFieldType(item_decl, *GetSILModule());
return &irgen_module.getTypeInfo(lowered_field_type);
}
return nullptr;
}
const swift::irgen::TypeInfo *SwiftASTContext::GetSwiftTypeInfo(void *type) {
VALID_OR_RETURN(nullptr);
if (type) {
auto &irgen_module = GetIRGenModule();
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
swift::SILType swift_sil_type = irgen_module.getLoweredType(
swift_can_type);
return &irgen_module.getTypeInfo(swift_sil_type);
}
return nullptr;
}
const swift::irgen::FixedTypeInfo *
SwiftASTContext::GetSwiftFixedTypeInfo(void *type) {
VALID_OR_RETURN(nullptr);
const swift::irgen::TypeInfo *type_info = GetSwiftTypeInfo(type);
if (type_info) {
if (type_info->isFixedSize())
return swift::cast<const swift::irgen::FixedTypeInfo>(type_info);
}
return nullptr;
}
uint64_t SwiftASTContext::GetBitSize(lldb::opaque_compiler_type_t type,
ExecutionContextScope *exe_scope) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Archetype:
case swift::TypeKind::LValue:
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::GenericFunction:
case swift::TypeKind::Function:
return GetPointerByteSize() * 8;
default:
break;
}
const swift::irgen::FixedTypeInfo *fixed_type_info =
GetSwiftFixedTypeInfo(type);
if (fixed_type_info)
return fixed_type_info->getFixedSize().getValue() * 8;
}
return 0;
}
uint64_t SwiftASTContext::GetByteStride(lldb::opaque_compiler_type_t type) {
if (type) {
const swift::irgen::FixedTypeInfo *fixed_type_info =
GetSwiftFixedTypeInfo(type);
if (fixed_type_info)
return fixed_type_info->getFixedStride().getValue();
}
return 0;
}
size_t SwiftASTContext::GetTypeBitAlign(void *type) {
if (type) {
const swift::irgen::FixedTypeInfo *fixed_type_info =
GetSwiftFixedTypeInfo(type);
if (fixed_type_info)
return fixed_type_info->getFixedAlignment().getValue();
}
return 0;
}
lldb::Encoding SwiftASTContext::GetEncoding(void *type, uint64_t &count) {
VALID_OR_RETURN(lldb::eEncodingInvalid);
if (!type)
return lldb::eEncodingInvalid;
count = 1;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
break;
case swift::TypeKind::BuiltinInteger:
return lldb::eEncodingSint; // TODO: detect if an integer is unsigned
case swift::TypeKind::BuiltinFloat:
return lldb::eEncodingIEEE754; // TODO: detect if an integer is unsigned
case swift::TypeKind::Archetype:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::Class: // Classes are pointers in swift...
case swift::TypeKind::BoundGenericClass:
return lldb::eEncodingUint;
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::Tuple:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetEncoding(count);
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
return lldb::eEncodingUint;
case swift::TypeKind::GenericFunction:
case swift::TypeKind::Function:
return lldb::eEncodingUint;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum:
break;
case swift::TypeKind::Struct:
case swift::TypeKind::Protocol:
case swift::TypeKind::Module:
case swift::TypeKind::ProtocolComposition:
break;
case swift::TypeKind::LValue:
return lldb::eEncodingUint;
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::BoundGenericStruct:
case swift::TypeKind::TypeVariable:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
count = 0;
return lldb::eEncodingInvalid;
}
lldb::Format SwiftASTContext::GetFormat(void *type) {
VALID_OR_RETURN(lldb::eFormatInvalid);
if (!type)
return lldb::eFormatDefault;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
break;
case swift::TypeKind::BuiltinInteger:
return eFormatDecimal; // TODO: detect if an integer is unsigned
case swift::TypeKind::BuiltinFloat:
return eFormatFloat; // TODO: detect if an integer is unsigned
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::Archetype:
return eFormatAddressInfo;
// Classes are always pointers in swift...
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass:
return eFormatHex;
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::Tuple:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetFormat();
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum:
return eFormatUnsigned;
case swift::TypeKind::GenericFunction:
case swift::TypeKind::Function:
return lldb::eFormatAddressInfo;
case swift::TypeKind::Struct:
case swift::TypeKind::Protocol:
case swift::TypeKind::Metatype:
case swift::TypeKind::Module:
case swift::TypeKind::ProtocolComposition:
break;
case swift::TypeKind::LValue:
return lldb::eFormatHex;
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::BoundGenericStruct:
case swift::TypeKind::TypeVariable:
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
// We don't know hot to display this type...
return lldb::eFormatBytes;
}
uint32_t SwiftASTContext::GetNumChildren(void *type,
bool omit_empty_base_classes) {
VALID_OR_RETURN(0);
if (!type)
return 0;
uint32_t num_children = 0;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::BuiltinVector:
case swift::TypeKind::Module:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::InOut:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetNumChildren(omit_empty_base_classes);
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info)
return cached_enum_info->GetNumElementsWithPayload();
} break;
case swift::TypeKind::Tuple:
case swift::TypeKind::Struct:
case swift::TypeKind::BoundGenericStruct:
return GetNumFields(type);
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass: {
auto class_decl = swift_can_type->getClassOrBoundGenericClass();
return (class_decl->hasSuperclass() ? 1 : 0) + GetNumFields(type);
}
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition: {
ProtocolInfo protocol_info;
if (!GetProtocolTypeInfo(
CompilerType(GetASTContext(), GetSwiftType(type)), protocol_info))
break;
return protocol_info.m_num_storage_words;
}
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
case swift::TypeKind::Archetype:
return 0;
case swift::TypeKind::LValue: {
swift::LValueType *lvalue_type = swift_can_type->castTo<swift::LValueType>();
swift::TypeBase *deref_type = lvalue_type->getObjectType().getPointer();
uint32_t num_pointee_children =
CompilerType(GetASTContext(), deref_type)
.GetNumChildren(omit_empty_base_classes);
// If this type points to a simple type (or to a class), then it has 1 child
if (num_pointee_children == 0 || deref_type->getClassOrBoundGenericClass())
num_children = 1;
else
num_children = num_pointee_children;
} break;
case swift::TypeKind::UnboundGeneric:
break;
case swift::TypeKind::TypeVariable:
break;
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return num_children;
}
lldb::BasicType SwiftASTContext::GetBasicTypeEnumeration(void *type) {
return eBasicTypeInvalid;
}
#pragma mark Aggregate Types
uint32_t SwiftASTContext::GetNumDirectBaseClasses(void *opaque_type) {
if (!opaque_type)
return 0;
swift::CanType swift_can_type(GetCanonicalSwiftType(opaque_type));
swift::ClassDecl *class_decl = swift_can_type->getClassOrBoundGenericClass();
if (class_decl) {
if (class_decl->hasSuperclass())
return 1;
}
return 0;
}
uint32_t SwiftASTContext::GetNumVirtualBaseClasses(void *opaque_type) {
return 0;
}
uint32_t SwiftASTContext::GetNumFields(void *type) {
VALID_OR_RETURN(0);
if (!type)
return 0;
uint32_t count = 0;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetNumFields();
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info)
return cached_enum_info->GetNumElementsWithPayload();
} break;
case swift::TypeKind::Tuple:
return cast<swift::TupleType>(swift_can_type)->getNumElements();
case swift::TypeKind::Struct:
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass:
case swift::TypeKind::BoundGenericStruct: {
auto nominal = swift_can_type->getAnyNominal();
return GetStoredProperties(nominal).size();
}
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition:
return GetNumChildren(type, /*omit_empty_base_classes=*/false);
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
return 0;
case swift::TypeKind::Module:
case swift::TypeKind::Archetype:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
case swift::TypeKind::LValue:
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::TypeVariable:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return count;
}
CompilerType
SwiftASTContext::GetDirectBaseClassAtIndex(void *opaque_type, size_t idx,
uint32_t *bit_offset_ptr) {
VALID_OR_RETURN(CompilerType());
if (opaque_type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(opaque_type));
swift::ClassDecl *class_decl =
swift_can_type->getClassOrBoundGenericClass();
if (class_decl) {
swift::Type base_class_type = class_decl->getSuperclass();
if (base_class_type)
return CompilerType(GetASTContext(), base_class_type.getPointer());
}
}
return CompilerType();
}
CompilerType
SwiftASTContext::GetVirtualBaseClassAtIndex(void *opaque_type, size_t idx,
uint32_t *bit_offset_ptr) {
return CompilerType();
}
/// Retrieve the printable name of a tuple element.
static std::string GetTupleElementName(const swift::TupleType *tuple_type,
unsigned index,
llvm::StringRef printed_index = "") {
const auto &element = tuple_type->getElement(index);
// Use the element name if there is one.
if (!element.getName().empty()) return element.getName().str();
// If we know the printed index already, use that.
if (!printed_index.empty()) return printed_index;
// Print the index and return that.
std::string str;
llvm::raw_string_ostream(str) << index;
return str;
}
/// Retrieve the printable name of a type referenced as a superclass.
static std::string GetSuperclassName(const CompilerType &superclass_type) {
return superclass_type.GetUnboundType().GetTypeName()
.AsCString("<no type name>");
}
/// Retrieve the type and name of a child of an existential type.
static std::pair<CompilerType, std::string>
GetExistentialTypeChild(swift::ASTContext *swift_ast_ctx,
CompilerType type,
const SwiftASTContext::ProtocolInfo &protocol_info,
unsigned idx) {
assert(idx < protocol_info.m_num_storage_words &&
"caller is responsible for validating index");
// A payload word for a non-class, non-error existential.
if (idx < protocol_info.m_num_payload_words) {
std::string name;
llvm::raw_string_ostream(name) << "payload_data_" << idx;
auto raw_pointer = swift_ast_ctx->TheRawPointerType;
return { CompilerType(swift_ast_ctx, raw_pointer.getPointer()),
std::move(name) };
}
// The instance for a class-bound existential.
if (idx == 0 && protocol_info.m_is_class_only) {
CompilerType class_type;
if (protocol_info.m_superclass) {
class_type = protocol_info.m_superclass;
} else {
auto raw_pointer = swift_ast_ctx->TheRawPointerType;
class_type = CompilerType(swift_ast_ctx, raw_pointer.getPointer());
}
return { class_type, "instance" };
}
// The instance for an error existential.
if (idx == 0 && protocol_info.m_is_errortype) {
auto raw_pointer = swift_ast_ctx->TheRawPointerType;
return { CompilerType(swift_ast_ctx, raw_pointer.getPointer()),
"error_instance" };
}
// The metatype for a non-class, non-error existential.
if (idx && idx == protocol_info.m_num_payload_words) {
// The metatype for a non-class, non-error existential.
auto any_metatype =
swift::ExistentialMetatypeType::get(swift_ast_ctx->TheAnyType);
return { CompilerType(swift_ast_ctx, any_metatype), "instance_type" };
}
// A witness table. Figure out which protocol it corresponds to.
unsigned witness_table_idx = idx - protocol_info.m_num_payload_words - 1;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
swift::ExistentialLayout layout = swift_can_type.getExistentialLayout();
std::string name;
for (auto protoType : layout.getProtocols()) {
auto proto = protoType->getDecl();
if (proto->isObjC()) continue;
if (witness_table_idx == 0) {
llvm::raw_string_ostream(name) << "witness_table_"
<< proto->getBaseName().userFacingName();
break;
}
--witness_table_idx;
}
auto raw_pointer = swift_ast_ctx->TheRawPointerType;
return { CompilerType(swift_ast_ctx, raw_pointer.getPointer()),
std::move(name) };
}
CompilerType SwiftASTContext::GetFieldAtIndex(void *type, size_t idx,
std::string &name,
uint64_t *bit_offset_ptr,
uint32_t *bitfield_bit_size_ptr,
bool *is_bitfield_ptr) {
VALID_OR_RETURN(CompilerType());
if (!type)
return CompilerType();
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
is_bitfield_ptr);
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info &&
idx < cached_enum_info->GetNumElementsWithPayload()) {
const SwiftEnumDescriptor::ElementInfo *enum_element_info =
cached_enum_info->GetElementWithPayloadAtIndex(idx);
name.assign(enum_element_info->name.GetCString());
if (bit_offset_ptr)
*bit_offset_ptr = 0;
if (bitfield_bit_size_ptr)
*bitfield_bit_size_ptr = 0;
if (is_bitfield_ptr)
*is_bitfield_ptr = false;
return enum_element_info->payload_type;
}
} break;
case swift::TypeKind::Tuple: {
auto tuple_type = cast<swift::TupleType>(swift_can_type);
if (idx >= tuple_type->getNumElements()) break;
// We cannot reliably get layout information without an execution
// context.
if (bit_offset_ptr)
*bit_offset_ptr = LLDB_INVALID_IVAR_OFFSET;
if (bitfield_bit_size_ptr)
*bitfield_bit_size_ptr = 0;
if (is_bitfield_ptr)
*is_bitfield_ptr = false;
name = GetTupleElementName(tuple_type, idx);
const auto &child = tuple_type->getElement(idx);
return CompilerType(GetASTContext(), child.getType().getPointer());
}
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass: {
auto class_decl = swift_can_type->getClassOrBoundGenericClass();
if (class_decl->hasSuperclass()) {
if (idx == 0) {
swift::Type superclass_swift_type = swift_can_type->getSuperclass();
CompilerType superclass_type(GetASTContext(),
superclass_swift_type.getPointer());
name = GetSuperclassName(superclass_type);
// We cannot reliably get layout information without an execution
// context.
if (bit_offset_ptr)
*bit_offset_ptr = LLDB_INVALID_IVAR_OFFSET;
if (bitfield_bit_size_ptr)
*bitfield_bit_size_ptr = 0;
if (is_bitfield_ptr)
*is_bitfield_ptr = false;
return superclass_type;
}
// Adjust the index to refer into the stored properties.
--idx;
}
LLVM_FALLTHROUGH;
}
case swift::TypeKind::Struct:
case swift::TypeKind::BoundGenericStruct: {
auto nominal = swift_can_type->getAnyNominal();
auto stored_properties = GetStoredProperties(nominal);
if (idx >= stored_properties.size()) break;
auto property = stored_properties[idx];
name = property->getBaseName().userFacingName();
// We cannot reliably get layout information without an execution
// context.
if (bit_offset_ptr)
*bit_offset_ptr = LLDB_INVALID_IVAR_OFFSET;
if (bitfield_bit_size_ptr)
*bitfield_bit_size_ptr = 0;
if (is_bitfield_ptr)
*is_bitfield_ptr = false;
swift::Type child_swift_type = swift_can_type->getTypeOfMember(
nominal->getModuleContext(), property, nullptr);
return CompilerType(GetASTContext(), child_swift_type.getPointer());
}
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition: {
ProtocolInfo protocol_info;
if (!GetProtocolTypeInfo(
CompilerType(GetASTContext(), GetSwiftType(type)), protocol_info))
break;
if (idx >= protocol_info.m_num_storage_words) break;
CompilerType compiler_type(GetASTContext(), GetSwiftType(type));
CompilerType child_type;
std::tie(child_type, name) =
GetExistentialTypeChild(GetASTContext(), compiler_type, protocol_info,
idx);
uint64_t child_size = child_type.GetByteSize(nullptr);
if (bit_offset_ptr)
*bit_offset_ptr = idx * child_size * 8;
if (bitfield_bit_size_ptr)
*bitfield_bit_size_ptr = 0;
if (is_bitfield_ptr)
*is_bitfield_ptr = false;
return child_type;
}
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
break;
case swift::TypeKind::Module:
case swift::TypeKind::Archetype:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
case swift::TypeKind::LValue:
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::TypeVariable:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return CompilerType();
}
// If a pointer to a pointee type (the clang_type arg) says that it has no
// children, then we either need to trust it, or override it and return a
// different result. For example, an "int *" has one child that is an integer,
// but a function pointer doesn't have any children. Likewise if a Record type
// claims it has no children, then there really is nothing to show.
uint32_t SwiftASTContext::GetNumPointeeChildren(void *type) {
if (!type)
return 0;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
return 0;
case swift::TypeKind::BuiltinInteger:
return 1;
case swift::TypeKind::BuiltinFloat:
return 1;
case swift::TypeKind::BuiltinRawPointer:
return 1;
case swift::TypeKind::BuiltinUnsafeValueBuffer:
return 1;
case swift::TypeKind::BuiltinNativeObject:
return 1;
case swift::TypeKind::BuiltinUnknownObject:
return 1;
case swift::TypeKind::BuiltinBridgeObject:
return 1;
case swift::TypeKind::BuiltinVector:
return 0;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return GetNumPointeeChildren(
swift::cast<swift::ReferenceStorageType>(swift_can_type)
.getPointer());
case swift::TypeKind::Tuple:
return 0;
case swift::TypeKind::GenericTypeParam:
return 0;
case swift::TypeKind::DependentMember:
return 0;
case swift::TypeKind::Enum:
return 0;
case swift::TypeKind::Struct:
return 0;
case swift::TypeKind::Class:
return 0;
case swift::TypeKind::Protocol:
return 0;
case swift::TypeKind::Metatype:
return 0;
case swift::TypeKind::Module:
return 0;
case swift::TypeKind::Archetype:
return 0;
case swift::TypeKind::Function:
return 0;
case swift::TypeKind::GenericFunction:
return 0;
case swift::TypeKind::ProtocolComposition:
return 0;
case swift::TypeKind::LValue:
return 1;
case swift::TypeKind::UnboundGeneric:
return 0;
case swift::TypeKind::BoundGenericClass:
return 0;
case swift::TypeKind::BoundGenericEnum:
return 0;
case swift::TypeKind::BoundGenericStruct:
return 0;
case swift::TypeKind::TypeVariable:
return 0;
case swift::TypeKind::ExistentialMetatype:
return 0;
case swift::TypeKind::DynamicSelf:
return 0;
case swift::TypeKind::SILBox:
return 0;
case swift::TypeKind::SILFunction:
return 0;
case swift::TypeKind::SILBlockStorage:
return 0;
case swift::TypeKind::InOut:
return 0;
case swift::TypeKind::Unresolved:
return 0;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return 0;
}
static int64_t GetInstanceVariableOffset_Metadata(
ValueObject *valobj, ExecutionContext *exe_ctx, const CompilerType &type,
ConstString ivar_name, const CompilerType &ivar_type) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf(
"[GetInstanceVariableOffset_Metadata] ivar_name = %s, type = %s",
ivar_name.AsCString(), type.GetTypeName().AsCString());
Process *process = exe_ctx->GetProcessPtr();
if (process) {
SwiftLanguageRuntime *runtime = process->GetSwiftLanguageRuntime();
if (runtime) {
Status error;
if (auto offset =
runtime->GetMemberVariableOffset(type, valobj, ivar_name, &error)) {
if (log)
log->Printf("[GetInstanceVariableOffset_Metadata] for %s: %llu",
ivar_name.AsCString(), *offset);
return *offset;
}
else if (log) {
log->Printf("[GetInstanceVariableOffset_Metadata] resolver failure: %s",
error.AsCString());
}
} else if (log)
log->Printf("[GetInstanceVariableOffset_Metadata] no runtime");
} else if (log)
log->Printf("[GetInstanceVariableOffset_Metadata] no process");
return LLDB_INVALID_IVAR_OFFSET;
}
static int64_t GetInstanceVariableOffset(ValueObject *valobj,
ExecutionContext *exe_ctx,
const CompilerType &class_type,
const char *ivar_name,
const CompilerType &ivar_type) {
int64_t offset = LLDB_INVALID_IVAR_OFFSET;
if (ivar_name && ivar_name[0]) {
if (exe_ctx) {
Target *target = exe_ctx->GetTargetPtr();
if (target) {
offset = GetInstanceVariableOffset_Metadata(
valobj, exe_ctx, class_type, ConstString(ivar_name), ivar_type);
}
}
}
return offset;
}
bool SwiftASTContext::IsNonTriviallyManagedReferenceType(
const CompilerType &type, NonTriviallyManagedReferenceStrategy &strategy,
CompilerType *underlying_type) {
if (auto ast =
llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem())) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
default:
break;
case swift::TypeKind::UnmanagedStorage: {
strategy = NonTriviallyManagedReferenceStrategy::eUnmanaged;
if (underlying_type)
*underlying_type = CompilerType(
ast, swift_can_type->getReferenceStorageReferent()
.getPointer());
}
return true;
case swift::TypeKind::UnownedStorage: {
strategy = NonTriviallyManagedReferenceStrategy::eUnowned;
if (underlying_type)
*underlying_type = CompilerType(
ast, swift_can_type->getReferenceStorageReferent()
.getPointer());
}
return true;
case swift::TypeKind::WeakStorage: {
strategy = NonTriviallyManagedReferenceStrategy::eWeak;
if (underlying_type)
*underlying_type = CompilerType(
ast, swift_can_type->getReferenceStorageReferent()
.getPointer());
}
return true;
}
}
return false;
}
CompilerType SwiftASTContext::GetChildCompilerTypeAtIndex(
void *type, ExecutionContext *exe_ctx, size_t idx,
bool transparent_pointers, bool omit_empty_base_classes,
bool ignore_array_bounds, std::string &child_name,
uint32_t &child_byte_size, int32_t &child_byte_offset,
uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
bool &child_is_base_class, bool &child_is_deref_of_parent,
ValueObject *valobj, uint64_t &language_flags) {
VALID_OR_RETURN(CompilerType());
if (!type)
return CompilerType();
language_flags = 0;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetChildCompilerTypeAtIndex(
exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
child_bitfield_bit_size, child_bitfield_bit_offset,
child_is_base_class, child_is_deref_of_parent, valobj,
language_flags);
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info &&
idx < cached_enum_info->GetNumElementsWithPayload()) {
const SwiftEnumDescriptor::ElementInfo *element_info =
cached_enum_info->GetElementWithPayloadAtIndex(idx);
child_name.assign(element_info->name.GetCString());
child_byte_size = element_info->payload_type.GetByteSize(
exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
child_byte_offset = 0;
child_bitfield_bit_size = 0;
child_bitfield_bit_offset = 0;
child_is_base_class = false;
child_is_deref_of_parent = false;
if (element_info->is_indirect) {
language_flags |= LanguageFlags::eIsIndirectEnumCase;
return CompilerType(GetASTContext(),
GetASTContext()->TheRawPointerType.getPointer());
} else
return element_info->payload_type;
}
} break;
case swift::TypeKind::Tuple: {
auto tuple_type = cast<swift::TupleType>(swift_can_type);
if (idx >= tuple_type->getNumElements()) break;
const auto &child = tuple_type->getElement(idx);
// Format the integer.
llvm::SmallString<16> printed_idx;
llvm::raw_svector_ostream(printed_idx) << idx;
CompilerType child_type(GetASTContext(), child.getType().getPointer());
auto exe_ctx_scope =
exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
child_name = GetTupleElementName(tuple_type, idx, printed_idx);
child_byte_size = child_type.GetByteSize(exe_ctx_scope);
child_is_base_class = false;
child_is_deref_of_parent = false;
CompilerType compiler_type(GetASTContext(), GetSwiftType(type));
child_byte_offset =
GetInstanceVariableOffset(valobj, exe_ctx, compiler_type,
printed_idx.c_str(), child_type);
child_bitfield_bit_size = 0;
child_bitfield_bit_offset = 0;
return child_type;
}
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass: {
auto class_decl = swift_can_type->getClassOrBoundGenericClass();
// Child 0 is the superclass, if there is one.
if (class_decl->hasSuperclass()) {
if (idx == 0) {
swift::Type superclass_swift_type = swift_can_type->getSuperclass();
CompilerType superclass_type(GetASTContext(),
superclass_swift_type.getPointer());
child_name = GetSuperclassName(superclass_type);
auto exe_ctx_scope =
exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
child_byte_size = superclass_type.GetByteSize(exe_ctx_scope);
child_is_base_class = true;
child_is_deref_of_parent = false;
child_byte_offset = 0;
child_bitfield_bit_size = 0;
child_bitfield_bit_offset = 0;
language_flags |= LanguageFlags::eIgnoreInstancePointerness;
return superclass_type;
}
// Adjust the index to refer into the stored properties.
--idx;
}
LLVM_FALLTHROUGH;
}
case swift::TypeKind::Struct:
case swift::TypeKind::BoundGenericStruct: {
auto nominal = swift_can_type->getAnyNominal();
auto stored_properties = GetStoredProperties(nominal);
if (idx >= stored_properties.size()) break;
// Find the stored property with this index.
auto property = stored_properties[idx];
swift::Type child_swift_type = swift_can_type->getTypeOfMember(
nominal->getModuleContext(), property, nullptr);
CompilerType child_type(GetASTContext(), child_swift_type.getPointer());
auto exe_ctx_scope =
exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
child_name = property->getBaseName().userFacingName();
child_byte_size = child_type.GetByteSize(exe_ctx_scope);
child_is_base_class = false;
child_is_deref_of_parent = false;
CompilerType compiler_type(GetASTContext(), GetSwiftType(type));
child_byte_offset =
GetInstanceVariableOffset(valobj, exe_ctx, compiler_type,
child_name.c_str(), child_type);
child_bitfield_bit_size = 0;
child_bitfield_bit_offset = 0;
return child_type;
}
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition: {
ProtocolInfo protocol_info;
if (!GetProtocolTypeInfo(
CompilerType(GetASTContext(), GetSwiftType(type)), protocol_info))
break;
if (idx >= protocol_info.m_num_storage_words) break;
CompilerType compiler_type(GetASTContext(), GetSwiftType(type));
CompilerType child_type;
std::tie(child_type, child_name) =
GetExistentialTypeChild(GetASTContext(), compiler_type, protocol_info,
idx);
auto exe_ctx_scope =
exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
child_byte_size = child_type.GetByteSize(exe_ctx_scope);
child_byte_offset = idx * child_byte_size;
child_bitfield_bit_size = 0;
child_bitfield_bit_offset = 0;
child_is_base_class = false;
child_is_deref_of_parent = false;
return child_type;
}
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
break;
case swift::TypeKind::Module:
case swift::TypeKind::Archetype:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
break;
case swift::TypeKind::LValue:
if (idx < GetNumChildren(type, omit_empty_base_classes)) {
CompilerType pointee_clang_type(GetNonReferenceType(type));
Flags pointee_clang_type_flags(pointee_clang_type.GetTypeInfo());
const char *parent_name = valobj ? valobj->GetName().GetCString() : NULL;
if (parent_name) {
child_name.assign(1, '&');
child_name += parent_name;
}
// We have a pointer to a simple type
if (idx == 0) {
child_byte_size = pointee_clang_type.GetByteSize(
exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
child_byte_offset = 0;
return pointee_clang_type;
}
}
break;
case swift::TypeKind::UnboundGeneric:
break;
case swift::TypeKind::TypeVariable:
break;
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return CompilerType();
}
// Look for a child member (doesn't include base classes, but it does include
// their members) in the type hierarchy. Returns an index path into "clang_type"
// on how to reach the appropriate member.
//
// class A
// {
// public:
// int m_a;
// int m_b;
// };
//
// class B
// {
// };
//
// class C :
// public B,
// public A
// {
// };
//
// If we have a clang type that describes "class C", and we wanted to look for
// "m_b" in it:
//
// With omit_empty_base_classes == false we would get an integer array back
// with:
// { 1, 1 }
// The first index 1 is the child index for "class A" within class C.
// The second index 1 is the child index for "m_b" within class A.
//
// With omit_empty_base_classes == true we would get an integer array back with:
// { 0, 1 }
// The first index 0 is the child index for "class A" within class C (since
// class B doesn't have any members it doesn't count).
// The second index 1 is the child index for "m_b" within class A.
size_t SwiftASTContext::GetIndexOfChildMemberWithName(
void *type, const char *name, bool omit_empty_base_classes,
std::vector<uint32_t> &child_indexes) {
VALID_OR_RETURN(0);
if (type && name && name[0]) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
child_indexes);
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info) {
ConstString const_name(name);
const size_t num_sized_elements =
cached_enum_info->GetNumElementsWithPayload();
for (size_t i = 0; i < num_sized_elements; ++i) {
if (cached_enum_info->GetElementWithPayloadAtIndex(i)->name ==
const_name) {
child_indexes.push_back(i);
return child_indexes.size();
}
}
}
} break;
case swift::TypeKind::Tuple: {
// For tuples only always look for the member by number first as a tuple
// element can be named, yet still be accessed by the number...
swift::TupleType *tuple_type = swift_can_type->castTo<swift::TupleType>();
uint32_t tuple_idx = StringConvert::ToUInt32(name, UINT32_MAX);
if (tuple_idx != UINT32_MAX) {
if (tuple_idx < tuple_type->getNumElements()) {
child_indexes.push_back(tuple_idx);
return child_indexes.size();
} else
return 0;
}
// Otherwise, perform lookup by name.
for (uint32_t tuple_idx : swift::range(tuple_type->getNumElements())) {
if (tuple_type->getElement(tuple_idx).getName().str() == name) {
child_indexes.push_back(tuple_idx);
return child_indexes.size();
}
}
return 0;
}
case swift::TypeKind::Struct:
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass:
case swift::TypeKind::BoundGenericStruct: {
auto nominal = swift_can_type->getAnyNominal();
auto stored_properties = GetStoredProperties(nominal);
auto class_decl = llvm::dyn_cast<swift::ClassDecl>(nominal);
// Search the stored properties.
for (unsigned idx : indices(stored_properties)) {
auto property = stored_properties[idx];
if (property->getBaseName().userFacingName() == name) {
// We found it!
// If we have a superclass, adjust the index accordingly.
if (class_decl && class_decl->hasSuperclass())
++idx;
child_indexes.push_back(idx);
return child_indexes.size();
}
}
// Search the superclass, if there is one.
if (class_decl && class_decl->hasSuperclass()) {
// Push index zero for the base class
child_indexes.push_back(0);
// Look in the superclass.
swift::Type superclass_swift_type = swift_can_type->getSuperclass();
CompilerType superclass_type(GetASTContext(),
superclass_swift_type.getPointer());
if (superclass_type.GetIndexOfChildMemberWithName(
name, omit_empty_base_classes, child_indexes))
return child_indexes.size();
// We didn't find a stored property matching "name" in our
// superclass, pop the superclass zero index that
// we pushed on above.
child_indexes.pop_back();
}
} break;
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition: {
ProtocolInfo protocol_info;
if (!GetProtocolTypeInfo(CompilerType(GetASTContext(),
GetSwiftType(type)), protocol_info))
break;
CompilerType compiler_type(GetASTContext(), GetSwiftType(type));
for (unsigned idx : swift::range(protocol_info.m_num_storage_words)) {
CompilerType child_type;
std::string child_name;
std::tie(child_type, child_name) =
GetExistentialTypeChild(GetASTContext(), compiler_type,
protocol_info, idx);
if (name == child_name) {
child_indexes.push_back(idx);
return child_indexes.size();
}
}
} break;
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype:
break;
case swift::TypeKind::Module:
case swift::TypeKind::Archetype:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
break;
case swift::TypeKind::InOut:
case swift::TypeKind::LValue: {
CompilerType pointee_clang_type(GetNonReferenceType(type));
if (pointee_clang_type.IsAggregateType()) {
return pointee_clang_type.GetIndexOfChildMemberWithName(
name, omit_empty_base_classes, child_indexes);
}
} break;
case swift::TypeKind::UnboundGeneric:
break;
case swift::TypeKind::TypeVariable:
break;
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
}
return 0;
}
// Get the index of the child of "clang_type" whose name matches. This function
// doesn't descend into the children, but only looks one level deep and name
// matches can include base class names.
uint32_t
SwiftASTContext::GetIndexOfChildWithName(void *type, const char *name,
bool omit_empty_base_classes) {
VALID_OR_RETURN(UINT32_MAX);
std::vector<uint32_t> child_indexes;
size_t num_child_indexes =
GetIndexOfChildMemberWithName(type, name, omit_empty_base_classes,
child_indexes);
return num_child_indexes == 1 ? child_indexes.front() : UINT32_MAX;
}
size_t SwiftASTContext::GetNumTemplateArguments(void *type) {
if (!type)
return 0;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::UnboundGeneric: {
swift::UnboundGenericType *unbound_generic_type =
swift_can_type->castTo<swift::UnboundGenericType>();
auto *nominal_type_decl = unbound_generic_type->getDecl();
swift::GenericParamList *generic_param_list =
nominal_type_decl->getGenericParams();
return generic_param_list->getParams().size();
} break;
case swift::TypeKind::BoundGenericClass:
case swift::TypeKind::BoundGenericStruct:
case swift::TypeKind::BoundGenericEnum: {
swift::BoundGenericType *bound_generic_type =
swift_can_type->castTo<swift::BoundGenericType>();
return bound_generic_type->getGenericArgs().size();
}
default:
break;
}
return 0;
}
bool SwiftASTContext::GetSelectedEnumCase(const CompilerType &type,
const DataExtractor &data,
ConstString *name, bool *has_payload,
CompilerType *payload,
bool *is_indirect) {
if (auto ast =
llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem())) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
default:
break;
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info =
ast->GetCachedEnumInfo(swift_can_type.getPointer());
if (cached_enum_info) {
auto enum_elem_info = cached_enum_info->GetElementFromData(data);
if (enum_elem_info) {
if (name)
*name = enum_elem_info->name;
if (has_payload)
*has_payload = enum_elem_info->has_payload;
if (payload)
*payload = enum_elem_info->payload_type;
if (is_indirect)
*is_indirect = enum_elem_info->is_indirect;
return true;
}
}
} break;
}
}
return false;
}
lldb::GenericKind SwiftASTContext::GetGenericArgumentKind(void *type,
size_t idx) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
if (auto *unbound_generic_type =
swift_can_type->getAs<swift::UnboundGenericType>())
return eUnboundGenericKindType;
if (auto *bound_generic_type =
swift_can_type->getAs<swift::BoundGenericType>())
if (idx < bound_generic_type->getGenericArgs().size())
return eBoundGenericKindType;
}
return eNullGenericKindType;
}
CompilerType SwiftASTContext::GetBoundGenericType(void *type, size_t idx) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
if (auto *bound_generic_type =
swift_can_type->getAs<swift::BoundGenericType>())
if (idx < bound_generic_type->getGenericArgs().size())
return CompilerType(
GetASTContext(),
bound_generic_type->getGenericArgs()[idx].getPointer());
}
return CompilerType();
}
CompilerType SwiftASTContext::GetUnboundGenericType(void *type, size_t idx) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
if (auto *unbound_generic_type =
swift_can_type->getAs<swift::UnboundGenericType>()) {
auto *nominal_type_decl = unbound_generic_type->getDecl();
swift::GenericSignature *generic_sig =
nominal_type_decl->getGenericSignature();
auto depTy = generic_sig->getGenericParams()[idx];
return CompilerType(GetASTContext(),
nominal_type_decl->mapTypeIntoContext(depTy)
->castTo<swift::ArchetypeType>());
}
}
return CompilerType();
}
CompilerType SwiftASTContext::GetGenericArgumentType(void *type, size_t idx) {
VALID_OR_RETURN(CompilerType());
switch (GetGenericArgumentKind(type, idx)) {
case eBoundGenericKindType:
return GetBoundGenericType(type, idx);
case eUnboundGenericKindType:
return GetUnboundGenericType(type, idx);
default:
break;
}
return CompilerType();
}
CompilerType SwiftASTContext::GetTypeForFormatters(void *type) {
VALID_OR_RETURN(CompilerType());
if (type) {
swift::Type swift_type(GetSwiftType(type));
return CompilerType(GetASTContext(), swift_type);
}
return CompilerType();
}
LazyBool SwiftASTContext::ShouldPrintAsOneLiner(void *type,
ValueObject *valobj) {
if (type) {
CompilerType can_compiler_type(GetCanonicalType(type));
if (IsImportedType(can_compiler_type, nullptr))
return eLazyBoolNo;
}
if (valobj) {
if (valobj->IsBaseClass())
return eLazyBoolNo;
if ((valobj->GetLanguageFlags() & LanguageFlags::eIsIndirectEnumCase) ==
LanguageFlags::eIsIndirectEnumCase)
return eLazyBoolNo;
}
return eLazyBoolCalculate;
}
bool SwiftASTContext::IsMeaninglessWithoutDynamicResolution(void *type) {
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Archetype:
return true;
default:
return false;
}
}
return false;
}
//----------------------------------------------------------------------
// Dumping types
//----------------------------------------------------------------------
#define DEPTH_INCREMENT 2
void SwiftASTContext::DumpValue(
void *type, ExecutionContext *exe_ctx, Stream *s, lldb::Format format,
const lldb_private::DataExtractor &data, lldb::offset_t data_byte_offset,
size_t data_byte_size, uint32_t bitfield_bit_size,
uint32_t bitfield_bit_offset, bool show_types, bool show_summary,
bool verbose, uint32_t depth) {}
bool SwiftASTContext::DumpTypeValue(
void *type, Stream *s, lldb::Format format,
const lldb_private::DataExtractor &data, lldb::offset_t byte_offset,
size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
ExecutionContextScope *exe_scope, bool is_base_class) {
VALID_OR_RETURN(false);
if (!type)
return false;
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
break;
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass:
// If we have a class that is in a variable then it is a pointer,
// else if it is a base class, it has no value.
if (is_base_class)
break;
// Fall through to case below
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::Archetype:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
case swift::TypeKind::LValue: {
uint32_t item_count = 1;
// A few formats, we might need to modify our size and count for depending
// on how we are trying to display the value...
switch (format) {
default:
case eFormatBoolean:
case eFormatBinary:
case eFormatComplex:
case eFormatCString: // NULL terminated C strings
case eFormatDecimal:
case eFormatEnum:
case eFormatHex:
case eFormatHexUppercase:
case eFormatFloat:
case eFormatOctal:
case eFormatOSType:
case eFormatUnsigned:
case eFormatPointer:
case eFormatVectorOfChar:
case eFormatVectorOfSInt8:
case eFormatVectorOfUInt8:
case eFormatVectorOfSInt16:
case eFormatVectorOfUInt16:
case eFormatVectorOfSInt32:
case eFormatVectorOfUInt32:
case eFormatVectorOfSInt64:
case eFormatVectorOfUInt64:
case eFormatVectorOfFloat32:
case eFormatVectorOfFloat64:
case eFormatVectorOfUInt128:
break;
case eFormatAddressInfo:
if (byte_size == 0) {
byte_size = exe_scope->CalculateTarget()
->GetArchitecture()
.GetAddressByteSize();
item_count = 1;
}
break;
case eFormatChar:
case eFormatCharPrintable:
case eFormatCharArray:
case eFormatBytes:
case eFormatBytesWithASCII:
item_count = byte_size;
byte_size = 1;
break;
case eFormatUnicode16:
item_count = byte_size / 2;
byte_size = 2;
break;
case eFormatUnicode32:
item_count = byte_size / 4;
byte_size = 4;
break;
}
return DumpDataExtractor(data, s, byte_offset, format, byte_size, item_count, UINT32_MAX,
LLDB_INVALID_ADDRESS, bitfield_bit_size,
bitfield_bit_offset, exe_scope);
} break;
case swift::TypeKind::BuiltinVector:
break;
case swift::TypeKind::Tuple:
break;
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
return CompilerType(GetASTContext(),
swift_can_type->getReferenceStorageReferent())
.DumpTypeValue(s, format, data, byte_offset, byte_size,
bitfield_bit_size, bitfield_bit_offset, exe_scope,
is_base_class);
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum: {
SwiftEnumDescriptor *cached_enum_info = GetCachedEnumInfo(type);
if (cached_enum_info) {
auto enum_elem_info = cached_enum_info->GetElementFromData(data);
if (enum_elem_info)
s->Printf("%s", enum_elem_info->name.GetCString());
else {
lldb::offset_t ptr = 0;
if (data.GetByteSize())
s->Printf("<invalid> (0x%" PRIx8 ")", data.GetU8(&ptr));
else
s->Printf("<empty>");
}
return true;
} else
s->Printf("<unknown type>");
} break;
case swift::TypeKind::Struct:
case swift::TypeKind::Protocol:
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
return false;
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::Metatype: {
return DumpDataExtractor(data, s, byte_offset, eFormatPointer, byte_size, 1, UINT32_MAX,
LLDB_INVALID_ADDRESS, bitfield_bit_size,
bitfield_bit_offset, exe_scope);
} break;
case swift::TypeKind::Module:
case swift::TypeKind::ProtocolComposition:
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::BoundGenericStruct:
case swift::TypeKind::TypeVariable:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
break;
case swift::TypeKind::Optional:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::Dictionary:
case swift::TypeKind::ArraySlice:
assert(false && "Not a canonical type");
break;
}
return 0;
}
bool SwiftASTContext::IsImportedType(const CompilerType &type,
CompilerType *original_type) {
bool success = false;
if (llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem())) {
do {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
swift::NominalType *nominal_type =
swift_can_type->getAs<swift::NominalType>();
if (!nominal_type)
break;
swift::NominalTypeDecl *nominal_type_decl = nominal_type->getDecl();
if (nominal_type_decl && nominal_type_decl->hasClangNode()) {
const clang::Decl *clang_decl = nominal_type_decl->getClangDecl();
if (!clang_decl)
break;
success = true;
if (!original_type)
break;
if (const clang::ObjCInterfaceDecl *objc_interface_decl =
llvm::dyn_cast<clang::ObjCInterfaceDecl>(
clang_decl)) // ObjCInterfaceDecl is not a TypeDecl
{
*original_type =
CompilerType(&objc_interface_decl->getASTContext(),
clang::QualType::getFromOpaquePtr(
objc_interface_decl->getTypeForDecl()));
} else if (const clang::TypeDecl *type_decl =
llvm::dyn_cast<clang::TypeDecl>(clang_decl)) {
*original_type = CompilerType(
&type_decl->getASTContext(),
clang::QualType::getFromOpaquePtr(type_decl->getTypeForDecl()));
} else // TODO: any more cases that we care about?
{
*original_type = CompilerType();
}
}
} while (0);
}
return success;
}
bool SwiftASTContext::IsImportedObjectiveCType(const CompilerType &type,
CompilerType *original_type) {
bool success = false;
if (llvm::dyn_cast_or_null<SwiftASTContext>(type.GetTypeSystem())) {
CompilerType local_original_type;
if (IsImportedType(type, &local_original_type)) {
if (local_original_type.IsValid()) {
ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(
local_original_type.GetTypeSystem());
if (clang_ast &&
clang_ast->IsObjCObjectOrInterfaceType(local_original_type)) {
if (original_type)
*original_type = local_original_type;
success = true;
}
}
}
}
return success;
}
void SwiftASTContext::DumpSummary(void *type, ExecutionContext *exe_ctx,
Stream *s,
const lldb_private::DataExtractor &data,
lldb::offset_t data_byte_offset,
size_t data_byte_size) {}
size_t SwiftASTContext::ConvertStringToFloatValue(void *type, const char *s,
uint8_t *dst,
size_t dst_size) {
return 0;
}
void SwiftASTContext::DumpTypeDescription(void *type) {
StreamFile s(stdout, false);
DumpTypeDescription(type, &s);
}
void SwiftASTContext::DumpTypeDescription(void *type, Stream *s) {
DumpTypeDescription(type, s, false, true);
}
void SwiftASTContext::DumpTypeDescription(void *type,
bool print_help_if_available,
bool print_extensions_if_available) {
StreamFile s(stdout, false);
DumpTypeDescription(type, &s, print_help_if_available,
print_extensions_if_available);
}
static void PrintSwiftNominalType(swift::NominalTypeDecl *nominal_type_decl,
Stream *s, bool print_help_if_available,
bool print_extensions_if_available) {
if (nominal_type_decl && s) {
std::string buffer;
llvm::raw_string_ostream ostream(buffer);
const swift::PrintOptions &print_options(
SwiftASTContext::GetUserVisibleTypePrintingOptions(
print_help_if_available));
nominal_type_decl->print(ostream, print_options);
ostream.flush();
if (buffer.empty() == false)
s->Printf("%s\n", buffer.c_str());
if (print_extensions_if_available) {
for (auto ext : nominal_type_decl->getExtensions()) {
if (ext) {
buffer.clear();
llvm::raw_string_ostream ext_ostream(buffer);
ext->print(ext_ostream, print_options);
ext_ostream.flush();
if (buffer.empty() == false)
s->Printf("%s\n", buffer.c_str());
}
}
}
}
}
void SwiftASTContext::DumpTypeDescription(void *type, Stream *s,
bool print_help_if_available,
bool print_extensions_if_available) {
llvm::SmallVector<char, 1024> buf;
llvm::raw_svector_ostream llvm_ostrm(buf);
if (type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
switch (swift_can_type->getKind()) {
case swift::TypeKind::Module: {
swift::ModuleType *module_type =
swift_can_type->castTo<swift::ModuleType>();
swift::ModuleDecl *module = module_type->getModule();
llvm::SmallVector<swift::Decl *, 10> decls;
module->getDisplayDecls(decls);
for (swift::Decl *decl : decls) {
swift::DeclKind kind = decl->getKind();
if (kind >= swift::DeclKind::First_TypeDecl &&
kind <= swift::DeclKind::Last_TypeDecl) {
swift::TypeDecl *type_decl =
llvm::dyn_cast_or_null<swift::TypeDecl>(decl);
if (type_decl) {
CompilerType clang_type(&module->getASTContext(),
type_decl->getDeclaredInterfaceType().getPointer());
if (clang_type) {
Flags clang_type_flags(clang_type.GetTypeInfo());
DumpTypeDescription(clang_type.GetOpaqueQualType(), s,
print_help_if_available,
print_extensions_if_available);
}
}
} else if (kind == swift::DeclKind::Func ||
kind == swift::DeclKind::Var) {
std::string buffer;
llvm::raw_string_ostream stream(buffer);
decl->print(stream,
SwiftASTContext::GetUserVisibleTypePrintingOptions(
print_help_if_available));
stream.flush();
s->Printf("%s\n", buffer.c_str());
} else if (kind == swift::DeclKind::Import) {
swift::ImportDecl *import_decl =
llvm::dyn_cast_or_null<swift::ImportDecl>(decl);
if (import_decl) {
switch (import_decl->getImportKind()) {
case swift::ImportKind::Module: {
swift::ModuleDecl *imported_module = import_decl->getModule();
if (imported_module) {
s->Printf("import %s\n", imported_module->getName().get());
}
} break;
default: {
for (swift::Decl *imported_decl : import_decl->getDecls()) {
// all of the non-module things you can import should be a
// ValueDecl
if (swift::ValueDecl *imported_value_decl =
llvm::dyn_cast_or_null<swift::ValueDecl>(
imported_decl)) {
if (swift::TypeBase *decl_type =
imported_value_decl->getInterfaceType().getPointer()) {
DumpTypeDescription(decl_type, s,
print_help_if_available,
print_extensions_if_available);
}
}
}
} break;
}
}
}
}
break;
}
case swift::TypeKind::Metatype: {
s->PutCString("metatype ");
swift::MetatypeType *metatype_type =
swift_can_type->castTo<swift::MetatypeType>();
DumpTypeDescription(metatype_type->getInstanceType().getPointer(),
print_help_if_available,
print_extensions_if_available);
} break;
case swift::TypeKind::UnboundGeneric: {
swift::UnboundGenericType *unbound_generic_type =
swift_can_type->castTo<swift::UnboundGenericType>();
auto nominal_type_decl = llvm::dyn_cast<swift::NominalTypeDecl>(
unbound_generic_type->getDecl());
if (nominal_type_decl) {
PrintSwiftNominalType(nominal_type_decl, s, print_help_if_available,
print_extensions_if_available);
}
} break;
case swift::TypeKind::GenericFunction:
case swift::TypeKind::Function: {
swift::AnyFunctionType *any_function_type =
swift_can_type->castTo<swift::AnyFunctionType>();
std::string buffer;
llvm::raw_string_ostream ostream(buffer);
const swift::PrintOptions &print_options(
SwiftASTContext::GetUserVisibleTypePrintingOptions(
print_help_if_available));
any_function_type->print(ostream, print_options);
ostream.flush();
if (buffer.empty() == false)
s->Printf("%s\n", buffer.c_str());
} break;
case swift::TypeKind::Tuple: {
swift::TupleType *tuple_type = swift_can_type->castTo<swift::TupleType>();
std::string buffer;
llvm::raw_string_ostream ostream(buffer);
const swift::PrintOptions &print_options(
SwiftASTContext::GetUserVisibleTypePrintingOptions(
print_help_if_available));
tuple_type->print(ostream, print_options);
ostream.flush();
if (buffer.empty() == false)
s->Printf("%s\n", buffer.c_str());
} break;
case swift::TypeKind::BoundGenericClass:
case swift::TypeKind::BoundGenericEnum:
case swift::TypeKind::BoundGenericStruct: {
swift::BoundGenericType *bound_generic_type =
swift_can_type->castTo<swift::BoundGenericType>();
swift::NominalTypeDecl *nominal_type_decl =
bound_generic_type->getDecl();
PrintSwiftNominalType(nominal_type_decl, s, print_help_if_available,
print_extensions_if_available);
} break;
case swift::TypeKind::BuiltinInteger: {
swift::BuiltinIntegerType *builtin_integer_type =
swift_can_type->castTo<swift::BuiltinIntegerType>();
s->Printf("builtin integer type of width %u bits\n",
builtin_integer_type->getWidth().getGreatestWidth());
break;
}
case swift::TypeKind::BuiltinFloat: {
swift::BuiltinFloatType *builtin_float_type =
swift_can_type->castTo<swift::BuiltinFloatType>();
s->Printf("builtin floating-point type of width %u bits\n",
builtin_float_type->getBitWidth());
break;
}
case swift::TypeKind::ProtocolComposition: {
swift::ProtocolCompositionType *protocol_composition_type =
swift_can_type->castTo<swift::ProtocolCompositionType>();
std::string buffer;
llvm::raw_string_ostream ostream(buffer);
const swift::PrintOptions &print_options(
SwiftASTContext::GetUserVisibleTypePrintingOptions(
print_help_if_available));
protocol_composition_type->print(ostream, print_options);
ostream.flush();
if (buffer.empty() == false)
s->Printf("%s\n", buffer.c_str());
break;
}
default: {
swift::NominalType *nominal_type =
llvm::dyn_cast_or_null<swift::NominalType>(
swift_can_type.getPointer());
if (nominal_type) {
swift::NominalTypeDecl *nominal_type_decl = nominal_type->getDecl();
PrintSwiftNominalType(nominal_type_decl, s, print_help_if_available,
print_extensions_if_available);
}
} break;
}
if (buf.size() > 0) {
s->Write(buf.data(), buf.size());
}
}
}
TypeSP SwiftASTContext::GetCachedType(const ConstString &mangled) {
TypeSP type_sp;
if (m_swift_type_map.Lookup(mangled.GetCString(), type_sp))
return type_sp;
else
return TypeSP();
}
void SwiftASTContext::SetCachedType(const ConstString &mangled,
const TypeSP &type_sp) {
m_swift_type_map.Insert(mangled.GetCString(), type_sp);
}
DWARFASTParser *SwiftASTContext::GetDWARFParser() {
if (!m_dwarf_ast_parser_ap)
m_dwarf_ast_parser_ap.reset(new DWARFASTParserSwift(*this));
return m_dwarf_ast_parser_ap.get();
}
std::vector<lldb::DataBufferSP> &
SwiftASTContext::GetASTVectorForModule(const Module *module) {
return m_ast_file_data_map[const_cast<Module *>(module)];
}
SwiftASTContextForExpressions::SwiftASTContextForExpressions(Target &target)
: SwiftASTContext(target.GetArchitecture().GetTriple().getTriple().c_str(),
&target),
m_persistent_state_up(new SwiftPersistentExpressionState) {}
UserExpression *SwiftASTContextForExpressions::GetUserExpression(
llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
Expression::ResultType desired_type,
const EvaluateExpressionOptions &options) {
TargetSP target_sp = m_target_wp.lock();
if (!target_sp)
return nullptr;
return new SwiftUserExpression(*target_sp.get(), expr, prefix, language,
desired_type, options);
}
PersistentExpressionState *
SwiftASTContextForExpressions::GetPersistentExpressionState() {
return m_persistent_state_up.get();
}
| 1 | 16,513 | Ahh the correct fix is to call `collectLinkLibraries` on the SourceFile being compiled, not the module. Sorry for our mistake! | apple-swift-lldb | cpp |
@@ -64,6 +64,7 @@ func TestConfigDefault(t *testing.T) {
"Default TaskMetadataSteadyStateRate is set incorrectly")
assert.Equal(t, DefaultTaskMetadataBurstRate, cfg.TaskMetadataBurstRate,
"Default TaskMetadataBurstRate is set incorrectly")
+ assert.False(t, cfg.SharedVolumeMatchFullConfig, "Default SharedVolumeMatchFullConfig set incorrectly")
}
// TestConfigFromFile tests the configuration can be read from file | 1 | // +build !windows,unit
// Copyright 2014-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 config
import (
"fmt"
"io/ioutil"
"os"
"testing"
"time"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/ec2"
cnitypes "github.com/containernetworking/cni/pkg/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConfigDefault(t *testing.T) {
defer setTestRegion()()
os.Unsetenv("ECS_HOST_DATA_DIR")
cfg, err := NewConfig(ec2.NewBlackholeEC2MetadataClient())
require.NoError(t, err)
assert.Equal(t, "unix:///var/run/docker.sock", cfg.DockerEndpoint, "Default docker endpoint set incorrectly")
assert.Equal(t, "/data/", cfg.DataDir, "Default datadir set incorrectly")
assert.False(t, cfg.DisableMetrics, "Default disablemetrics set incorrectly")
assert.Equal(t, 5, len(cfg.ReservedPorts), "Default reserved ports set incorrectly")
assert.Equal(t, uint16(0), cfg.ReservedMemory, "Default reserved memory set incorrectly")
assert.Equal(t, 30*time.Second, cfg.DockerStopTimeout, "Default docker stop container timeout set incorrectly")
assert.Equal(t, 3*time.Minute, cfg.ContainerStartTimeout, "Default docker start container timeout set incorrectly")
assert.False(t, cfg.PrivilegedDisabled, "Default PrivilegedDisabled set incorrectly")
assert.Equal(t, []dockerclient.LoggingDriver{dockerclient.JSONFileDriver, dockerclient.NoneDriver},
cfg.AvailableLoggingDrivers, "Default logging drivers set incorrectly")
assert.Equal(t, 3*time.Hour, cfg.TaskCleanupWaitDuration, "Default task cleanup wait duration set incorrectly")
assert.False(t, cfg.TaskENIEnabled, "TaskENIEnabled set incorrectly")
assert.False(t, cfg.TaskIAMRoleEnabled, "TaskIAMRoleEnabled set incorrectly")
assert.False(t, cfg.TaskIAMRoleEnabledForNetworkHost, "TaskIAMRoleEnabledForNetworkHost set incorrectly")
assert.Equal(t, DefaultEnabled, cfg.TaskCPUMemLimit, "TaskCPUMemLimit should be DefaultEnabled")
assert.False(t, cfg.CredentialsAuditLogDisabled, "CredentialsAuditLogDisabled set incorrectly")
assert.Equal(t, defaultCredentialsAuditLogFile, cfg.CredentialsAuditLogFile, "CredentialsAuditLogFile is set incorrectly")
assert.False(t, cfg.ImageCleanupDisabled, "ImageCleanupDisabled default is set incorrectly")
assert.Equal(t, DefaultImageDeletionAge, cfg.MinimumImageDeletionAge, "MinimumImageDeletionAge default is set incorrectly")
assert.Equal(t, DefaultImageCleanupTimeInterval, cfg.ImageCleanupInterval, "ImageCleanupInterval default is set incorrectly")
assert.Equal(t, DefaultNumImagesToDeletePerCycle, cfg.NumImagesToDeletePerCycle, "NumImagesToDeletePerCycle default is set incorrectly")
assert.Equal(t, defaultCNIPluginsPath, cfg.CNIPluginsPath, "CNIPluginsPath default is set incorrectly")
assert.False(t, cfg.AWSVPCBlockInstanceMetdata, "AWSVPCBlockInstanceMetdata default is incorrectly set")
assert.Equal(t, "/var/lib/ecs", cfg.DataDirOnHost, "Default DataDirOnHost set incorrectly")
assert.Equal(t, DefaultTaskMetadataSteadyStateRate, cfg.TaskMetadataSteadyStateRate,
"Default TaskMetadataSteadyStateRate is set incorrectly")
assert.Equal(t, DefaultTaskMetadataBurstRate, cfg.TaskMetadataBurstRate,
"Default TaskMetadataBurstRate is set incorrectly")
}
// TestConfigFromFile tests the configuration can be read from file
func TestConfigFromFile(t *testing.T) {
cluster := "TestCluster"
dockerAuthType := "dockercfg"
dockerAuth := `{
"https://index.docker.io/v1/":{
"auth":"admin",
"email":"email"
}
}`
testPauseImageName := "pause-image-name"
testPauseTag := "pause-image-tag"
content := fmt.Sprintf(`{
"AWSRegion": "not-real-1",
"Cluster": "%s",
"EngineAuthType": "%s",
"EngineAuthData": %s,
"DataDir": "/var/run/ecs_agent",
"TaskIAMRoleEnabled": true,
"TaskCPUMemLimit": true,
"InstanceAttributes": {
"attribute1": "value1"
},
"PauseContainerImageName":"%s",
"PauseContainerTag":"%s",
"AWSVPCAdditionalLocalRoutes":["169.254.172.1/32"]
}`, cluster, dockerAuthType, dockerAuth, testPauseImageName, testPauseTag)
filePath := setupFileConfiguration(t, content)
defer os.Remove(filePath)
defer setTestEnv("ECS_AGENT_CONFIG_FILE_PATH", filePath)()
defer setTestEnv("AWS_DEFAULT_REGION", "us-west-2")()
cfg, err := fileConfig()
assert.NoError(t, err, "reading configuration from file failed")
assert.Equal(t, cluster, cfg.Cluster, "cluster name not as expected from file")
assert.Equal(t, dockerAuthType, cfg.EngineAuthType, "docker auth type not as expected from file")
assert.Equal(t, dockerAuth, string(cfg.EngineAuthData.Contents()), "docker auth data not as expected from file")
assert.Equal(t, map[string]string{"attribute1": "value1"}, cfg.InstanceAttributes)
assert.Equal(t, testPauseImageName, cfg.PauseContainerImageName, "should read PauseContainerImageName")
assert.Equal(t, testPauseTag, cfg.PauseContainerTag, "should read PauseContainerTag")
assert.Equal(t, 1, len(cfg.AWSVPCAdditionalLocalRoutes), "should have one additional local route")
expectedLocalRoute, err := cnitypes.ParseCIDR("169.254.172.1/32")
assert.NoError(t, err)
assert.Equal(t, expectedLocalRoute.IP, cfg.AWSVPCAdditionalLocalRoutes[0].IP, "should match expected route IP")
assert.Equal(t, expectedLocalRoute.Mask, cfg.AWSVPCAdditionalLocalRoutes[0].Mask, "should match expected route Mask")
assert.Equal(t, ExplicitlyEnabled, cfg.TaskCPUMemLimit, "TaskCPUMemLimit should be explicitly enabled")
}
// TestDockerAuthMergeFromFile tests docker auth read from file correctly after merge
func TestDockerAuthMergeFromFile(t *testing.T) {
cluster := "myCluster"
dockerAuthType := "dockercfg"
dockerAuth := `{
"https://index.docker.io/v1/":{
"auth":"admin",
"email":"email"
}
}`
content := fmt.Sprintf(`{
"AWSRegion": "not-real-1",
"Cluster": "TestCluster",
"EngineAuthType": "%s",
"EngineAuthData": %s,
"DataDir": "/var/run/ecs_agent",
"TaskIAMRoleEnabled": true,
"InstanceAttributes": {
"attribute1": "value1"
}
}`, dockerAuthType, dockerAuth)
filePath := setupFileConfiguration(t, content)
defer os.Remove(filePath)
defer setTestEnv("ECS_CLUSTER", cluster)()
defer setTestEnv("ECS_AGENT_CONFIG_FILE_PATH", filePath)()
defer setTestEnv("AWS_DEFAULT_REGION", "us-west-2")()
cfg, err := NewConfig(ec2.NewBlackholeEC2MetadataClient())
assert.NoError(t, err, "create configuration failed")
assert.Equal(t, cluster, cfg.Cluster, "cluster name not as expected from environment variable")
assert.Equal(t, dockerAuthType, cfg.EngineAuthType, "docker auth type not as expected from file")
assert.Equal(t, dockerAuth, string(cfg.EngineAuthData.Contents()), "docker auth data not as expected from file")
assert.Equal(t, map[string]string{"attribute1": "value1"}, cfg.InstanceAttributes)
}
func TestBadFileContent(t *testing.T) {
content := `{
"AWSRegion": "not-real-1",
"AWSVPCAdditionalLocalRoutes":["169.254.172.1/32", "300.300.300.300/32", "foo"]
}`
filePath := setupFileConfiguration(t, content)
defer os.Remove(filePath)
os.Setenv("ECS_AGENT_CONFIG_FILE_PATH", filePath)
defer os.Unsetenv("ECS_AGENT_CONFIG_FILE_PATH")
_, err := NewConfig(ec2.NewBlackholeEC2MetadataClient())
assert.Error(t, err, "create configuration should fail")
}
func TestShouldLoadPauseContainerTarball(t *testing.T) {
cfg := DefaultConfig()
assert.True(t, cfg.ShouldLoadPauseContainerTarball(), "should load tarball by default")
cfg.PauseContainerTag = "foo!"
assert.False(t, cfg.ShouldLoadPauseContainerTarball(), "should not load tarball if tag differs")
cfg = DefaultConfig()
cfg.PauseContainerImageName = "foo!"
assert.False(t, cfg.ShouldLoadPauseContainerTarball(), "should not load tarball if image name differs")
}
// setupFileConfiguration create a temp file store the configuration
func setupFileConfiguration(t *testing.T, configContent string) string {
file, err := ioutil.TempFile("", "ecs-test")
require.NoError(t, err, "creating temp file for configuration failed")
_, err = file.Write([]byte(configContent))
require.NoError(t, err, "writing configuration to file failed")
return file.Name()
}
| 1 | 20,723 | Can you also modify the `TestEnvironmentConfig` in `config_test.go` to cover this? | aws-amazon-ecs-agent | go |
@@ -120,8 +120,12 @@ public class SalesforceNetworkPlugin extends ForcePlugin {
}
restClient.sendAsync(request, new RestClient.AsyncRequestCallback() {
+ // TODO: Remove onSuccess for 9.0 Release.
@Override
- public void onSuccess(RestRequest request, RestResponse response) {
+ public void onSuccess(RestRequest request, RestResponse response) {}
+
+ @Override
+ public void onResponse(RestRequest request, RestResponse response) {
try {
// Not a 2xx status
if (!response.isSuccess()) { | 1 | /*
* Copyright (c) 2016-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.androidsdk.phonegap.plugin;
import android.text.TextUtils;
import android.util.Base64;
import com.salesforce.androidsdk.phonegap.app.SalesforceHybridSDKManager;
import com.salesforce.androidsdk.phonegap.ui.SalesforceDroidGapActivity;
import com.salesforce.androidsdk.phonegap.util.SalesforceHybridLogger;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
/**
* PhoneGap plugin for native networking.
*
* @author bhariharan
*/
public class SalesforceNetworkPlugin extends ForcePlugin {
private static final String TAG = "SalesforceNetworkPlugin";
private static final String METHOD_KEY = "method";
private static final String END_POINT_KEY = "endPoint";
private static final String PATH_KEY = "path";
private static final String QUERY_PARAMS_KEY = "queryParams";
private static final String HEADER_PARAMS_KEY = "headerParams";
private static final String FILE_PARAMS_KEY = "fileParams";
private static final String FILE_MIME_TYPE_KEY = "fileMimeType";
private static final String FILE_URL_KEY = "fileUrl";
private static final String FILE_NAME_KEY = "fileName";
private static final String RETURN_BINARY = "returnBinary";
private static final String ENCODED_BODY = "encodedBody";
private static final String CONTENT_TYPE = "contentType";
private static final String DOES_NOT_REQUIRE_AUTHENTICATION = "doesNotRequireAuthentication";
/**
* Supported plugin actions that the client can take.
*/
enum Action {
pgSendRequest
}
@Override
public boolean execute(String actionStr, JavaScriptPluginVersion jsVersion, JSONArray args,
CallbackContext callbackContext) {
Action action;
try {
action = Action.valueOf(actionStr);
switch(action) {
case pgSendRequest:
sendRequest(args, callbackContext);
return true;
default:
return false;
}
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Native implementation for "sendRequest" action.
*
* @param callbackContext Used when calling back into Javascript.
*/
protected void sendRequest(JSONArray args, final CallbackContext callbackContext) {
try {
final RestRequest request = prepareRestRequest(args);
final boolean returnBinary = ((JSONObject) args.get(0)).optBoolean(RETURN_BINARY, false);
final boolean doesNotRequireAuth = ((JSONObject) args.get(0)).optBoolean(DOES_NOT_REQUIRE_AUTHENTICATION, false);
// Sends the request.
final RestClient restClient = getRestClient(doesNotRequireAuth);
if (restClient == null) {
return;
}
restClient.sendAsync(request, new RestClient.AsyncRequestCallback() {
@Override
public void onSuccess(RestRequest request, RestResponse response) {
try {
// Not a 2xx status
if (!response.isSuccess()) {
callbackContext.error(response.asString());
}
// Binary response
else if (returnBinary) {
JSONObject result = new JSONObject();
result.put(CONTENT_TYPE, response.getContentType());
result.put(ENCODED_BODY, Base64.encodeToString(response.asBytes(), Base64.DEFAULT));
callbackContext.success(result);
}
// Some response
else if (response.asBytes().length > 0) {
// Is it a JSONObject?
final JSONObject responseAsJSONObject = parseResponseAsJSONObject(response);
if (responseAsJSONObject != null) {
callbackContext.success(responseAsJSONObject);
return;
}
// Is it a JSONArray?
final JSONArray responseAsJSONArray = parseResponseAsJSONArray(response);
if (responseAsJSONArray != null) {
callbackContext.success(responseAsJSONArray);
return;
}
// Otherwise return as string
callbackContext.success(response.asString());
}
// No response
else {
callbackContext.success();
}
} catch (Exception e) {
SalesforceHybridLogger.e(TAG, "Error while parsing response", e);
onError(e);
}
}
@Override
public void onError(Exception exception) {
callbackContext.error(exception.getMessage());
}
});
} catch (Exception exception) {
callbackContext.error(exception.getMessage());
}
}
private JSONObject parseResponseAsJSONObject(RestResponse response) throws IOException {
try {
return response.asJSONObject();
}
catch (JSONException e) {
// Not a JSON object
return null;
}
}
private JSONArray parseResponseAsJSONArray(RestResponse response) throws IOException {
try {
return response.asJSONArray();
}
catch (JSONException e) {
// Not a JSON array
return null;
}
}
private RestRequest prepareRestRequest(JSONArray args) throws UnsupportedEncodingException,
URISyntaxException, JSONException {
final JSONObject arg0 = args.optJSONObject(0);
if (arg0 != null) {
final RestRequest.RestMethod method = RestRequest.RestMethod.valueOf(arg0.optString(METHOD_KEY));
final String endPoint = arg0.optString(END_POINT_KEY);
final String path = arg0.optString(PATH_KEY);
final String queryParamString = arg0.optString(QUERY_PARAMS_KEY);
JSONObject queryParams = new JSONObject();
if (!TextUtils.isEmpty(queryParamString)) {
queryParams = new JSONObject(queryParamString);
}
final JSONObject headerParams = arg0.optJSONObject(HEADER_PARAMS_KEY);
final Iterator<String> headerKeys = headerParams.keys();
final Map<String, String> additionalHeaders = new HashMap<>();
if (headerKeys != null) {
while (headerKeys.hasNext()) {
final String headerKeyStr = headerKeys.next();
if (!TextUtils.isEmpty(headerKeyStr)) {
additionalHeaders.put(headerKeyStr, headerParams.optString(headerKeyStr));
}
}
}
final JSONObject fileParams = arg0.optJSONObject(FILE_PARAMS_KEY);
// Prepares the request.
String urlParams = "";
RequestBody requestBody = null;
if (method == RestRequest.RestMethod.DELETE || method == RestRequest.RestMethod.GET
|| method == RestRequest.RestMethod.HEAD) {
urlParams = buildQueryString(queryParams);
} else {
requestBody = buildRequestBody(queryParams, fileParams);
}
final String separator = urlParams.isEmpty()
? ""
: path.contains("?")
? (path.endsWith("&") ? "" : "&")
: "?";
return new RestRequest(method, endPoint + path + separator + urlParams,
requestBody, additionalHeaders);
}
return null;
}
private RestClient getRestClient(boolean doesNotRequireAuth) {
final SalesforceDroidGapActivity currentActivity = (SalesforceDroidGapActivity) cordova.getActivity();
if (currentActivity == null) {
return null;
}
if (doesNotRequireAuth) {
return currentActivity.buildClientManager().peekUnauthenticatedRestClient();
}
return currentActivity.getRestClient();
}
private static String buildQueryString(JSONObject params) throws UnsupportedEncodingException {
if (params == null || params.length() == 0) {
return "";
}
final StringBuilder sb = new StringBuilder();
final Iterator<String> keys = params.keys();
if (keys != null) {
while (keys.hasNext()) {
final String keyStr = keys.next();
if (!TextUtils.isEmpty(keyStr)) {
sb.append(keyStr).append("=").append(URLEncoder.encode(params.optString(keyStr),
RestRequest.UTF_8)).append("&");
}
}
}
return sb.toString();
}
private static RequestBody buildRequestBody(JSONObject params, JSONObject fileParams) throws URISyntaxException {
if (fileParams == null || fileParams.length() == 0) {
return RequestBody.create(RestRequest.MEDIA_TYPE_JSON, params.toString());
} else {
final MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
final Iterator<String> keys = params.keys();
if (keys != null) {
while (keys.hasNext()) {
final String keyStr = keys.next();
if (!TextUtils.isEmpty(keyStr)) {
builder.addFormDataPart(keyStr, params.optString(keyStr));
}
}
}
/*
* File params expected to be of the form:
* {<fileParamNameInPost>: {fileMimeType:<someMimeType>, fileUrl:<fileUrl>, fileName:<fileNameForPost>}}.
*/
final Iterator<String> fileKeys = fileParams.keys();
if (fileKeys != null) {
while (fileKeys.hasNext()) {
final String fileKeyStr = fileKeys.next();
if (!TextUtils.isEmpty(fileKeyStr)) {
final JSONObject fileParam = fileParams.optJSONObject(fileKeyStr);
if (fileParam != null) {
final String mimeType = fileParam.optString(FILE_MIME_TYPE_KEY);
final String name = fileParam.optString(FILE_NAME_KEY);
final URI url = new URI(fileParam.optString(FILE_URL_KEY));
final File file = new File(url);
final MediaType mediaType = MediaType.parse(mimeType);
builder.addFormDataPart(fileKeyStr, name, RequestBody.create(mediaType, file));
}
}
}
}
return builder.build();
}
}
}
| 1 | 17,758 | There's no point "deprecating" this interface method (the customer still has to implement the new callback that we have introduced which makes it a breaking change). I'd make an exception and simply rename it to `onResponse`. | forcedotcom-SalesforceMobileSDK-Android | java |
@@ -102,7 +102,7 @@ class ExternalDriverSupplier implements Supplier<WebDriver> {
Optional<Class<? extends Supplier<WebDriver>>> supplierClass = getDelegateClass();
if (supplierClass.isPresent()) {
Class<? extends Supplier<WebDriver>> clazz = supplierClass.get();
- logger.info("Using delegate supplier: " + clazz.getName());
+ logger.finest("Using delegate supplier: " + clazz.getName());
try {
@SuppressWarnings("unchecked")
Constructor<Supplier<WebDriver>> ctor = | 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.testing.drivers;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.base.Suppliers;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.net.UrlChecker;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.logging.Logger;
/**
* Supports providing WebDriver instances from an external source using the following system
* properties:
* <dl>
* <dt>selenium.external.serverUrl</dt>
* <dd>Defines the fully qualified URL of an external WebDriver server to send commands to.
* This server <i>must</i> be compliant with the
* <a href="https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol">JSON wire protocol</a>.
* If only this property is provided, then this supplier will provide a new
* {@link RemoteWebDriver} instance pointed at the designated server. Otherwise, if a
* custom supplier is also defined (see below), this supplier will wait for the server to
* be accepting commands before delegating to the designated class for the actual client
* creation.
* </dd>
* <dt>selenium.external.supplierClass</dt>
* <dd>Specifies the fully qualified name of another class on the classpath. This class must
* implement {@code Supplier<WebDriver>} and have a public constructor that accepts two
* {@link Capabilities} objects as arguments (for the desired and required capabilities,
* respectively).
* </dd>
* </dl>
*/
class ExternalDriverSupplier implements Supplier<WebDriver> {
private static final Logger logger = Logger.getLogger(ExternalDriverSupplier.class.getName());
private static final String DELEGATE_SUPPLIER_CLASS_PROPERTY = "selenium.external.supplierClass";
private static final String EXTERNAL_SERVER_URL_PROPERTY = "selenium.external.serverUrl";
private final Capabilities desiredCapabilities;
ExternalDriverSupplier(Capabilities desiredCapabilities) {
this.desiredCapabilities = new ImmutableCapabilities(desiredCapabilities);
}
@Override
public WebDriver get() {
Optional<Supplier<WebDriver>> delegate = createDelegate(desiredCapabilities);
delegate = createForExternalServer(desiredCapabilities, delegate);
return delegate.orElse(Suppliers.ofInstance(null)).get();
}
private static Optional<Supplier<WebDriver>> createForExternalServer(
Capabilities desiredCapabilities,
Optional<Supplier<WebDriver>> delegate) {
String externalUrl = System.getProperty(EXTERNAL_SERVER_URL_PROPERTY);
if (externalUrl != null) {
logger.info("Using external WebDriver server: " + externalUrl);
URL url;
try {
url = new URL(externalUrl);
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid server URL: " + externalUrl, e);
}
Supplier<WebDriver> defaultSupplier = new DefaultRemoteSupplier(url, desiredCapabilities);
Supplier<WebDriver> supplier = new ExternalServerDriverSupplier(
url, delegate.orElse(defaultSupplier));
return Optional.of(supplier);
}
return delegate;
}
private static Optional<Supplier<WebDriver>> createDelegate(Capabilities desiredCapabilities) {
Optional<Class<? extends Supplier<WebDriver>>> supplierClass = getDelegateClass();
if (supplierClass.isPresent()) {
Class<? extends Supplier<WebDriver>> clazz = supplierClass.get();
logger.info("Using delegate supplier: " + clazz.getName());
try {
@SuppressWarnings("unchecked")
Constructor<Supplier<WebDriver>> ctor =
(Constructor<Supplier<WebDriver>>) clazz.getConstructor(Capabilities.class);
return Optional.of(ctor.newInstance(desiredCapabilities));
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private static Optional<Class<? extends Supplier<WebDriver>>> getDelegateClass() {
String delegateClassName = System.getProperty(DELEGATE_SUPPLIER_CLASS_PROPERTY);
if (delegateClassName != null) {
try {
logger.info("Loading custom supplier: " + delegateClassName);
Class<? extends Supplier<WebDriver>> clazz =
(Class<? extends Supplier<WebDriver>>) Class.forName(delegateClassName);
return Optional.of(clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return Optional.empty();
}
/**
* Waits for an external WebDriver server to be ready before delegating to another supplier
* for driver creation.
*/
private static class ExternalServerDriverSupplier implements Supplier<WebDriver> {
private final URL serverUrl;
private final Supplier<WebDriver> delegateSupplier;
private ExternalServerDriverSupplier(
URL serverUrl, Supplier<WebDriver> delegateSupplier) {
this.serverUrl = serverUrl;
this.delegateSupplier = delegateSupplier;
}
@Override
public WebDriver get() {
try {
logger.info("Waiting for server to be ready at " + serverUrl);
new UrlChecker().waitUntilAvailable(60, SECONDS, new URL(serverUrl + "/status"));
logger.info("Server is ready");
} catch (UrlChecker.TimeoutException e) {
throw new RuntimeException("The external server is not accepting commands", e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
return delegateSupplier.get();
}
}
/**
* Creates basic {@link RemoteWebDriver} instances.
*/
private static class DefaultRemoteSupplier implements Supplier<WebDriver> {
private final URL url;
private final Capabilities desiredCapabilities;
private DefaultRemoteSupplier(URL url, Capabilities desiredCapabilities) {
this.url = url;
this.desiredCapabilities = desiredCapabilities;
}
@Override
public WebDriver get() {
RemoteWebDriver driver = new RemoteWebDriver(url, desiredCapabilities);
driver.setFileDetector(new LocalFileDetector());
return driver;
}
}
}
| 1 | 16,449 | We chose `info` in the test code for obvious reasons. Changing to `finest` makes debugging harder and noisier. | SeleniumHQ-selenium | js |
@@ -40,6 +40,8 @@ THE SOFTWARE.
#include "hip_hcc_internal.h"
#include "trace_helper.h"
+//TODO Add support for multiple modules
+static std::unordered_map<std::string, uintptr_t> coGlobals;
//TODO Use Pool APIs from HCC to get memory regions.
#include <cassert> | 1 | /*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 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 <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include <map>
#include <hsa/hsa.h>
#include <hsa/hsa_ext_amd.h>
#include <hsa/amd_hsa_kernel_code.h>
#include "elfio/elfio.hpp"
#include "hip/hip_runtime.h"
#include "hip_hcc_internal.h"
#include "trace_helper.h"
//TODO Use Pool APIs from HCC to get memory regions.
#include <cassert>
inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
assert(Align != 0u && "Align can't be 0.");
Skew %= Align;
return (Value + Align - 1 - Skew) / Align * Align + Skew;
}
struct ihipKernArgInfo{
std::vector<uint32_t> Size;
std::vector<uint32_t> Align;
std::vector<std::string> ArgType;
std::vector<std::string> ArgName;
uint32_t totalSize;
};
std::map<std::string,struct ihipKernArgInfo> kernelArguments;
struct MyElfNote {
uint32_t n_namesz = 0;
uint32_t n_descsz = 0;
uint32_t n_type = 0;
MyElfNote() = default;
};
struct ihipModuleSymbol_t{
uint64_t _object; // The kernel object.
uint32_t _groupSegmentSize;
uint32_t _privateSegmentSize;
std::string _name; // TODO - review for performance cost. Name is just used for debug.
};
template <>
std::string ToString(hipFunction_t v)
{
std::ostringstream ss;
ss << "0x" << std::hex << v->_object;
return ss.str();
};
#define CHECK_HSA(hsaStatus, hipStatus) \
if (hsaStatus != HSA_STATUS_SUCCESS) {\
return hipStatus;\
}
#define CHECKLOG_HSA(hsaStatus, hipStatus) \
if (hsaStatus != HSA_STATUS_SUCCESS) {\
return ihipLogStatus(hipStatus);\
}
namespace hipdrv {
hsa_status_t findSystemRegions(hsa_region_t region, void *data){
hsa_region_segment_t segment_id;
hsa_region_get_info(region, HSA_REGION_INFO_SEGMENT, &segment_id);
if(segment_id != HSA_REGION_SEGMENT_GLOBAL){
return HSA_STATUS_SUCCESS;
}
hsa_region_global_flag_t flags;
hsa_region_get_info(region, HSA_REGION_INFO_GLOBAL_FLAGS, &flags);
hsa_region_t *reg = (hsa_region_t*)data;
if(flags & HSA_REGION_GLOBAL_FLAG_FINE_GRAINED){
*reg = region;
}
return HSA_STATUS_SUCCESS;
}
} // End namespace hipdrv
uint64_t PrintSymbolSizes(const void *emi, const char *name){
using namespace ELFIO;
const Elf64_Ehdr *ehdr = (const Elf64_Ehdr*)emi;
if(NULL == ehdr || EV_CURRENT != ehdr->e_version){}
const Elf64_Shdr * shdr = (const Elf64_Shdr*)((char*)emi + ehdr->e_shoff);
for(uint16_t i=0;i<ehdr->e_shnum;++i){
if(shdr[i].sh_type == SHT_SYMTAB){
const Elf64_Sym *syms = (const Elf64_Sym*)((char*)emi + shdr[i].sh_offset);
assert(syms);
uint64_t numSyms = shdr[i].sh_size/shdr[i].sh_entsize;
const char* strtab = (const char*)((char*)emi + shdr[shdr[i].sh_link].sh_offset);
assert(strtab);
for(uint64_t i=0;i<numSyms;++i){
const char *symname = strtab + syms[i].st_name;
assert(symname);
uint64_t size = syms[i].st_size;
if(strcmp(name, symname) == 0){
return size;
}
}
}
}
return 0;
}
uint64_t ElfSize(const void *emi){
using namespace ELFIO;
const Elf64_Ehdr *ehdr = (const Elf64_Ehdr*)emi;
const Elf64_Shdr *shdr = (const Elf64_Shdr*)((char*)emi + ehdr->e_shoff);
uint64_t max_offset = ehdr->e_shoff;
uint64_t total_size = max_offset + ehdr->e_shentsize * ehdr->e_shnum;
for(uint16_t i=0;i < ehdr->e_shnum;++i){
uint64_t cur_offset = static_cast<uint64_t>(shdr[i].sh_offset);
if(max_offset < cur_offset){
max_offset = cur_offset;
total_size = max_offset;
if(SHT_NOBITS != shdr[i].sh_type){
total_size += static_cast<uint64_t>(shdr[i].sh_size);
}
}
}
return total_size;
}
namespace
{
template<typename P>
inline
ELFIO::section* find_section_if(ELFIO::elfio& reader, P p)
{
using namespace std;
const auto it = find_if(
reader.sections.begin(), reader.sections.end(), move(p));
return it != reader.sections.end() ? *it : nullptr;
}
inline
std::vector<std::string> copy_names_of_undefined_symbols(
const ELFIO::symbol_section_accessor& section)
{
using namespace ELFIO;
using namespace std;
vector<string> r;
for (auto i = 0u; i != section.get_symbols_num(); ++i) {
// TODO: this is boyscout code, caching the temporaries
// may be of worth.
string name;
Elf64_Addr value = 0;
Elf_Xword size = 0;
Elf_Half sect_idx = 0;
uint8_t bind = 0;
uint8_t type = 0;
uint8_t other = 0;
section.get_symbol(
i, name, value, size, bind, type, sect_idx, other);
if (sect_idx == SHN_UNDEF && !name.empty()) {
r.push_back(std::move(name));
}
}
return r;
}
inline
std::pair<ELFIO::Elf64_Addr, ELFIO::Elf_Xword> find_symbol_address(
const ELFIO::symbol_section_accessor& section,
const std::string& symbol_name)
{
using namespace ELFIO;
using namespace std;
static const pair<Elf64_Addr, Elf_Xword> r{0, 0};
for (auto i = 0u; i != section.get_symbols_num(); ++i) {
// TODO: this is boyscout code, caching the temporaries
// may be of worth.
string name;
Elf64_Addr value = 0;
Elf_Xword size = 0;
Elf_Half sect_idx = 0;
uint8_t bind = 0;
uint8_t type = 0;
uint8_t other = 0;
section.get_symbol(
i, name, value, size, bind, type, sect_idx, other);
if (name == symbol_name) return make_pair(value, size);
}
return r;
}
inline
void associate_code_object_symbols_with_host_allocation(
const ELFIO::elfio& reader,
const ELFIO::elfio& self_reader,
ELFIO::section* code_object_dynsym,
ELFIO::section* process_symtab,
hsa_agent_t agent,
hsa_executable_t executable)
{
using namespace ELFIO;
using namespace std;
if (!code_object_dynsym || !process_symtab) return;
const auto undefined_symbols = copy_names_of_undefined_symbols(
symbol_section_accessor{reader, code_object_dynsym});
for (auto&& x : undefined_symbols) {
const auto tmp = find_symbol_address(
symbol_section_accessor{self_reader, process_symtab}, x);
assert(tmp.first);
void* p = nullptr;
hsa_amd_memory_lock(
reinterpret_cast<void*>(tmp.first), tmp.second, &agent, 1, &p);
hsa_executable_agent_global_variable_define(
executable, agent, x.c_str(), p);
static vector<
unique_ptr<void, decltype(hsa_amd_memory_unlock)*>> globals;
static mutex mtx;
lock_guard<std::mutex> lck{mtx};
globals.emplace_back(p, hsa_amd_memory_unlock);
}
}
inline
void load_code_object_and_freeze_executable(
const char* file, hsa_agent_t agent, hsa_executable_t executable)
{ // TODO: the following sequence is inefficient, should be refactored
// into a single load of the file and subsequent ELFIO
// processing.
using namespace std;
static const auto cor_deleter = [](hsa_code_object_reader_t* p) {
hsa_code_object_reader_destroy(*p);
};
using RAII_code_reader = unique_ptr<
hsa_code_object_reader_t, decltype(cor_deleter)>;
unique_ptr<FILE, decltype(fclose)*> cobj{fopen(file, "r"), fclose};
RAII_code_reader tmp{new hsa_code_object_reader_t, cor_deleter};
hsa_code_object_reader_create_from_file(fileno(cobj.get()), tmp.get());
hsa_executable_load_agent_code_object(
executable, agent, *tmp, nullptr, nullptr);
hsa_executable_freeze(executable, nullptr);
static vector<RAII_code_reader> code_readers;
static mutex mtx;
lock_guard<mutex> lck{mtx};
code_readers.push_back(move(tmp));
}
}
hipError_t hipModuleLoad(hipModule_t *module, const char *fname)
{
using namespace ELFIO;
HIP_INIT_API(module, fname);
hipError_t ret = hipSuccess;
*module = new ihipModule_t;
if(module == NULL){
return ihipLogStatus(hipErrorInvalidValue);
}
auto ctx = ihipGetTlsDefaultCtx();
if(ctx == nullptr){
ret = hipErrorInvalidContext;
}else{
int deviceId = ctx->getDevice()->_deviceId;
ihipDevice_t *currentDevice = ihipGetDevice(deviceId);
hsa_executable_create_alt(
HSA_PROFILE_FULL,
HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT,
nullptr,
&(*module)->executable);
elfio reader;
if (!reader.load(fname)) {
return ihipLogStatus(hipErrorFileNotFound);
}
else {
// TODO: this may benefit from caching as well.
elfio self_reader;
self_reader.load("/proc/self/exe");
const auto symtab =
find_section_if(self_reader, [](const ELFIO::section* x) {
return x->get_type() == SHT_SYMTAB;
});
const auto code_object_dynsym =
find_section_if(reader, [](const ELFIO::section* x) {
return x->get_type() == SHT_DYNSYM;
});
associate_code_object_symbols_with_host_allocation(
reader,
self_reader,
code_object_dynsym,
symtab,
currentDevice->_hsaAgent,
(*module)->executable);
load_code_object_and_freeze_executable(
fname, currentDevice->_hsaAgent, (*module)->executable);
}
}
return ihipLogStatus(ret);
}
hipError_t hipModuleUnload(hipModule_t hmod)
{
HIP_INIT_API(hmod);
// TODO - improve this synchronization so it is thread-safe.
// Currently we want for all inflight activity to complete, but don't prevent another
// thread from launching new kernels before we finish this operation.
ihipSynchronize();
hipError_t ret = hipSuccess;
hsa_status_t status = hsa_executable_destroy(hmod->executable);
if(status != HSA_STATUS_SUCCESS)
{
ret = hipErrorInvalidValue;
}
// status = hsa_code_object_destroy(hmod->object);
// if(status != HSA_STATUS_SUCCESS)
// {
// ret = hipErrorInvalidValue;
// }
// status = hsa_memory_free(hmod->ptr);
// if(status != HSA_STATUS_SUCCESS)
// {
// ret = hipErrorInvalidValue;
// }
for(auto f = hmod->funcTrack.begin(); f != hmod->funcTrack.end(); ++f) {
delete *f;
}
delete hmod;
return ihipLogStatus(ret);
}
hipError_t ihipModuleGetSymbol(hipFunction_t *func, hipModule_t hmod, const char *name)
{
auto ctx = ihipGetTlsDefaultCtx();
hipError_t ret = hipSuccess;
if (name == nullptr){
return (hipErrorInvalidValue);
}
if (ctx == nullptr){
ret = hipErrorInvalidContext;
} else {
std::string str(name);
for(auto f = hmod->funcTrack.begin(); f != hmod->funcTrack.end(); ++f) {
if((*f)->_name == str) {
*func = *f;
return ret;
}
}
ihipModuleSymbol_t *sym = new ihipModuleSymbol_t;
int deviceId = ctx->getDevice()->_deviceId;
ihipDevice_t *currentDevice = ihipGetDevice(deviceId);
hsa_agent_t gpuAgent = (hsa_agent_t)currentDevice->_hsaAgent;
hsa_status_t status;
hsa_executable_symbol_t symbol;
status = hsa_executable_get_symbol(hmod->executable, NULL, name, gpuAgent, 0, &symbol);
if(status != HSA_STATUS_SUCCESS){
return hipErrorNotFound;
}
status = hsa_executable_symbol_get_info(symbol,
HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT,
&sym->_object);
CHECK_HSA(status, hipErrorNotFound);
status = hsa_executable_symbol_get_info(symbol,
HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE,
&sym->_groupSegmentSize);
CHECK_HSA(status, hipErrorNotFound);
status = hsa_executable_symbol_get_info(symbol,
HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE,
&sym->_privateSegmentSize);
CHECK_HSA(status, hipErrorNotFound);
sym->_name = name;
*func = sym;
hmod->funcTrack.push_back(*func);
}
return ret;
}
hipError_t hipModuleGetFunction(hipFunction_t *hfunc, hipModule_t hmod,
const char *name){
HIP_INIT_API(hfunc, hmod, name);
return ihipLogStatus(ihipModuleGetSymbol(hfunc, hmod, name));
}
hipError_t ihipModuleLaunchKernel(hipFunction_t f,
uint32_t globalWorkSizeX, uint32_t globalWorkSizeY, uint32_t globalWorkSizeZ,
uint32_t localWorkSizeX, uint32_t localWorkSizeY, uint32_t localWorkSizeZ,
size_t sharedMemBytes, hipStream_t hStream,
void **kernelParams, void **extra,
hipEvent_t startEvent, hipEvent_t stopEvent)
{
auto ctx = ihipGetTlsDefaultCtx();
hipError_t ret = hipSuccess;
if(ctx == nullptr){
ret = hipErrorInvalidDevice;
}else{
int deviceId = ctx->getDevice()->_deviceId;
ihipDevice_t *currentDevice = ihipGetDevice(deviceId);
hsa_agent_t gpuAgent = (hsa_agent_t)currentDevice->_hsaAgent;
void *config[5] = {0};
size_t kernArgSize;
if(kernelParams != NULL){
std::string name = f->_name;
struct ihipKernArgInfo pl = kernelArguments[name];
char* argBuf = (char*)malloc(pl.totalSize);
memset(argBuf, 0, pl.totalSize);
int index = 0;
for(int i=0;i<pl.Size.size();i++){
memcpy(argBuf + index, kernelParams[i], pl.Size[i]);
index += pl.Align[i];
}
config[1] = (void*)argBuf;
kernArgSize = pl.totalSize;
} else if(extra != NULL){
memcpy(config, extra, sizeof(size_t)*5);
if(config[0] == HIP_LAUNCH_PARAM_BUFFER_POINTER && config[2] == HIP_LAUNCH_PARAM_BUFFER_SIZE && config[4] == HIP_LAUNCH_PARAM_END){
kernArgSize = *(size_t*)(config[3]);
} else {
return hipErrorNotInitialized;
}
}else{
return hipErrorInvalidValue;
}
/*
Kernel argument preparation.
*/
grid_launch_parm lp;
lp.dynamic_group_mem_bytes = sharedMemBytes; // TODO - this should be part of preLaunchKernel.
hStream = ihipPreLaunchKernel(hStream, dim3(globalWorkSizeX, globalWorkSizeY, globalWorkSizeZ), dim3(localWorkSizeX, localWorkSizeY, localWorkSizeZ), &lp, f->_name.c_str());
hsa_kernel_dispatch_packet_t aql;
memset(&aql, 0, sizeof(aql));
//aql.completion_signal._handle = 0;
//aql.kernarg_address = 0;
aql.workgroup_size_x = localWorkSizeX;
aql.workgroup_size_y = localWorkSizeY;
aql.workgroup_size_z = localWorkSizeZ;
aql.grid_size_x = globalWorkSizeX;
aql.grid_size_y = globalWorkSizeY;
aql.grid_size_z = globalWorkSizeZ;
aql.group_segment_size = f->_groupSegmentSize + sharedMemBytes;
aql.private_segment_size = f->_privateSegmentSize;
aql.kernel_object = f->_object;
aql.setup = 3 << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
aql.header = (HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE) |
(1 << HSA_PACKET_HEADER_BARRIER); // TODO - honor queue setting for execute_in_order
if (HCC_OPT_FLUSH) {
aql.header |= (HSA_FENCE_SCOPE_AGENT << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE) |
(HSA_FENCE_SCOPE_AGENT << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE);
} else {
aql.header |= (HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE) |
(HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE);
};
hc::completion_future cf;
lp.av->dispatch_hsa_kernel(&aql, config[1] /* kernarg*/, kernArgSize,
(startEvent || stopEvent) ? &cf : nullptr
#if (__hcc_workweek__ > 17312)
, f->_name.c_str()
#endif
);
if (startEvent) {
startEvent->attachToCompletionFuture(&cf, hStream, hipEventTypeStartCommand);
}
if (stopEvent) {
stopEvent->attachToCompletionFuture (&cf, hStream, hipEventTypeStopCommand);
}
if(kernelParams != NULL){
free(config[1]);
}
ihipPostLaunchKernel(f->_name.c_str(), hStream, lp);
}
return ret;
}
hipError_t hipModuleLaunchKernel(hipFunction_t f,
uint32_t gridDimX, uint32_t gridDimY, uint32_t gridDimZ,
uint32_t blockDimX, uint32_t blockDimY, uint32_t blockDimZ,
uint32_t sharedMemBytes, hipStream_t hStream,
void **kernelParams, void **extra)
{
HIP_INIT_API(f, gridDimX, gridDimY, gridDimZ,
blockDimX, blockDimY, blockDimZ,
sharedMemBytes, hStream,
kernelParams, extra);
return ihipLogStatus(ihipModuleLaunchKernel(f,
blockDimX * gridDimX, blockDimY * gridDimY, gridDimZ * blockDimZ,
blockDimX, blockDimY, blockDimZ,
sharedMemBytes, hStream, kernelParams, extra,
nullptr, nullptr));
}
hipError_t hipHccModuleLaunchKernel(hipFunction_t f,
uint32_t globalWorkSizeX, uint32_t globalWorkSizeY, uint32_t globalWorkSizeZ,
uint32_t localWorkSizeX, uint32_t localWorkSizeY, uint32_t localWorkSizeZ,
size_t sharedMemBytes, hipStream_t hStream,
void **kernelParams, void **extra,
hipEvent_t startEvent, hipEvent_t stopEvent)
{
HIP_INIT_API(f, globalWorkSizeX, globalWorkSizeY, globalWorkSizeZ,
localWorkSizeX, localWorkSizeY, localWorkSizeZ,
sharedMemBytes, hStream,
kernelParams, extra);
return ihipLogStatus(ihipModuleLaunchKernel(f, globalWorkSizeX, globalWorkSizeY, globalWorkSizeZ,
localWorkSizeX, localWorkSizeY, localWorkSizeZ,
sharedMemBytes, hStream, kernelParams, extra, startEvent, stopEvent));
}
namespace
{
struct Agent_global {
std::string name;
hipDeviceptr_t address;
std::uint32_t byte_cnt;
};
inline
void* address(hsa_executable_symbol_t x)
{
void* r = nullptr;
hsa_executable_symbol_get_info(
x, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS, &r);
return r;
}
inline
std::string name(hsa_executable_symbol_t x)
{
uint32_t sz = 0u;
hsa_executable_symbol_get_info(
x, HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH, &sz);
std::string r(sz, '\0');
hsa_executable_symbol_get_info(
x, HSA_EXECUTABLE_SYMBOL_INFO_NAME, &r.front());
return r;
}
inline
std::uint32_t size(hsa_executable_symbol_t x)
{
std::uint32_t r = 0;
hsa_executable_symbol_get_info(
x, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE, &r);
return r;
}
inline
void track(const Agent_global& x)
{
tprintf(
DB_MEM,
" add variable '%s' with ptr=%p size=%u to tracker\n",
x.name.c_str(),
x.address,
x.byte_cnt);
auto device = ihipGetTlsDefaultCtx()->getWriteableDevice();
hc::AmPointerInfo ptr_info(
nullptr,
x.address,
x.address,
x.byte_cnt,
device->_acc,
true,
false);
hc::am_memtracker_add(x.address, ptr_info);
hc::am_memtracker_update(x.address, device->_deviceId, 0u);
}
template<typename Container = std::vector<Agent_global>>
inline
hsa_status_t copy_agent_global_variables(
hsa_executable_t, hsa_agent_t, hsa_executable_symbol_t x, void* out)
{
assert(out);
hsa_symbol_kind_t t = {};
hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_TYPE, &t);
if (t == HSA_SYMBOL_KIND_VARIABLE) {
static_cast<Container*>(out)->push_back(
Agent_global{name(x), address(x), size(x)});
track(static_cast<Container*>(out)->back());
}
return HSA_STATUS_SUCCESS;
}
inline
hsa_agent_t this_agent()
{
auto ctx = ihipGetTlsDefaultCtx();
if (!ctx) throw std::runtime_error{"No active HIP context."};
auto device = ctx->getDevice();
if (!device) throw std::runtime_error{"No device available for HIP."};
ihipDevice_t *currentDevice = ihipGetDevice(device->_deviceId);
if (!currentDevice) {
throw std::runtime_error{"No active device for HIP"};
}
return currentDevice->_hsaAgent;
}
inline
std::vector<Agent_global> read_agent_globals(hipModule_t hmodule)
{
std::vector<Agent_global> r;
hsa_executable_iterate_agent_symbols(
hmodule->executable, this_agent(), copy_agent_global_variables, &r);
return r;
}
}
hipError_t hipModuleGetGlobal(hipDeviceptr_t *dptr, size_t *bytes,
hipModule_t hmod, const char* name)
{
HIP_INIT_API(dptr, bytes, hmod, name);
hipError_t ret = hipSuccess;
if(dptr == NULL || bytes == NULL){
return ihipLogStatus(hipErrorInvalidValue);
}
if(name == NULL || hmod == NULL){
return ihipLogStatus(hipErrorNotInitialized);
}
else{
static std::unordered_map<
hipModule_t, std::vector<Agent_global>> agent_globals;
// TODO: this is not particularly robust.
if (agent_globals.count(hmod) == 0) {
static std::mutex mtx;
std::lock_guard<std::mutex> lck{mtx};
if (agent_globals.count(hmod) == 0) {
agent_globals.emplace(hmod, read_agent_globals(hmod));
}
}
// TODO: This is unsafe iff some other emplacement triggers rehashing.
// It will have to be properly fleshed out in the future.
const auto it0 = agent_globals.find(hmod);
if (it0 == agent_globals.cend()) {
throw std::runtime_error{"agent_globals data structure corrupted."};
}
const auto it1 = std::find_if(
it0->second.cbegin(),
it0->second.cend(),
[=](const Agent_global& x) { return x.name == name; });
if (it1 == it0->second.cend()) return ihipLogStatus(hipErrorNotFound);
*dptr = it1->address;
*bytes = it1->byte_cnt;
return ihipLogStatus(hipSuccess);
}
}
hipError_t hipModuleLoadData(hipModule_t *module, const void *image)
{
HIP_INIT_API(module, image);
hipError_t ret = hipSuccess;
if(image == NULL || module == NULL){
return ihipLogStatus(hipErrorNotInitialized);
} else {
auto ctx = ihipGetTlsDefaultCtx();
*module = new ihipModule_t;
int deviceId = ctx->getDevice()->_deviceId;
ihipDevice_t *currentDevice = ihipGetDevice(deviceId);
void *p;
uint64_t size = ElfSize(image);
hsa_agent_t agent = currentDevice->_hsaAgent;
hsa_region_t sysRegion;
hsa_status_t status = hsa_agent_iterate_regions(agent, hipdrv::findSystemRegions, &sysRegion);
status = hsa_memory_allocate(sysRegion, size, (void**)&p);
if(status != HSA_STATUS_SUCCESS){
return ihipLogStatus(hipErrorOutOfMemory);
}
char *ptr = (char*)p;
if(!ptr){
return ihipLogStatus(hipErrorOutOfMemory);
}
(*module)->ptr = p;
(*module)->size = size;
memcpy(ptr, image, size);
status = hsa_code_object_deserialize(ptr, size, NULL, &(*module)->object);
if(status != HSA_STATUS_SUCCESS){
return ihipLogStatus(hipErrorSharedObjectInitFailed);
}
status = hsa_executable_create(HSA_PROFILE_FULL, HSA_EXECUTABLE_STATE_UNFROZEN, NULL, &(*module)->executable);
CHECKLOG_HSA(status, hipErrorNotInitialized);
status = hsa_executable_load_code_object((*module)->executable, agent, (*module)->object, NULL);
CHECKLOG_HSA(status, hipErrorNotInitialized);
status = hsa_executable_freeze((*module)->executable, NULL);
CHECKLOG_HSA(status, hipErrorNotInitialized);
}
return ihipLogStatus(ret);
}
hipError_t hipModuleLoadDataEx(hipModule_t *module, const void *image, unsigned int numOptions, hipJitOption *options, void **optionValues)
{
return hipModuleLoadData(module, image);
}
| 1 | 6,466 | I know this is not new here but we need to remove this global or protect access from multiple threads. | ROCm-Developer-Tools-HIP | cpp |
@@ -30,13 +30,13 @@ namespace OpenTelemetry.Trace
/// Enables HttpClient and HttpWebRequest instrumentation.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/> being configured.</param>
- /// <param name="configureHttpClientInstrumentationOptions">HttpClient configuration options.</param>
/// <param name="configureHttpWebRequestInstrumentationOptions">HttpWebRequest configuration options.</param>
+ /// <param name="configureHttpClientInstrumentationOptions">HttpClient configuration options.</param>
/// <returns>The instance of <see cref="TracerProviderBuilder"/> to chain the calls.</returns>
public static TracerProviderBuilder AddHttpClientInstrumentation(
this TracerProviderBuilder builder,
- Action<HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions = null,
- Action<HttpWebRequestInstrumentationOptions> configureHttpWebRequestInstrumentationOptions = null)
+ Action<HttpWebRequestInstrumentationOptions> configureHttpWebRequestInstrumentationOptions = null,
+ Action<HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions = null)
#else
/// <summary>
/// Enables HttpClient instrumentation. | 1 | // <copyright file="TracerProviderBuilderExtensions.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 OpenTelemetry.Instrumentation.Http;
using OpenTelemetry.Instrumentation.Http.Implementation;
namespace OpenTelemetry.Trace
{
/// <summary>
/// Extension methods to simplify registering of httpclient instrumentation.
/// </summary>
public static class TracerProviderBuilderExtensions
{
#if NETFRAMEWORK
/// <summary>
/// Enables HttpClient and HttpWebRequest instrumentation.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/> being configured.</param>
/// <param name="configureHttpClientInstrumentationOptions">HttpClient configuration options.</param>
/// <param name="configureHttpWebRequestInstrumentationOptions">HttpWebRequest configuration options.</param>
/// <returns>The instance of <see cref="TracerProviderBuilder"/> to chain the calls.</returns>
public static TracerProviderBuilder AddHttpClientInstrumentation(
this TracerProviderBuilder builder,
Action<HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions = null,
Action<HttpWebRequestInstrumentationOptions> configureHttpWebRequestInstrumentationOptions = null)
#else
/// <summary>
/// Enables HttpClient instrumentation.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/> being configured.</param>
/// <param name="configureHttpClientInstrumentationOptions">HttpClient configuration options.</param>
/// <returns>The instance of <see cref="TracerProviderBuilder"/> to chain the calls.</returns>
public static TracerProviderBuilder AddHttpClientInstrumentation(
this TracerProviderBuilder builder,
Action<HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions = null)
#endif
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
var httpClientOptions = new HttpClientInstrumentationOptions();
configureHttpClientInstrumentationOptions?.Invoke(httpClientOptions);
builder.AddInstrumentation(() => new HttpClientInstrumentation(httpClientOptions));
builder.AddSource(HttpHandlerDiagnosticListener.ActivitySourceName);
builder.AddLegacySource("System.Net.Http.HttpRequestOut");
#if NETFRAMEWORK
builder.AddHttpWebRequestInstrumentation(configureHttpWebRequestInstrumentationOptions);
#endif
return builder;
}
#if NETFRAMEWORK
internal static TracerProviderBuilder AddHttpWebRequestInstrumentation(
this TracerProviderBuilder builder,
Action<HttpWebRequestInstrumentationOptions> configureOptions = null)
{
HttpWebRequestInstrumentationOptions options = new HttpWebRequestInstrumentationOptions();
configureOptions?.Invoke(options);
HttpWebRequestActivitySource.Options = options;
builder.AddSource(HttpWebRequestActivitySource.ActivitySourceName);
return builder;
}
#endif
}
}
| 1 | 19,929 | Doesn't seem any less confusing or error-prone to me. IMO the solution is to not use "object" in the enrich callback signatures. Type safety/compile-time checking is our friend! | open-telemetry-opentelemetry-dotnet | .cs |
@@ -19,6 +19,9 @@ module Travis
def export
super
sh.export 'TRAVIS_GO_VERSION', go_version, echo: false
+ sh.if '-z $GOMAXPROCS' do
+ sh.export 'GOMAXPROCS', '2', echo: true
+ end
end
def prepare | 1 | require 'uri'
module Travis
module Build
class Script
class Go < Script
DEFAULTS = {
gobuild_args: '-v',
gimme_config: {
url: "#{ENV.fetch(
'TRAVIS_BUILD_GIMME_URL',
'https://raw.githubusercontent.com/meatballhat/gimme/v0.2.3/gimme'
)}".untaint,
force_reinstall: !!ENV['TRAVIS_BUILD_GIMME_FORCE_REINSTALL']
},
go: "#{ENV.fetch('TRAVIS_BUILD_GO_VERSION', '1.4.1')}".untaint
}
def export
super
sh.export 'TRAVIS_GO_VERSION', go_version, echo: false
end
def prepare
super
ensure_gvm_wiped
sh.if "! -x '#{HOME_DIR}/bin/gimme' && ! -x '/usr/local/bin/gimme'" do
install_gimme
end
install_gimme if gimme_config[:force_reinstall]
end
def announce
super
sh.cmd 'gimme version'
sh.cmd 'go version'
sh.cmd 'go env', fold: 'go.env'
end
def setup
super
sh.cmd %Q'eval "$(gimme #{go_version})"'
# NOTE: $GOPATH is a plural ":"-separated var a la $PATH. We export
# only a single path here, but users who want to treat $GOPATH as
# singular *should* probably use "${GOPATH%%:*}" to take the first
# entry.
sh.export 'GOPATH', "#{HOME_DIR}/gopath", echo: true
sh.export 'PATH', "#{HOME_DIR}/gopath/bin:$PATH", echo: true
sh.mkdir "#{HOME_DIR}/gopath/src/#{data.source_host}/#{data.slug}", recursive: true, assert: false, timing: false
sh.cmd "rsync -az ${TRAVIS_BUILD_DIR}/ #{HOME_DIR}/gopath/src/#{data.source_host}/#{data.slug}/", assert: false, timing: false
sh.export "TRAVIS_BUILD_DIR", "#{HOME_DIR}/gopath/src/#{data.source_host}/#{data.slug}"
sh.cd "#{HOME_DIR}/gopath/src/#{data.source_host}/#{data.slug}", assert: true
end
def install
sh.if '-f Godeps/Godeps.json' do
sh.export 'GOPATH', '${TRAVIS_BUILD_DIR}/Godeps/_workspace:$GOPATH', retry: false
sh.export 'PATH', '${TRAVIS_BUILD_DIR}/Godeps/_workspace/bin:$PATH', retry: false
if go_version >= '1.1'
sh.if '! -d Godeps/_workspace/src' do
sh.cmd "#{go_get_cmd} github.com/tools/godep", echo: true, retry: true, timing: true, assert: true
sh.cmd 'godep restore', retry: true, timing: true, assert: true, echo: true
end
end
end
sh.if uses_make do
sh.cmd 'true', retry: true, fold: 'install' # TODO instead negate the condition
end
sh.else do
sh.cmd "#{go_get_cmd} #{config[:gobuild_args]} ./...", retry: true, fold: 'install'
end
end
def script
sh.if uses_make do
sh.cmd 'make'
end
sh.else do
sh.cmd "go test #{config[:gobuild_args]} ./..."
end
end
def cache_slug
super << '--go-' << go_version
end
private
def uses_make
'-f GNUmakefile || -f makefile || -f Makefile || -f BSDmakefile'
end
def gobuild_args
config[:gobuild_args]
end
def go_version
@go_version ||= normalized_go_version
end
def normalized_go_version
v = config[:go].to_s
case v
when 'default' then DEFAULTS[:go]
when '1' then '1.4.1'
when '1.0' then '1.0.3'
when '1.2' then '1.2.2'
when 'go1' then v
when /^go/ then v.sub(/^go/, '')
else v
end
end
def go_get_cmd
(go_version < '1.2' || go_version == 'go1') ? 'go get' : 'go get -t'
end
def ensure_gvm_wiped
sh.cmd 'unset gvm', echo: false
sh.if "-d #{HOME_DIR}/.gvm" do
sh.mv "#{HOME_DIR}/.gvm", "#{HOME_DIR}/.gvm.disabled", echo: false
end
end
def install_gimme
sh.echo "Installing gimme from #{gimme_url.inspect}", ansi: :yellow
sh.mkdir "#{HOME_DIR}/bin", echo: false, recursive: true
sh.cmd "curl -sL -o #{HOME_DIR}/bin/gimme '#{gimme_url}'", echo: false
sh.cmd "chmod +x #{HOME_DIR}/bin/gimme", echo: false
sh.export 'PATH', "#{HOME_DIR}/bin:$PATH", retry: false, echo: false
# install bootstrap version so that tip/master/whatever can be used immediately
sh.cmd %Q'gimme 1.4.1 >/dev/null 2>&1'
end
def gimme_config
config[:gimme_config]
end
def gimme_url
cleaned = URI.parse(gimme_config[:url]).to_s.untaint
return cleaned if cleaned =~ %r{^https://raw\.githubusercontent\.com/meatballhat/gimme}
DEFAULTS[:gimme_config][:url]
rescue URI::InvalidURIError => e
warn e
DEFAULTS[:gimme_config][:url]
end
end
end
end
end
| 1 | 13,169 | I think this should be `GOMAXPROCS=$(nproc 2>/dev/null || echo 2)` | travis-ci-travis-build | rb |
@@ -175,8 +175,9 @@ func (ctx *rollDPoSCtx) validateProposeBlock(blk Block, expectedProposer string)
errorLog.Msg("error when validating the block signature")
return false
}
- if producer == ctx.addr.RawAddress {
- // If the block is self proposed, skip validation
+ // TODO: in long term, block in process and after process should be represented differently
+ if producer == ctx.addr.RawAddress && block.WorkingSet != nil {
+ // If the block is self proposed and working set is not nil (meaning not obtained from wire), skip validation
return true
}
containCoinbase := true | 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 rolldpos
import (
"context"
"encoding/hex"
"time"
"github.com/facebookgo/clock"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/zjshen14/go-fsm"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/actpool"
"github.com/iotexproject/iotex-core/blockchain"
"github.com/iotexproject/iotex-core/blockchain/block"
"github.com/iotexproject/iotex-core/blocksync"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/consensus/scheme"
"github.com/iotexproject/iotex-core/crypto"
"github.com/iotexproject/iotex-core/endorsement"
"github.com/iotexproject/iotex-core/explorer/idl/explorer"
"github.com/iotexproject/iotex-core/iotxaddress"
"github.com/iotexproject/iotex-core/logger"
"github.com/iotexproject/iotex-core/pkg/hash"
"github.com/iotexproject/iotex-core/proto"
"github.com/iotexproject/iotex-core/state"
)
var (
timeSlotMtc = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "iotex_consensus_time_slot",
Help: "Consensus time slot",
},
[]string{},
)
)
const sigSize = 5 // number of uint32s in BLS sig
func init() {
prometheus.MustRegister(timeSlotMtc)
}
var (
// ErrNewRollDPoS indicates the error of constructing RollDPoS
ErrNewRollDPoS = errors.New("error when constructing RollDPoS")
// ErrZeroDelegate indicates seeing 0 delegates in the network
ErrZeroDelegate = errors.New("zero delegates in the network")
)
type rollDPoSCtx struct {
cfg config.RollDPoS
addr *iotxaddress.Address
chain blockchain.Blockchain
actPool actpool.ActPool
broadcastHandler scheme.Broadcast
epoch epochCtx
round roundCtx
clock clock.Clock
rootChainAPI explorer.Explorer
// candidatesByHeightFunc is only used for testing purpose
candidatesByHeightFunc func(uint64) ([]*state.Candidate, error)
sync blocksync.BlockSync
}
var (
// ErrNotEnoughCandidates indicates there are not enough candidates from the candidate pool
ErrNotEnoughCandidates = errors.New("Candidate pool does not have enough candidates")
)
func (ctx *rollDPoSCtx) OnConsensusReached() error {
pendingBlock := ctx.round.block.(*blockWrapper)
// If the pending block is a secret block, record the secret share generated by producer
if ctx.shouldHandleDKG() {
for _, secretProposal := range pendingBlock.SecretProposals {
if secretProposal.DstAddr() == ctx.addr.RawAddress {
ctx.epoch.committedSecrets[secretProposal.SrcAddr()] = secretProposal.Secret()
break
}
}
}
// Commit and broadcast the pending block
if err := ctx.chain.CommitBlock(pendingBlock.Block); err != nil {
logger.Error().
Err(err).
Uint64("block", pendingBlock.Height()).
Msg("error when committing a block")
}
// Remove transfers in this block from ActPool and reset ActPool state
ctx.actPool.Reset()
// Broadcast the committed block to the network
if blkProto := pendingBlock.ConvertToBlockPb(); blkProto != nil {
if err := ctx.Broadcast(blkProto); err != nil {
logger.Error().
Err(err).
Uint64("block", pendingBlock.Height()).
Msg("error when broadcasting blkProto")
}
// putblock to parent chain if the current node is proposer and current chain is a sub chain
if ctx.round.proposer == ctx.addr.RawAddress && ctx.chain.ChainAddress() != "" {
putBlockToParentChain(ctx.rootChainAPI, ctx.chain.ChainAddress(), ctx.addr, pendingBlock.Block)
}
} else {
logger.Error().
Uint64("block", pendingBlock.Height()).
Msg("error when converting a block into a proto msg")
}
return nil
}
type blockWrapper struct {
*block.Block
round uint32
}
func (bw *blockWrapper) Hash() []byte {
hash := bw.HashBlock()
return hash[:]
}
func (bw *blockWrapper) Proposer() string {
return bw.ProducerAddress()
}
func (bw *blockWrapper) Round() uint32 {
return bw.round
}
func (ctx *rollDPoSCtx) MintBlock() (Block, error) {
if blk := ctx.round.block; blk != nil {
return blk, nil
}
blk, err := ctx.mintBlock()
if err != nil {
return nil, err
}
return &blockWrapper{
blk,
ctx.round.number,
}, nil
}
func (ctx *rollDPoSCtx) validateProposeBlock(blk Block, expectedProposer string) bool {
blkHash := blk.Hash()
errorLog := logger.Error().
Uint64("expectedHeight", ctx.round.height).
Str("expectedProposer", expectedProposer).
Str("hash", hex.EncodeToString(blkHash[:]))
if blk.Height() != ctx.round.height {
errorLog.Uint64("blockHeight", blk.Height()).
Msg("error when validating the block height")
return false
}
producer := blk.Proposer()
if producer == "" || producer != expectedProposer {
errorLog.Str("proposer", producer).
Msg("error when validating the block proposer")
return false
}
block := blk.(*blockWrapper)
if !block.VerifySignature() {
errorLog.Msg("error when validating the block signature")
return false
}
if producer == ctx.addr.RawAddress {
// If the block is self proposed, skip validation
return true
}
containCoinbase := true
if ctx.cfg.EnableDKG {
if ctx.shouldHandleDKG() {
containCoinbase = false
} else if err := verifyDKGSignature(block.Block, ctx.epoch.seed); err != nil {
// Verify dkg signature failed
errorLog.Err(err).Msg("Failed to verify the DKG signature")
return false
}
}
if err := ctx.chain.ValidateBlock(block.Block, containCoinbase); err != nil {
errorLog.Err(err).Msg("error when validating the proposed block")
return false
}
return true
}
func verifyDKGSignature(blk *block.Block, seedByte []byte) error {
return crypto.BLS.Verify(blk.DKGPubkey(), seedByte, blk.DKGSignature())
}
func (ctx *rollDPoSCtx) Broadcast(msg proto.Message) error {
var t iproto.ConsensusPb_ConsensusMessageType
switch msg.(type) {
case *iproto.BlockPb:
return ctx.broadcastHandler(msg)
case *iproto.ProposePb:
t = iproto.ConsensusPb_PROPOSAL
case *iproto.EndorsePb:
t = iproto.ConsensusPb_ENDORSEMENT
default:
return errors.New("Invalid message type")
}
data, err := proto.Marshal(msg)
if err != nil {
return err
}
consensusMsg := &iproto.ConsensusPb{
Height: ctx.round.height,
Round: ctx.round.number,
Type: t,
Data: data,
Timestamp: uint64(ctx.clock.Now().Unix()),
}
return ctx.broadcastHandler(consensusMsg)
}
// rollingDelegates will only allows the delegates chosen for given epoch to enter the epoch
func (ctx *rollDPoSCtx) rollingDelegates(epochNum uint64) ([]string, error) {
numDlgs := ctx.cfg.NumDelegates
height := uint64(numDlgs) * uint64(ctx.cfg.NumSubEpochs) * (epochNum - 1)
var candidates []*state.Candidate
var err error
if ctx.candidatesByHeightFunc != nil {
// Test only
candidates, err = ctx.candidatesByHeightFunc(height)
} else {
candidates, err = ctx.chain.CandidatesByHeight(height)
}
if err != nil {
return []string{}, errors.Wrap(err, "error when getting delegates from the candidate pool")
}
if len(candidates) < int(numDlgs) {
return []string{}, errors.Wrapf(ErrNotEnoughCandidates, "only %d delegates from the candidate pool", len(candidates))
}
var candidatesAddress []string
for _, candidate := range candidates {
candidatesAddress = append(candidatesAddress, candidate.Address)
}
crypto.SortCandidates(candidatesAddress, epochNum, ctx.epoch.seed)
return candidatesAddress[:numDlgs], nil
}
// calcEpochNum calculates the epoch ordinal number and the epoch start height offset, which is based on the height of
// the next block to be produced
func (ctx *rollDPoSCtx) calcEpochNumAndHeight() (uint64, uint64, error) {
height := ctx.chain.TipHeight()
numDlgs := ctx.cfg.NumDelegates
numSubEpochs := ctx.getNumSubEpochs()
epochNum := height/(uint64(numDlgs)*uint64(numSubEpochs)) + 1
epochHeight := uint64(numDlgs)*uint64(numSubEpochs)*(epochNum-1) + 1
return epochNum, epochHeight, nil
}
// calcSubEpochNum calculates the sub-epoch ordinal number
func (ctx *rollDPoSCtx) calcSubEpochNum() (uint64, error) {
height := ctx.chain.TipHeight() + 1
if height < ctx.epoch.height {
return 0, errors.New("Tip height cannot be less than epoch height")
}
numDlgs := ctx.cfg.NumDelegates
subEpochNum := (height - ctx.epoch.height) / uint64(numDlgs)
return subEpochNum, nil
}
// shouldHandleDKG indicates whether a node is in DKG stage
func (ctx *rollDPoSCtx) shouldHandleDKG() bool {
if !ctx.cfg.EnableDKG {
return false
}
return ctx.epoch.subEpochNum == 0
}
// generateDKGSecrets generates DKG secrets and witness
func (ctx *rollDPoSCtx) generateDKGSecrets() ([][]uint32, [][]byte, error) {
idList := make([][]uint8, 0)
for _, addr := range ctx.epoch.delegates {
dkgID := iotxaddress.CreateID(addr)
idList = append(idList, dkgID)
if addr == ctx.addr.RawAddress {
ctx.epoch.dkgAddress = iotxaddress.DKGAddress{ID: dkgID}
}
}
_, secrets, witness, err := crypto.DKG.Init(crypto.DKG.SkGeneration(), idList)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to generate DKG Secrets and Witness")
}
return secrets, witness, nil
}
// TODO: numDlgs should also be configurable in BLS. For test purpose, let's make it 21.
// generateDKGKeyPair generates DKG key pair
func (ctx *rollDPoSCtx) generateDKGKeyPair() ([]byte, []uint32, error) {
numDlgs := ctx.cfg.NumDelegates
if numDlgs != 21 {
return nil, nil, errors.New("Number of delegates must be 21 for test purpose")
}
shares := make([][]uint32, numDlgs)
shareStatusMatrix := make([][21]bool, numDlgs)
for i := range shares {
shares[i] = make([]uint32, sigSize)
}
for i, delegate := range ctx.epoch.delegates {
if secret, ok := ctx.epoch.committedSecrets[delegate]; ok {
shares[i] = secret
for j := 0; j < int(numDlgs); j++ {
shareStatusMatrix[j][i] = true
}
}
}
_, dkgPubKey, dkgPriKey, err := crypto.DKG.KeyPairGeneration(shares, shareStatusMatrix)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to generate DKG key pair")
}
return dkgPubKey, dkgPriKey, nil
}
// getNumSubEpochs returns max(configured number, 1)
func (ctx *rollDPoSCtx) getNumSubEpochs() uint {
num := uint(1)
if ctx.cfg.NumSubEpochs > 0 {
num = ctx.cfg.NumSubEpochs
}
if ctx.cfg.EnableDKG {
num++
}
return num
}
// rotatedProposer will rotate among the delegates to choose the proposer. It is pseudo order based on the position
// in the delegate list and the block height
func (ctx *rollDPoSCtx) rotatedProposer() (string, uint64, uint32, error) {
// Next block height
height := ctx.chain.TipHeight() + 1
round, proposer, err := ctx.calcProposer(height, ctx.epoch.delegates)
return proposer, height, round, err
}
// calcProposer calculates the proposer for the block at a given height
func (ctx *rollDPoSCtx) calcProposer(height uint64, delegates []string) (uint32, string, error) {
numDelegates := len(delegates)
if numDelegates == 0 {
return 0, "", ErrZeroDelegate
}
timeSlotIndex := uint32(0)
if ctx.cfg.ProposerInterval > 0 {
duration, err := ctx.calcDurationSinceLastBlock()
if err != nil || duration < 0 {
if !ctx.cfg.TimeBasedRotation {
return 0, delegates[(height)%uint64(numDelegates)], nil
}
return 0, "", errors.Wrap(err, "error when computing the duration since last block time")
}
if duration > ctx.cfg.ProposerInterval {
timeSlotIndex = uint32(duration/ctx.cfg.ProposerInterval) - 1
}
}
if !ctx.cfg.TimeBasedRotation {
return timeSlotIndex, delegates[(height)%uint64(numDelegates)], nil
}
// TODO: should downgrade to debug level in the future
logger.Info().Uint32("slot", timeSlotIndex).Msg("calculate time slot offset")
timeSlotMtc.WithLabelValues().Set(float64(timeSlotIndex))
return timeSlotIndex, delegates[(height+uint64(timeSlotIndex))%uint64(numDelegates)], nil
}
// mintBlock mints a new block to propose
func (ctx *rollDPoSCtx) mintBlock() (*block.Block, error) {
if ctx.shouldHandleDKG() {
return ctx.mintSecretBlock()
}
return ctx.mintCommonBlock()
}
// mintSecretBlock collects DKG secret proposals and witness and creates a block to propose
func (ctx *rollDPoSCtx) mintSecretBlock() (*block.Block, error) {
secrets := ctx.epoch.secrets
witness := ctx.epoch.witness
if len(secrets) != len(ctx.epoch.delegates) {
return nil, errors.New("Number of secrets does not match number of delegates")
}
confirmedNonce, err := ctx.chain.Nonce(ctx.addr.RawAddress)
if err != nil {
return nil, errors.Wrap(err, "failed to get the confirmed nonce of secret block producer")
}
nonce := confirmedNonce + 1
secretProposals := make([]*action.SecretProposal, 0)
for i, delegate := range ctx.epoch.delegates {
secretProposal, err := action.NewSecretProposal(nonce, ctx.addr.RawAddress, delegate, secrets[i])
if err != nil {
return nil, errors.Wrap(err, "failed to create the secret proposal")
}
secretProposals = append(secretProposals, secretProposal)
nonce++
}
secretWitness, err := action.NewSecretWitness(nonce, ctx.addr.RawAddress, witness)
if err != nil {
return nil, errors.Wrap(err, "failed to create the secret witness")
}
blk, err := ctx.chain.MintNewSecretBlock(secretProposals, secretWitness, ctx.addr)
if err != nil {
return nil, err
}
logger.Info().
Uint64("height", blk.Height()).
Int("secretProposals", len(blk.SecretProposals)).
Msg("minted a new secret block")
return blk, nil
}
// mintCommonBlock picks the actions and creates a common block to propose
func (ctx *rollDPoSCtx) mintCommonBlock() (*block.Block, error) {
actions := ctx.actPool.PickActs()
logger.Debug().
Int("action", len(actions)).
Msg("pick actions from the action pool")
blk, err := ctx.chain.MintNewBlock(actions, ctx.addr, &ctx.epoch.dkgAddress,
ctx.epoch.seed, "")
if err != nil {
return nil, err
}
logger.Info().
Uint64("height", blk.Height()).
Int("actions", len(blk.Actions)).
Msg("minted a new block")
return blk, nil
}
// calcDurationSinceLastBlock returns the duration since last block time
func (ctx *rollDPoSCtx) calcDurationSinceLastBlock() (time.Duration, error) {
height := ctx.chain.TipHeight()
blk, err := ctx.chain.GetBlockByHeight(height)
if err != nil {
return 0, errors.Wrapf(err, "error when getting the block at height: %d", height)
}
return ctx.clock.Now().Sub(blk.Header.Timestamp()), nil
}
// calcQuorum calculates if more than 2/3 vote yes or no including self's vote
func (ctx *rollDPoSCtx) calcQuorum(decisions map[string]bool) (bool, bool) {
yes := 0
no := 0
for _, decision := range decisions {
if decision {
yes++
} else {
no++
}
}
numDelegates := len(ctx.epoch.delegates)
return yes >= numDelegates*2/3+1, no >= numDelegates*1/3
}
// isEpochFinished checks the epoch is finished or not
func (ctx *rollDPoSCtx) isEpochFinished() (bool, error) {
height := ctx.chain.TipHeight()
// if the height of the last committed block is already the last one should be minted from this epochStart, go back
// to epochStart start
if height >= ctx.epoch.height+uint64(uint(len(ctx.epoch.delegates))*ctx.epoch.numSubEpochs)-1 {
return true, nil
}
return false, nil
}
// isDKGFinished checks the DKG sub-epoch is finished or not
func (ctx *rollDPoSCtx) isDKGFinished() bool {
height := ctx.chain.TipHeight()
return height >= ctx.epoch.height+uint64(len(ctx.epoch.delegates))-1
}
// updateSeed returns the seed for the next epoch
func (ctx *rollDPoSCtx) updateSeed() ([]byte, error) {
epochNum, epochHeight, err := ctx.calcEpochNumAndHeight()
if err != nil {
return hash.Hash256b(ctx.epoch.seed), errors.Wrap(err, "Failed to do decode seed")
}
if epochNum <= 1 {
return crypto.CryptoSeed, nil
}
selectedID := make([][]uint8, 0)
selectedSig := make([][]byte, 0)
selectedPK := make([][]byte, 0)
for h := uint64(ctx.cfg.NumDelegates)*uint64(ctx.cfg.NumSubEpochs)*(epochNum-2) + 1; h < epochHeight && len(selectedID) <= crypto.Degree; h++ {
blk, err := ctx.chain.GetBlockByHeight(h)
if err != nil {
continue
}
if len(blk.DKGID()) > 0 && len(blk.DKGPubkey()) > 0 && len(blk.DKGSignature()) > 0 {
selectedID = append(selectedID, blk.DKGID())
selectedSig = append(selectedSig, blk.DKGSignature())
selectedPK = append(selectedPK, blk.DKGPubkey())
}
}
if len(selectedID) <= crypto.Degree {
return hash.Hash256b(ctx.epoch.seed), errors.New("DKG signature/pubic key is not enough to aggregate")
}
aggregateSig, err := crypto.BLS.SignAggregate(selectedID, selectedSig)
if err != nil {
return hash.Hash256b(ctx.epoch.seed), errors.Wrap(err, "Failed to generate aggregate signature to update Seed")
}
if err = crypto.BLS.VerifyAggregate(selectedID, selectedPK, ctx.epoch.seed, aggregateSig); err != nil {
return hash.Hash256b(ctx.epoch.seed), errors.Wrap(err, "Failed to verify aggregate signature to update Seed")
}
return aggregateSig, nil
}
// epochCtx keeps the context data for the current epoch
type epochCtx struct {
// num is the ordinal number of an epoch
num uint64
// height means offset for current epochStart (i.e., the height of the first block generated in this epochStart)
height uint64
// numSubEpochs defines number of sub-epochs/rotations will happen in an epochStart
numSubEpochs uint
// subEpochNum is the ordinal number of sub-epoch within the current epoch
subEpochNum uint64
// secrets are the dkg secrets sent from current node to other delegates
secrets [][]uint32
// witness is the dkg secret witness sent from current node to other delegates
witness [][]byte
// committedSecrets are the secret shares within the secret blocks committed by current node
committedSecrets map[string][]uint32
delegates []string
dkgAddress iotxaddress.DKGAddress
seed []byte
}
// roundCtx keeps the context data for the current round and block.
type roundCtx struct {
height uint64
number uint32
proofOfLock *endorsement.Set
timestamp time.Time
block Block
endorsementSets map[string]*endorsement.Set
proposer string
}
// RollDPoS is Roll-DPoS consensus main entrance
type RollDPoS struct {
cfsm *cFSM
ctx *rollDPoSCtx
}
// Start starts RollDPoS consensus
func (r *RollDPoS) Start(ctx context.Context) error {
if err := r.cfsm.Start(ctx); err != nil {
return errors.Wrap(err, "error when starting the consensus FSM")
}
r.cfsm.produce(r.cfsm.newCEvt(eRollDelegates), r.ctx.cfg.Delay)
return nil
}
// Stop stops RollDPoS consensus
func (r *RollDPoS) Stop(ctx context.Context) error {
return errors.Wrap(r.cfsm.Stop(ctx), "error when stopping the consensus FSM")
}
// HandleConsensusMsg handles incoming consensus message
func (r *RollDPoS) HandleConsensusMsg(msg *iproto.ConsensusPb) error {
data := msg.Data
tipHeight := r.ctx.chain.TipHeight()
switch msg.Type {
case iproto.ConsensusPb_PROPOSAL:
pPb := &iproto.ProposePb{}
if err := proto.Unmarshal(data, pPb); err != nil {
return err
}
pbEvt, err := r.cfsm.newProposeBlkEvtFromProposePb(pPb)
if err != nil {
return errors.Wrap(err, "error when casting a proto msg to proposeBlkEvt")
}
if pbEvt.height() <= tipHeight {
return errors.New("old block proposal")
}
r.cfsm.produce(pbEvt, 0)
case iproto.ConsensusPb_ENDORSEMENT:
ePb := &iproto.EndorsePb{}
if err := proto.Unmarshal(data, ePb); err != nil {
return err
}
eEvt, err := r.cfsm.newEndorseEvtWithEndorsePb(ePb)
if err != nil {
return errors.Wrap(err, "error when casting a proto msg to endorse")
}
if eEvt.height() <= tipHeight && eEvt.endorse.Endorser() != r.ctx.addr.RawAddress {
logger.Debug().
Uint64("event height", eEvt.height()).
Uint64("Chain Height", tipHeight).
Msg("ignore old endorsement message")
return nil
}
r.cfsm.produce(eEvt, 0)
default:
return errors.Errorf("Invalid consensus message type %s", msg.Type)
}
return nil
}
// Metrics returns RollDPoS consensus metrics
func (r *RollDPoS) Metrics() (scheme.ConsensusMetrics, error) {
var metrics scheme.ConsensusMetrics
// Compute the epoch ordinal number
epochNum, _, err := r.ctx.calcEpochNumAndHeight()
if err != nil {
return metrics, errors.Wrap(err, "error when calculating the epoch ordinal number")
}
// Compute delegates
delegates, err := r.ctx.rollingDelegates(epochNum)
if err != nil {
return metrics, errors.Wrap(err, "error when getting the rolling delegates")
}
// Compute the height
height := r.ctx.chain.TipHeight()
// Compute block producer
_, producer, err := r.ctx.calcProposer(height+1, delegates)
if err != nil {
return metrics, errors.Wrap(err, "error when calculating the block producer")
}
// Get all candidates
candidates, err := r.ctx.chain.CandidatesByHeight(height)
if err != nil {
return metrics, errors.Wrap(err, "error when getting all candidates")
}
candidateAddresses := make([]string, len(candidates))
for i, c := range candidates {
candidateAddresses[i] = c.Address
}
crypto.SortCandidates(candidateAddresses, epochNum, r.ctx.epoch.seed)
return scheme.ConsensusMetrics{
LatestEpoch: epochNum,
LatestHeight: height,
LatestDelegates: delegates,
LatestBlockProducer: producer,
Candidates: candidateAddresses,
}, nil
}
// NumPendingEvts returns the number of pending events
func (r *RollDPoS) NumPendingEvts() int {
return len(r.cfsm.evtq)
}
// CurrentState returns the current state
func (r *RollDPoS) CurrentState() fsm.State {
return r.cfsm.fsm.CurrentState()
}
// Builder is the builder for RollDPoS
type Builder struct {
cfg config.RollDPoS
// TODO: we should use keystore in the future
addr *iotxaddress.Address
chain blockchain.Blockchain
actPool actpool.ActPool
broadcastHandler scheme.Broadcast
clock clock.Clock
rootChainAPI explorer.Explorer
candidatesByHeightFunc func(uint64) ([]*state.Candidate, error)
}
// NewRollDPoSBuilder instantiates a Builder instance
func NewRollDPoSBuilder() *Builder {
return &Builder{}
}
// SetConfig sets RollDPoS config
func (b *Builder) SetConfig(cfg config.RollDPoS) *Builder {
b.cfg = cfg
return b
}
// SetAddr sets the address and key pair for signature
func (b *Builder) SetAddr(addr *iotxaddress.Address) *Builder {
b.addr = addr
return b
}
// SetBlockchain sets the blockchain APIs
func (b *Builder) SetBlockchain(chain blockchain.Blockchain) *Builder {
b.chain = chain
return b
}
// SetActPool sets the action pool APIs
func (b *Builder) SetActPool(actPool actpool.ActPool) *Builder {
b.actPool = actPool
return b
}
// SetBroadcast sets the broadcast callback
func (b *Builder) SetBroadcast(broadcastHandler scheme.Broadcast) *Builder {
b.broadcastHandler = broadcastHandler
return b
}
// SetClock sets the clock
func (b *Builder) SetClock(clock clock.Clock) *Builder {
b.clock = clock
return b
}
// SetRootChainAPI sets root chain API
func (b *Builder) SetRootChainAPI(api explorer.Explorer) *Builder {
b.rootChainAPI = api
return b
}
// SetCandidatesByHeightFunc sets candidatesByHeightFunc, which is only used by tests
func (b *Builder) SetCandidatesByHeightFunc(
candidatesByHeightFunc func(uint64) ([]*state.Candidate, error),
) *Builder {
b.candidatesByHeightFunc = candidatesByHeightFunc
return b
}
// Build builds a RollDPoS consensus module
func (b *Builder) Build() (*RollDPoS, error) {
if b.chain == nil {
return nil, errors.Wrap(ErrNewRollDPoS, "blockchain APIs is nil")
}
if b.actPool == nil {
return nil, errors.Wrap(ErrNewRollDPoS, "action pool APIs is nil")
}
if b.broadcastHandler == nil {
return nil, errors.Wrap(ErrNewRollDPoS, "broadcast callback is nil")
}
if b.clock == nil {
b.clock = clock.New()
}
ctx := rollDPoSCtx{
cfg: b.cfg,
addr: b.addr,
chain: b.chain,
actPool: b.actPool,
broadcastHandler: b.broadcastHandler,
clock: b.clock,
rootChainAPI: b.rootChainAPI,
candidatesByHeightFunc: b.candidatesByHeightFunc,
}
cfsm, err := newConsensusFSM(&ctx)
if err != nil {
return nil, errors.Wrap(err, "error when constructing the consensus FSM")
}
return &RollDPoS{
cfsm: cfsm,
ctx: &ctx,
}, nil
}
| 1 | 14,248 | Can we log if this actually happens. | iotexproject-iotex-core | go |
@@ -203,6 +203,9 @@ public class RegistrationRequest {
if (pendingConfiguration.port != null) {
pendingRequest.configuration.port = pendingConfiguration.port;
}
+ if (pendingConfiguration.remoteHost != null) {
+ pendingRequest.configuration.remoteHost = pendingConfiguration.remoteHost;
+ }
// make sure we have a valid host
pendingRequest.configuration.fixUpHost(); | 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.grid.common;
import org.openqa.grid.common.exception.GridConfigurationException;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.json.JsonException;
import java.util.Map;
import java.util.TreeMap;
/**
* Helper to register to the grid. Using JSON to exchange the object between the node and the hub.
*/
public class RegistrationRequest {
// some special param for capability
public static final String MAX_INSTANCES = "maxInstances";
// see enum SeleniumProtocol
public static final String SELENIUM_PROTOCOL = "seleniumProtocol";
public static final String PATH = "path";
private String name;
private String description;
private GridNodeConfiguration configuration;
/**
* Create a new registration request using the default values of a
* {@link GridNodeConfiguration}
*/
public RegistrationRequest() {
this(new GridNodeConfiguration());
}
/**
* Create a new registration request using the supplied {@link GridNodeConfiguration}
*
* @param configuration the {@link GridNodeConfiguration} to use. Internally calls {@code new
* GridNodeConfiguration()} if a {@code null} value is provided since a
* request without configuration is not valid.
*/
public RegistrationRequest(GridNodeConfiguration configuration) {
this(configuration, null, null);
}
/**
* Create a new registration request using the supplied {@link GridNodeConfiguration}, and name
*
* @param configuration the {@link GridNodeConfiguration} to use. Internally calls {@code new
* GridNodeConfiguration()} if a {@code null} value is provided since a
* request without configuration is not valid.
* @param name the name for the remote
*/
public RegistrationRequest(GridNodeConfiguration configuration, String name) {
this(configuration, name, null);
}
/**
* Create a new registration request using the supplied {@link GridNodeConfiguration}, name, and
* description
*
* @param configuration the {@link GridNodeConfiguration} to use. Internally calls {@code new
* GridNodeConfiguration()} if a {@code null} value is provided since a
* request without configuration is not valid.
* @param name the name for the remote
* @param description the description for the remote host
*/
public RegistrationRequest(GridNodeConfiguration configuration, String name, String description) {
this.configuration = (configuration == null) ? new GridNodeConfiguration() : configuration;
this.name = name;
this.description = description;
// make sure we have something that looks like a valid host
this.configuration.fixUpHost();
// make sure the capabilities are updated with required fields
this.configuration.fixUpCapabilities();
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public GridNodeConfiguration getConfiguration() {
return configuration;
}
public Map<String, Object> toJson() {
Map<String, Object> json = new TreeMap<>();
json.put("class", getClass());
json.put("name", getName());
json.put("description", getDescription());
json.put("configuration", getConfiguration());
return json;
}
/**
* Create an object from a registration request formatted as a json string.
*/
public static RegistrationRequest fromJson(Map<String, Object> raw) throws JsonException {
// If we could, we'd just get Json to coerce this for us, but that would lead to endless
// recursion as the first thing it would do would be to call this very method. *sigh*
Json json = new Json();
RegistrationRequest request = new RegistrationRequest();
if (raw.get("name") instanceof String) {
request.name = (String) raw.get("name");
}
if (raw.get("description") instanceof String) {
request.description = (String) raw.get("description");
}
if (raw.get("configuration") instanceof Map) {
// This is nasty. Look away now!
String converted = json.toJson(raw.get("configuration"));
request.configuration = GridConfiguredJson.toType(converted, GridNodeConfiguration.class);
}
return request;
}
/**
* Build a RegistrationRequest.
*/
public static RegistrationRequest build() {
return RegistrationRequest.build(new GridNodeConfiguration(), null, null);
}
/**
* Build a RegistrationRequest from the provided {@link GridNodeConfiguration}. This is different
* than {@code new RegistrationRequest(GridNodeConfiguration)} because it will first load any
* specified {@link GridNodeConfiguration#nodeConfigFile} and then merge the provided
* configuration onto it.
*
* @param configuration the {@link GridNodeConfiguration} to use. Internally calls {@code new
* GridNodeConfiguration()} if a {@code null} value is provided since a
* request without configuration is not valid.
*/
public static RegistrationRequest build(GridNodeConfiguration configuration) {
return RegistrationRequest.build(configuration, null, null);
}
/**
* Build a RegistrationRequest from the provided {@link GridNodeConfiguration}, use the provided
* name. This is different than {@code new RegistrationRequest(GridNodeConfiguration, String)}
* because it will first load any specified {@link GridNodeConfiguration#nodeConfigFile} and then
* merge the provided configuration onto it.
*
* @param configuration the {@link GridNodeConfiguration} to use. Internally calls {@code new
* GridNodeConfiguration()} if a {@code null} value is provided since a
* request without configuration is not valid.
* @param name the name for the remote
*/
public static RegistrationRequest build(GridNodeConfiguration configuration, String name) {
return RegistrationRequest.build(configuration, name, null);
}
/**
* Build a RegistrationRequest from the provided {@link GridNodeConfiguration}, use the provided
* name and description. This is different than {@code new RegistrationRequest(GridNodeConfiguration,
* String, String)} because it will first load any specified {@link
* GridNodeConfiguration#nodeConfigFile} and then merge the provided configuration onto it.
*
* @param configuration the {@link GridNodeConfiguration} to use. Internally calls {@code new
* GridNodeConfiguration()} if a {@code null} value is provided since a
* request without configuration is not valid.
* @param name the name for the remote
* @param description the description for the remote host
*/
public static RegistrationRequest build(GridNodeConfiguration configuration, String name, String description) {
RegistrationRequest pendingRequest = new RegistrationRequest(configuration, name, description);
GridNodeConfiguration pendingConfiguration = pendingRequest.configuration;
if (pendingConfiguration.nodeConfigFile != null) {
pendingRequest.configuration = GridNodeConfiguration.loadFromJSON(pendingConfiguration.nodeConfigFile);
}
pendingRequest.configuration.merge(pendingConfiguration);
//update important merge protected values for the pendingRequest we are building.
if (pendingConfiguration.host != null) {
pendingRequest.configuration.host = pendingConfiguration.host;
}
if (pendingConfiguration.port != null) {
pendingRequest.configuration.port = pendingConfiguration.port;
}
// make sure we have a valid host
pendingRequest.configuration.fixUpHost();
// make sure the capabilities are updated with required fields
pendingRequest.configuration.fixUpCapabilities();
pendingRequest.configuration.dropCapabilitiesThatDoesNotMatchCurrentPlatform();
return pendingRequest;
}
/**
* Validate the current setting and throw a config exception is an invalid setup is detected.
*
* @throws GridConfigurationException grid configuration
*/
public void validate() throws GridConfigurationException {
// validations occur here in the getters called on the configuration.
try {
configuration.getHubHost();
configuration.getHubPort();
} catch (RuntimeException e) {
throw new GridConfigurationException(e.getMessage());
}
}
}
| 1 | 15,979 | This is not really needed, the line added in `GridNodeConfiguration.java` is what really fixes the `remoteHost` regression. | SeleniumHQ-selenium | py |
@@ -1,8 +1,10 @@
/* eslint-disable no-restricted-globals */
/* global __STORYBOOK_CLIENT_API__ */
+
/**
* External dependencies
*/
+import lodash from 'lodash';
import React from 'react';
import { addDecorator, configure } from '@storybook/react';
| 1 | /* eslint-disable no-restricted-globals */
/* global __STORYBOOK_CLIENT_API__ */
/**
* External dependencies
*/
import React from 'react';
import { addDecorator, configure } from '@storybook/react';
/**
* WordPress dependencies
*/
import { createHigherOrderComponent } from '@wordpress/compose';
import {
Component,
createRef,
Fragment,
createElement,
createPortal,
} from '@wordpress/element';
import { __, sprintf, setLocaleData } from '@wordpress/i18n';
import {
getQueryString,
addQueryArgs,
} from '@wordpress/url';
import lodash from 'lodash';
import {
addFilter,
removeFilter,
addAction,
doAction,
applyFilters,
removeAction,
removeAllFilters,
} from '@wordpress/hooks';
/**
* Internal dependencies
*/
import '../assets/sass/wpdashboard.scss';
import '../assets/sass/adminbar.scss';
import '../assets/sass/admin.scss';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/common.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/dashboard.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/edit.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/forms.css';
import { googlesitekit as dashboardData } from '../.storybook/data/wp-admin-admin.php-page=googlesitekit-dashboard-googlesitekit';
import { bootstrapFetchMocks } from './fetch-mocks';
// Setup.
const wp = {};
wp.element = wp.element || {};
wp.i18n = wp.i18n || {};
wp.hooks = wp.hooks || {};
wp.url = {
getQueryString,
addQueryArgs,
};
wp.compose = {};
wp.compose.createHigherOrderComponent = createHigherOrderComponent;
wp.hooks.addFilter = addFilter;
wp.hooks.removeFilter = removeFilter;
wp.hooks.addAction = addAction;
wp.hooks.doAction = doAction;
wp.hooks.applyFilters = applyFilters;
wp.hooks.removeAction = removeAction;
wp.hooks.removeAllFilters = removeAllFilters;
wp.element.Component = Component;
wp.element.createRef = createRef;
wp.element.Fragment = Fragment;
wp.element.createElement = createElement;
wp.element.createPortal = createPortal;
wp.i18n.__ = __ || {};
wp.i18n.setLocaleData = setLocaleData || {};
wp.i18n.sprintf = sprintf || {};
global.wp = global.wp || wp;
global.React = React;
global.lodash = lodash;
global._googlesitekitLegacyData = dashboardData;
global._googlesitekitLegacyData.admin.assetsRoot = './assets/';
global._googlesitekitLegacyData.isStorybook = true;
global._googlesitekitBaseData = {
homeURL: 'http://example.com/',
referenceSiteURL: 'http://example.com/',
userIDHash: 'storybook',
adminURL: 'http://example.com/wp-admin/',
assetsURL: 'http://example.com/wp-content/plugins/google-site-kit/dist/assets/',
blogPrefix: 'wp_',
ampMode: false,
isNetworkMode: false,
isFirstAdmin: true,
isOwner: true,
splashURL: 'http://example.com/wp-admin/admin.php?page=googlesitekit-splash',
proxySetupURL: 'https://sitekit.withgoogle.com/site-management/setup/?scope=openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsiteverification%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fwebmasters%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.manage.users%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.edit&supports=credentials_retrieval%20short_verification_token%20file_verification&nonce=&site_id=storybooksiteid.apps.sitekit.withgoogle.com',
proxyPermissionsURL: 'https://sitekit.withgoogle.com/site-management/permissions/?token=storybooktoken&site_id=storybooksiteid.apps.sitekit.withgoogle.com',
trackingEnabled: false,
trackingID: 'UA-000000000-1',
};
global._googlesitekitEntityData = {
currentEntityURL: null,
currentEntityType: null,
currentEntityTitle: null,
currentEntityID: null,
};
bootstrapFetchMocks();
// Global Decorator.
addDecorator( ( story ) => <div className="googlesitekit-plugin-preview">
<div className="googlesitekit-plugin">{ story() }</div>
</div> );
const req = require.context( '../stories', true, /\.stories\.js$/ );
function loadStories() {
req.keys().forEach( ( filename ) => req( filename ) );
}
configure( loadStories, module );
// TODO Would be nice if this wrote to a file. This logs our Storybook data to the browser console. Currently it gets put in .storybook/storybook-data and used in tests/backstop/scenarios.js.
// eslint-disable-next-line no-console
console.log( '__STORYBOOK_CLIENT_API__.raw()', __STORYBOOK_CLIENT_API__.raw() );
| 1 | 32,448 | It looks like the import format was only changed from one-per-line to all on one line here. Can we keep it as it was so it's easier to see what changed? It's also more consistent with how we format multiple imports in other components. | google-site-kit-wp | js |
@@ -57,8 +57,10 @@ module Selenium
#
# @return [Driver]
#
- # @see Selenium::WebDriver::Remote::Bridge
+ # @see Selenium::WebDriver::Remote::OSSBridge
+ # @see Selenium::WebDriver::Remote::W3CBridge
# @see Selenium::WebDriver::Firefox::Bridge
+ # @see Selenium::WebDriver::Firefox::W3CBridge
# @see Selenium::WebDriver::IE::Bridge
# @see Selenium::WebDriver::Edge::Bridge
# @see Selenium::WebDriver::Chrome::Bridge | 1 | # encoding: utf-8
#
# 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.
require 'childprocess'
require 'tmpdir'
require 'fileutils'
require 'date'
require 'json'
require 'selenium/webdriver/common'
require 'selenium/webdriver/atoms'
module Selenium
module WebDriver
Point = Struct.new(:x, :y)
Dimension = Struct.new(:width, :height)
Location = Struct.new(:latitude, :longitude, :altitude)
autoload :Chrome, 'selenium/webdriver/chrome'
autoload :Edge, 'selenium/webdriver/edge'
autoload :Firefox, 'selenium/webdriver/firefox'
autoload :IE, 'selenium/webdriver/ie'
autoload :PhantomJS, 'selenium/webdriver/phantomjs'
autoload :Remote, 'selenium/webdriver/remote'
autoload :Safari, 'selenium/webdriver/safari'
autoload :Support, 'selenium/webdriver/support'
# @api private
def self.root
@root ||= File.expand_path('../..', __FILE__)
end
#
# Create a new Driver instance with the correct bridge for the given browser
#
# @param browser [:ie, :internet_explorer, :edge, :remote, :chrome, :firefox, :ff, :phantomjs, :safari]
# the driver type to use
# @param *rest
# arguments passed to Bridge.new
#
# @return [Driver]
#
# @see Selenium::WebDriver::Remote::Bridge
# @see Selenium::WebDriver::Firefox::Bridge
# @see Selenium::WebDriver::IE::Bridge
# @see Selenium::WebDriver::Edge::Bridge
# @see Selenium::WebDriver::Chrome::Bridge
# @see Selenium::WebDriver::PhantomJS::Bridge
# @see Selenium::WebDriver::Safari::Bridge
#
# @example
#
# WebDriver.for :firefox, :profile => "some-profile"
# WebDriver.for :firefox, :profile => Profile.new
# WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps
#
# One special argument is not passed on to the bridges, :listener.
# You can pass a listener for this option to get notified of WebDriver events.
# The passed object must respond to #call or implement the methods from AbstractEventListener.
#
# @see Selenium::WebDriver::Support::AbstractEventListener
#
def self.for(*args)
WebDriver::Driver.for(*args)
end
end # WebDriver
end # Selenium
| 1 | 14,227 | Maybe call it `WireBridge`? | SeleniumHQ-selenium | py |
@@ -5,12 +5,16 @@ import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.StrictMode;
import android.preference.PreferenceManager;
+import android.util.Log;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.mozilla.geckoview.GeckoSessionSettings;
import org.mozilla.telemetry.TelemetryHolder;
import org.mozilla.vrbrowser.BuildConfig;
import org.mozilla.vrbrowser.R;
import org.mozilla.vrbrowser.telemetry.TelemetryWrapper;
+import org.mozilla.vrbrowser.ui.widgets.WidgetPlacement;
import org.mozilla.vrbrowser.utils.DeviceType;
import org.mozilla.vrbrowser.utils.LocaleUtils;
import org.mozilla.vrbrowser.utils.StringUtils; | 1 | package org.mozilla.vrbrowser.browser;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import org.mozilla.geckoview.GeckoSessionSettings;
import org.mozilla.telemetry.TelemetryHolder;
import org.mozilla.vrbrowser.BuildConfig;
import org.mozilla.vrbrowser.R;
import org.mozilla.vrbrowser.telemetry.TelemetryWrapper;
import org.mozilla.vrbrowser.utils.DeviceType;
import org.mozilla.vrbrowser.utils.LocaleUtils;
import org.mozilla.vrbrowser.utils.StringUtils;
import androidx.annotation.NonNull;
import java.util.Locale;
import static org.mozilla.vrbrowser.utils.ServoUtils.isServoAvailable;
public class SettingsStore {
private static final String LOGTAG = "VRB";
private static SettingsStore mSettingsInstance;
public static synchronized @NonNull
SettingsStore getInstance(final @NonNull Context aContext) {
if (mSettingsInstance == null) {
mSettingsInstance = new SettingsStore(aContext);
}
return mSettingsInstance;
}
private Context mContext;
private SharedPreferences mPrefs;
// Developer options default values
public final static boolean REMOTE_DEBUGGING_DEFAULT = false;
public final static boolean CONSOLE_LOGS_DEFAULT = false;
public final static boolean ENV_OVERRIDE_DEFAULT = false;
public final static boolean MULTIPROCESS_DEFAULT = false;
public final static boolean PERFORMANCE_MONITOR_DEFAULT = true;
public final static boolean DRM_PLAYBACK_DEFAULT = false;
public final static boolean TRACKING_DEFAULT = true;
public final static boolean NOTIFICATIONS_DEFAULT = true;
public final static boolean SPEECH_DATA_COLLECTION_DEFAULT = false;
public final static boolean SERVO_DEFAULT = false;
public final static int UA_MODE_DEFAULT = GeckoSessionSettings.USER_AGENT_MODE_VR;
public final static int INPUT_MODE_DEFAULT = 1;
public final static float DISPLAY_DENSITY_DEFAULT = 1.0f;
public final static int WINDOW_WIDTH_DEFAULT = 800;
public final static int WINDOW_HEIGHT_DEFAULT = 450;
public final static int DISPLAY_DPI_DEFAULT = 96;
public final static int MAX_WINDOW_WIDTH_DEFAULT = 1200;
public final static int MAX_WINDOW_HEIGHT_DEFAULT = 1200;
public final static int POINTER_COLOR_DEFAULT_DEFAULT = Color.parseColor("#FFFFFF");
public final static int SCROLL_DIRECTION_DEFAULT = 0;
public final static String ENV_DEFAULT = "offworld";
public final static float BROWSER_WORLD_WIDTH_DEFAULT = 4.0f;
public final static float BROWSER_WORLD_HEIGHT_DEFAULT = 2.25f;
public final static int MSAA_DEFAULT_LEVEL = 1;
public final static boolean AUDIO_ENABLED = false;
public final static float CYLINDER_DENSITY_ENABLED_DEFAULT = 4680.0f;
public final static int FOVEATED_APP_DEFAULT_LEVEL = 0;
public final static int FOVEATED_WEBVR_DEFAULT_LEVEL = 0;
private final static long CRASH_RESTART_DELTA = 2000;
public final static boolean AUTOPLAY_ENABLED = false;
// Enable telemetry by default (opt-out).
private final static boolean enableCrashReportingByDefault = false;
private final static boolean enableTelemetryByDefault = true;
private int mCachedScrollDirection = -1;
public SettingsStore(Context aContext) {
mContext = aContext;
mPrefs = PreferenceManager.getDefaultSharedPreferences(aContext);
}
public boolean isCrashReportingEnabled() {
return mPrefs.getBoolean(mContext.getString(R.string.settings_key_crash), enableCrashReportingByDefault);
}
public void setCrashReportingEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_crash), isEnabled);
editor.commit();
}
public boolean isTelemetryEnabled() {
// The first access to shared preferences will require a disk read.
final StrictMode.ThreadPolicy threadPolicy = StrictMode.allowThreadDiskReads();
try {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_telemetry), enableTelemetryByDefault);
} finally {
StrictMode.setThreadPolicy(threadPolicy);
}
}
public void setTelemetryEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_telemetry), isEnabled);
editor.commit();
// If the state of Telemetry is not the same, we reinitialize it.
final boolean hasEnabled = isTelemetryEnabled();
if (hasEnabled != isEnabled) {
TelemetryWrapper.init(mContext);
}
TelemetryHolder.get().getConfiguration().setUploadEnabled(isEnabled);
TelemetryHolder.get().getConfiguration().setCollectionEnabled(isEnabled);
}
public void setGeolocationData(String aGeolocationData) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(mContext.getString(R.string.settings_key_geolocation_data), aGeolocationData);
editor.commit();
}
public String getGeolocationData() {
return mPrefs.getString(mContext.getString(R.string.settings_key_geolocation_data), "");
}
public boolean isRemoteDebuggingEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_remote_debugging), REMOTE_DEBUGGING_DEFAULT);
}
public void setRemoteDebuggingEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_remote_debugging), isEnabled);
editor.commit();
}
public boolean isConsoleLogsEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_console_logs), CONSOLE_LOGS_DEFAULT);
}
public void setConsoleLogsEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_console_logs), isEnabled);
editor.commit();
}
public boolean isDrmContentPlaybackEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_drm_playback), DRM_PLAYBACK_DEFAULT);
}
public void setDrmContentPlaybackEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_drm_playback), isEnabled);
editor.commit();
}
public boolean isTrackingProtectionEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_tracking_protection), TRACKING_DEFAULT);
}
public void setTrackingProtectionEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_tracking_protection), isEnabled);
editor.commit();
}
public boolean isEnvironmentOverrideEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_environment_override), ENV_OVERRIDE_DEFAULT);
}
public void setEnvironmentOverrideEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_environment_override), isEnabled);
editor.commit();
}
public boolean isMultiprocessEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_multiprocess), MULTIPROCESS_DEFAULT);
}
public void setMultiprocessEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_multiprocess), isEnabled);
editor.commit();
}
public boolean isPerformanceMonitorEnabled() {
return mPrefs.getBoolean(mContext.getString(R.string.settings_key_performance_monitor), PERFORMANCE_MONITOR_DEFAULT);
}
public void setPerformanceMonitorEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_performance_monitor), isEnabled);
editor.commit();
}
public boolean isServoEnabled() {
return isServoAvailable() && mPrefs.getBoolean(mContext.getString(R.string.settings_key_servo), SERVO_DEFAULT);
}
public void setServoEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_servo), isEnabled);
editor.commit();
}
public int getUaMode() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_user_agent_version), UA_MODE_DEFAULT);
}
public void setUaMode(int mode) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_user_agent_version), mode);
editor.commit();
}
public int getInputMode() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_input_mode), INPUT_MODE_DEFAULT);
}
public void setInputMode(int aTouchMode) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_input_mode), aTouchMode);
editor.commit();
}
public String getHomepage() {
return mPrefs.getString(
mContext.getString(R.string.settings_key_homepage),
mContext.getString(R.string.homepage_url));
}
public void setHomepage(String aHomepage) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(mContext.getString(R.string.settings_key_homepage), aHomepage);
editor.commit();
}
public float getDisplayDensity() {
return mPrefs.getFloat(
mContext.getString(R.string.settings_key_display_density), DISPLAY_DENSITY_DEFAULT);
}
public void setDisplayDensity(float aDensity) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putFloat(mContext.getString(R.string.settings_key_display_density), aDensity);
editor.commit();
}
public int getWindowWidth() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_window_width), WINDOW_WIDTH_DEFAULT);
}
public void setWindowWidth(int aWindowWidth) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_window_width), aWindowWidth);
editor.commit();
}
public int getWindowHeight() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_window_height), WINDOW_HEIGHT_DEFAULT);
}
public void setWindowHeight(int aWindowHeight) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_window_height), aWindowHeight);
editor.commit();
}
public float getWindowAspect() {
return (float)getWindowWidth() / (float)getWindowHeight();
}
public int getDisplayDpi() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_display_dpi), DISPLAY_DPI_DEFAULT);
}
public void setDisplayDpi(int aDpi) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_display_dpi), aDpi);
editor.commit();
}
public int getMaxWindowWidth() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_max_window_width), MAX_WINDOW_WIDTH_DEFAULT);
}
public void setMaxWindowWidth(int aMaxWindowWidth) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_max_window_width), aMaxWindowWidth);
editor.commit();
}
public int getMaxWindowHeight() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_max_window_height), MAX_WINDOW_HEIGHT_DEFAULT);
}
public void setMaxWindowHeight(int aMaxWindowHeight) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_max_window_height), aMaxWindowHeight);
editor.commit();
}
public String getEnvironment() {
return mPrefs.getString(mContext.getString(R.string.settings_key_env), ENV_DEFAULT);
}
public void setEnvironment(String aEnv) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(mContext.getString(R.string.settings_key_env), aEnv);
editor.commit();
}
public float getBrowserWorldWidth() {
return mPrefs.getFloat(
mContext.getString(R.string.settings_key_browser_world_width), BROWSER_WORLD_WIDTH_DEFAULT);
}
public void setBrowserWorldWidth(float aBrowserWorldWidth) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putFloat(mContext.getString(R.string.settings_key_browser_world_width), aBrowserWorldWidth);
editor.commit();
}
public float getBrowserWorldHeight() {
return mPrefs.getFloat(
mContext.getString(R.string.settings_key_browser_world_height), BROWSER_WORLD_HEIGHT_DEFAULT);
}
public void setBrowserWorldHeight(float aBrowserWorldHeight) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putFloat(mContext.getString(R.string.settings_key_browser_world_height), aBrowserWorldHeight);
editor.commit();
}
public int getPointerColor() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_pointer_color), POINTER_COLOR_DEFAULT_DEFAULT);
}
public void setPointerColor(int color) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_pointer_color), color);
editor.commit();
}
public int getScrollDirection() {
if (mCachedScrollDirection < 0) {
mCachedScrollDirection = mPrefs.getInt(mContext.getString(R.string.settings_key_scroll_direction), SCROLL_DIRECTION_DEFAULT);
}
return mCachedScrollDirection;
}
public void setScrollDirection(int aScrollDirection) {
mCachedScrollDirection = aScrollDirection;
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_scroll_direction), aScrollDirection);
editor.commit();
}
public int getMSAALevel() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_msaa), MSAA_DEFAULT_LEVEL);
}
public void setMSAALevel(int level) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_msaa), level);
editor.commit();
}
public boolean getLayersEnabled() {
if (DeviceType.isOculusBuild()) {
return true;
}
return false;
}
public int getTransparentBorderWidth() {
return 1;
}
public boolean isAudioEnabled() {
return mPrefs.getBoolean(mContext.getString(R.string.settings_key_audio), AUDIO_ENABLED);
}
public void setAudioEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_audio), isEnabled);
editor.commit();
}
public String getVoiceSearchLanguage() {
String language = mPrefs.getString(
mContext.getString(R.string.settings_key_voice_search_language), null);
if (language == null) {
return LocaleUtils.getDefaultVoiceSearchLanguage(mContext);
}
return language;
}
public void setVoiceSearchLanguage(String language) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(mContext.getString(R.string.settings_key_voice_search_language), language);
editor.commit();
}
public float getCylinderDensity() {
return mPrefs.getFloat(mContext.getString(R.string.settings_key_cylinder_density), 0);
}
public void setCylinderDensity(float aDensity) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putFloat(mContext.getString(R.string.settings_key_cylinder_density), aDensity);
editor.commit();
}
public int getFoveatedLevelApp() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_foveated_app), FOVEATED_APP_DEFAULT_LEVEL);
}
public int getFoveatedLevelWebVR() {
return mPrefs.getInt(
mContext.getString(R.string.settings_key_foveated_webvr), FOVEATED_WEBVR_DEFAULT_LEVEL);
}
public void setFoveatedLevelApp(int level) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_foveated_app), level);
editor.commit();
}
public void setFoveatedLevelWebVR(int level) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(mContext.getString(R.string.settings_key_foveated_webvr), level);
editor.commit();
}
public void setSelectedKeyboard(Locale aLocale) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(mContext.getString(R.string.settings_key_keyboard_locale), aLocale.toLanguageTag());
editor.commit();
}
public Locale getKeyboardLocale() {
String value = mPrefs.getString(mContext.getString(R.string.settings_key_keyboard_locale), null);
if (StringUtils.isEmpty(value)) {
return null;
}
return Locale.forLanguageTag(value);
}
public synchronized long getCrashRestartCount() {
long count = mPrefs.getLong(mContext.getString(R.string.settings_key_crash_restart_count), 0);
if (count > 0) {
final long timestamp = mPrefs.getLong(mContext.getString(R.string.settings_key_crash_restart_count_timestamp), -1);
if (System.currentTimeMillis() - timestamp > CRASH_RESTART_DELTA) {
count = 0;
SharedPreferences.Editor editor = mPrefs.edit();
editor.putLong(mContext.getString(R.string.settings_key_crash_restart_count), count);
editor.putLong(mContext.getString(R.string.settings_key_crash_restart_count_timestamp), -1);
editor.commit();
}
}
return count;
}
public synchronized void incrementCrashRestartCount() {
SharedPreferences.Editor editor = mPrefs.edit();
long count = mPrefs.getLong(mContext.getString(R.string.settings_key_crash_restart_count), 0);
count++;
editor.putLong(mContext.getString(R.string.settings_key_crash_restart_count), count);
editor.putLong(mContext.getString(R.string.settings_key_crash_restart_count_timestamp), System.currentTimeMillis());
editor.commit();
}
public synchronized void resetCrashRestartCount() {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putLong(mContext.getString(R.string.settings_key_crash_restart_count), 0);
editor.commit();
}
public boolean isSpeechDataCollectionEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_speech_data_collection), SPEECH_DATA_COLLECTION_DEFAULT);
}
public void setSpeechDataCollectionEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_speech_data_collection), isEnabled);
editor.commit();
}
public boolean isNotificationsEnabled() {
return mPrefs.getBoolean(
mContext.getString(R.string.settings_key_notifications), NOTIFICATIONS_DEFAULT);
}
public void setNotificationsEnabled(boolean isEnabled) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mContext.getString(R.string.settings_key_notifications), isEnabled);
editor.commit();
}
}
| 1 | 7,936 | Looks like `org.json.*` can be removed? | MozillaReality-FirefoxReality | java |
@@ -890,7 +890,9 @@ public enum WidgetInfo
SECOND_TRADING_WITH_MY_ITEMS(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_MY_ITEMS),
SECOND_TRADING_WITH_THEIR_ITEMS(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_THEIR_ITEMS),
- GAUNTLET_TIMER_CONTAINER(WidgetID.GAUNTLET_TIMER_GROUP_ID, WidgetID.GauntletTimer.CONTAINER);
+ GAUNTLET_TIMER_CONTAINER(WidgetID.GAUNTLET_TIMER_GROUP_ID, WidgetID.GauntletTimer.CONTAINER),
+ GAUNTLET_MAP(WidgetID.GAUNTLET_MAP_GROUP_ID, WidgetID.GauntletMap.CONTAINER),
+ ;
private final int groupId;
private final int childId; | 1 | /*
* Copyright (c) 2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.api.widgets;
/**
* Represents a group-child {@link Widget} relationship.
* <p>
* For getting a specific widget from the client, see {@link net.runelite.api.Client#getWidget(WidgetInfo)}.
*/
public enum WidgetInfo
{
FAIRY_RING_LEFT_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.LEFT_ORB_CLOCKWISE),
FAIRY_RING_LEFT_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.LEFT_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_MIDDLE_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.MIDDLE_ORB_CLOCKWISE),
FAIRY_RING_MIDDLE_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.MIDDLE_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_RIGHT_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.RIGHT_ORB_CLOCKWISE),
FAIRY_RING_RIGHT_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.RIGHT_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_TELEPORT_BUTTON(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.TELEPORT_BUTTON),
WORLD_SWITCHER_BUTTON(WidgetID.LOGOUT_PANEL_ID, WidgetID.LogoutPanel.WORLD_SWITCHER_BUTTON),
LOGOUT_BUTTON(WidgetID.LOGOUT_PANEL_ID, WidgetID.LogoutPanel.LOGOUT_BUTTON),
INVENTORY(WidgetID.INVENTORY_GROUP_ID, 0),
FRIENDS_LIST(WidgetID.FRIENDS_LIST_GROUP_ID, 0),
IGNORE_LIST(WidgetID.IGNORE_LIST_GROUP_ID, 0),
FRIENDS_CHAT(WidgetID.FRIENDS_CHAT_GROUP_ID, 0),
RAIDING_PARTY(WidgetID.RAIDING_PARTY_GROUP_ID, 0),
WORLD_MAP_VIEW(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.MAPVIEW),
WORLD_MAP_OVERVIEW_MAP(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.OVERVIEW_MAP),
WORLD_MAP_SEARCH(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.SEARCH),
WORLD_MAP_SURFACE_SELECTOR(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.SURFACE_SELECTOR),
WORLD_MAP_TOOLTIP(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.TOOLTIP),
WORLD_MAP_OPTION(WidgetID.WORLD_MAP_MENU_GROUP_ID, WidgetID.WorldMap.OPTION),
WORLD_MAP_BUTTON_BORDER(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.WORLDMAP_ORB),
CLUE_SCROLL_TEXT(WidgetID.CLUE_SCROLL_GROUP_ID, WidgetID.Cluescroll.CLUE_TEXT),
CLUE_SCROLL_REWARD_ITEM_CONTAINER(WidgetID.CLUE_SCROLL_REWARD_GROUP_ID, WidgetID.Cluescroll.CLUE_SCROLL_ITEM_CONTAINER),
EQUIPMENT(WidgetID.EQUIPMENT_GROUP_ID, 0),
EQUIPMENT_INVENTORY_ITEMS_CONTAINER(WidgetID.EQUIPMENT_INVENTORY_GROUP_ID, WidgetID.Equipment.INVENTORY_ITEM_CONTAINER),
EQUIPMENT_HELMET(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.HELMET),
EQUIPMENT_CAPE(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.CAPE),
EQUIPMENT_AMULET(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.AMULET),
EQUIPMENT_WEAPON(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.WEAPON),
EQUIPMENT_BODY(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.BODY),
EQUIPMENT_SHIELD(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.SHIELD),
EQUIPMENT_LEGS(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.LEGS),
EQUIPMENT_GLOVES(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.GLOVES),
EQUIPMENT_BOOTS(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.BOOTS),
EQUIPMENT_RING(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.RING),
EQUIPMENT_AMMO(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.AMMO),
EMOTE_WINDOW(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_WINDOW),
EMOTE_CONTAINER(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_CONTAINER),
EMOTE_SCROLLBAR(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_SCROLLBAR),
MUSIC_WINDOW(WidgetID.MUSIC_GROUP_ID, WidgetID.Music.CONTAINER),
MUSIC_TRACK_LIST(WidgetID.MUSIC_GROUP_ID, WidgetID.Music.LIST),
MUSIC_TRACK_SCROLLBAR(WidgetID.MUSIC_GROUP_ID, WidgetID.Music.SCROLLBAR),
DIARY_QUEST_WIDGET_TITLE(WidgetID.DIARY_QUEST_GROUP_ID, WidgetID.Diary.DIARY_TITLE),
DIARY_QUEST_WIDGET_TEXT(WidgetID.DIARY_QUEST_GROUP_ID, WidgetID.Diary.DIARY_TEXT),
MINIGAME_DIALOG(WidgetID.DIALOG_MINIGAME_GROUP_ID, 0),
MINIGAME_DIALOG_TEXT(WidgetID.DIALOG_MINIGAME_GROUP_ID, WidgetID.MinigameDialog.TEXT),
PEST_CONTROL_EXCHANGE_WINDOW(WidgetID.PEST_CONTROL_EXCHANGE_WINDOW_GROUP_ID, 0),
PEST_CONTROL_EXCHANGE_WINDOW_POINTS(WidgetID.PEST_CONTROL_EXCHANGE_WINDOW_GROUP_ID, WidgetID.PestControlExchangeWindow.POINTS),
PEST_CONTROL_BOAT_INFO(WidgetID.PEST_CONTROL_BOAT_GROUP_ID, WidgetID.PestControlBoat.INFO),
PEST_CONTROL_BOAT_INFO_POINTS(WidgetID.PEST_CONTROL_BOAT_GROUP_ID, WidgetID.PestControlBoat.POINTS),
PEST_CONTROL_INFO(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.INFO),
PEST_CONTROL_INFO_TIME(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.TIME),
PEST_CONTROL_PURPLE_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_SHIELD),
PEST_CONTROL_BLUE_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_SHIELD),
PEST_CONTROL_YELLOW_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_SHIELD),
PEST_CONTROL_RED_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_SHIELD),
PEST_CONTROL_PURPLE_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_HEALTH),
PEST_CONTROL_BLUE_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_HEALTH),
PEST_CONTROL_YELLOW_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_HEALTH),
PEST_CONTROL_RED_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_HEALTH),
PEST_CONTROL_PURPLE_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_ICON),
PEST_CONTROL_BLUE_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_ICON),
PEST_CONTROL_YELLOW_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_ICON),
PEST_CONTROL_RED_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_ICON),
PEST_CONTROL_ACTIVITY_BAR(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.ACTIVITY_BAR),
PEST_CONTROL_ACTIVITY_PROGRESS(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.ACTIVITY_PROGRESS),
VOLCANIC_MINE_GENERAL_INFOBOX_GROUP(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.GENERAL_INFOBOX_GROUP_ID),
VOLCANIC_MINE_TIME_LEFT(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.TIME_LEFT),
VOLCANIC_MINE_POINTS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.POINTS),
VOLCANIC_MINE_STABILITY(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.STABILITY),
VOLCANIC_MINE_PLAYER_COUNT(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.PLAYER_COUNT),
VOLCANIC_MINE_VENTS_INFOBOX_GROUP(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENTS_INFOBOX_GROUP_ID),
VOLCANIC_MINE_VENT_A_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_A_PERCENTAGE),
VOLCANIC_MINE_VENT_B_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_B_PERCENTAGE),
VOLCANIC_MINE_VENT_C_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_C_PERCENTAGE),
VOLCANIC_MINE_VENT_A_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_A_STATUS),
VOLCANIC_MINE_VENT_B_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_B_STATUS),
VOLCANIC_MINE_VENT_C_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_C_STATUS),
FRIEND_CHAT_TITLE(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.TITLE),
FRIEND_LIST_FULL_CONTAINER(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.FULL_CONTAINER),
FRIEND_LIST_SORT_BY_NAME_BUTTON(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.SORT_BY_NAME_BUTTON),
FRIEND_LIST_SORT_BY_LAST_WORLD_CHANGE_BUTTON(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.SORT_BY_LAST_WORLD_CHANGE_BUTTON),
FRIEND_LIST_SORT_BY_WORLD_BUTTON(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.SORT_BY_WORLD_BUTTON),
FRIEND_LIST_LEGACY_SORT_BUTTON(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.LEGACY_SORT_BUTTON),
FRIEND_LIST_NAMES_CONTAINER(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.NAMES_CONTAINER),
FRIEND_LIST_SCROLL_BAR(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.SCROLL_BAR),
FRIEND_LIST_LOADING_TEXT(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.LOADING_TEXT),
FRIEND_LIST_PREVIOUS_NAME_HOLDER(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.PREVIOUS_NAME_HOLDER),
IGNORE_TITLE(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.TITLE),
IGNORE_FULL_CONTAINER(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.FULL_CONTAINER),
IGNORE_SORT_BY_NAME_BUTTON(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.SORT_BY_NAME_BUTTON),
IGNORE_LEGACY_SORT_BUTTON(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.LEGACY_SORT_BUTTON),
IGNORE_NAMES_CONTAINER(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.NAMES_CONTAINER),
IGNORE_SCROLL_BAR(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.SCROLL_BAR),
IGNORE_LOADING_TEXT(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.LOADING_TEXT),
IGNORE_PREVIOUS_NAME_HOLDER(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.PREVIOUS_NAME_HOLDER),
EXPLORERS_RING_ALCH_INVENTORY(WidgetID.EXPLORERS_RING_ALCH_GROUP_ID, WidgetID.ExplorersRing.INVENTORY),
FRIENDS_CHAT_TITLE(WidgetID.FRIENDS_CHAT_GROUP_ID, WidgetID.FriendsChat.TITLE),
FRIENDS_CHAT_NAME(WidgetID.FRIENDS_CHAT_GROUP_ID, WidgetID.FriendsChat.NAME),
FRIENDS_CHAT_OWNER(WidgetID.FRIENDS_CHAT_GROUP_ID, WidgetID.FriendsChat.OWNER),
FRIENDS_CHAT_LIST(WidgetID.FRIENDS_CHAT_GROUP_ID, WidgetID.FriendsChat.LIST),
BANK_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.BANK_CONTAINER),
BANK_SEARCH_BUTTON_BACKGROUND(WidgetID.BANK_GROUP_ID, WidgetID.Bank.SEARCH_BUTTON_BACKGROUND),
BANK_ITEM_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.ITEM_CONTAINER),
BANK_INVENTORY_ITEMS_CONTAINER(WidgetID.BANK_INVENTORY_GROUP_ID, WidgetID.Bank.INVENTORY_ITEM_CONTAINER),
BANK_TITLE_BAR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.BANK_TITLE_BAR),
BANK_INCINERATOR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.INCINERATOR),
BANK_INCINERATOR_CONFIRM(WidgetID.BANK_GROUP_ID, WidgetID.Bank.INCINERATOR_CONFIRM),
BANK_CONTENT_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.CONTENT_CONTAINER),
BANK_DEPOSIT_EQUIPMENT(WidgetID.BANK_GROUP_ID, WidgetID.Bank.DEPOSIT_EQUIPMENT),
BANK_DEPOSIT_INVENTORY(WidgetID.BANK_GROUP_ID, WidgetID.Bank.DEPOSIT_INVENTORY),
BANK_TAB_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.TAB_CONTAINER),
BANK_EQUIPMENT_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.EQUIPMENT_CONTENT_CONTAINER),
BANK_EQUIPMENT_BUTTON(WidgetID.BANK_GROUP_ID, WidgetID.Bank.EQUIPMENT_BUTTON),
BANK_ITEM_COUNT_TOP(WidgetID.BANK_GROUP_ID, WidgetID.Bank.ITEM_COUNT_TOP),
BANK_ITEM_COUNT_BAR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.ITEM_COUNT_BAR),
BANK_ITEM_COUNT_BOTTOM(WidgetID.BANK_GROUP_ID, WidgetID.Bank.ITEM_COUNT_BOTTOM),
BANK_PIN_CONTAINER(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.CONTAINER),
BANK_SETTINGS_BUTTON(WidgetID.BANK_GROUP_ID, WidgetID.Bank.SETTINGS_BUTTON),
BANK_TUTORIAL_BUTTON(WidgetID.BANK_GROUP_ID, WidgetID.Bank.TUTORIAL_BUTTON),
GRAND_EXCHANGE_WINDOW_CONTAINER(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.WINDOW_CONTAINER),
GRAND_EXCHANGE_OFFER_CONTAINER(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_CONTAINER),
GRAND_EXCHANGE_OFFER_TEXT(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_DESCRIPTION),
GRAND_EXCHANGE_OFFER_PRICE(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_PRICE),
GRAND_EXCHANGE_INVENTORY_ITEMS_CONTAINER(WidgetID.GRAND_EXCHANGE_INVENTORY_GROUP_ID, WidgetID.GrandExchangeInventory.INVENTORY_ITEM_CONTAINER),
DEPOSIT_BOX_INVENTORY_ITEMS_CONTAINER(WidgetID.DEPOSIT_BOX_GROUP_ID, WidgetID.DepositBox.INVENTORY_ITEM_CONTAINER),
SHOP_ITEMS_CONTAINER(WidgetID.SHOP_GROUP_ID, WidgetID.Shop.ITEMS_CONTAINER),
SHOP_INVENTORY_ITEMS_CONTAINER(WidgetID.SHOP_INVENTORY_GROUP_ID, WidgetID.Shop.INVENTORY_ITEM_CONTAINER),
SMITHING_INVENTORY_ITEMS_CONTAINER(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.INVENTORY_ITEM_CONTAINER),
SMITHING_ANVIL_DAGGER(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.DAGGER),
SMITHING_ANVIL_SWORD(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.SWORD),
SMITHING_ANVIL_SCIMITAR(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.SCIMITAR),
SMITHING_ANVIL_LONG_SWORD(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.LONG_SWORD),
SMITHING_ANVIL_TWO_H_SWORD(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.TWO_H_SWORD),
SMITHING_ANVIL_AXE(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.AXE),
SMITHING_ANVIL_MACE(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.MACE),
SMITHING_ANVIL_WARHAMMER(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.WARHAMMER),
SMITHING_ANVIL_BATTLE_AXE(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.BATTLE_AXE),
SMITHING_ANVIL_CLAWS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.CLAWS),
SMITHING_ANVIL_CHAIN_BODY(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.CHAIN_BODY),
SMITHING_ANVIL_PLATE_LEGS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.PLATE_LEGS),
SMITHING_ANVIL_PLATE_SKIRT(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.PLATE_SKIRT),
SMITHING_ANVIL_PLATE_BODY(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.PLATE_BODY),
SMITHING_ANVIL_NAILS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.NAILS),
SMITHING_ANVIL_MED_HELM(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.MED_HELM),
SMITHING_ANVIL_FULL_HELM(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.FULL_HELM),
SMITHING_ANVIL_SQ_SHIELD(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.SQ_SHIELD),
SMITHING_ANVIL_KITE_SHIELD(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.KITE_SHIELD),
SMITHING_ANVIL_DART_TIPS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.DART_TIPS),
SMITHING_ANVIL_ARROW_HEADS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.ARROW_HEADS),
SMITHING_ANVIL_KNIVES(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.KNIVES),
SMITHING_ANVIL_JAVELIN_HEADS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.JAVELIN_HEADS),
SMITHING_ANVIL_BOLTS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.BOLTS),
SMITHING_ANVIL_LIMBS(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.LIMBS),
SMITHING_ANVIL_EXCLUSIVE1(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.EXCLUSIVE1),
SMITHING_ANVIL_EXCLUSIVE2(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.EXCLUSIVE2),
GUIDE_PRICES_ITEMS_CONTAINER(WidgetID.GUIDE_PRICES_GROUP_ID, WidgetID.GuidePrices.ITEM_CONTAINER),
GUIDE_PRICES_INVENTORY_ITEMS_CONTAINER(WidgetID.GUIDE_PRICES_INVENTORY_GROUP_ID, WidgetID.GuidePrices.INVENTORY_ITEM_CONTAINER),
RUNE_POUCH_ITEM_CONTAINER(WidgetID.RUNE_POUCH_GROUP_ID, 0),
MINIMAP_ORBS(WidgetID.MINIMAP_GROUP_ID, 0),
MINIMAP_XP_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.XP_ORB),
MINIMAP_PRAYER_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.PRAYER_ORB),
MINIMAP_QUICK_PRAYER_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.QUICK_PRAYER_ORB),
MINIMAP_PRAYER_ORB_TEXT(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.PRAYER_ORB_TEXT),
MINIMAP_RUN_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.RUN_ORB),
MINIMAP_TOGGLE_RUN_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.TOGGLE_RUN_ORB),
MINIMAP_RUN_ORB_TEXT(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.RUN_ORB_TEXT),
MINIMAP_HEALTH_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.HEALTH_ORB),
MINIMAP_SPEC_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.SPEC_ORB),
MINIMAP_WORLDMAP_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.WORLDMAP_ORB),
MINIMAP_WORLD_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.WORLDMAP_ORB),
MINIMAP_WIKI_BANNER(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.WIKI_BANNER),
LMS_INFO(WidgetID.LMS_GROUP_ID, WidgetID.Lms.INFO),
LMS_KDA(WidgetID.LMS_INGAME_GROUP_ID, WidgetID.LmsKDA.INFO),
LOGIN_CLICK_TO_PLAY_SCREEN(WidgetID.LOGIN_CLICK_TO_PLAY_GROUP_ID, 0),
LOGIN_CLICK_TO_PLAY_SCREEN_MESSAGE_OF_THE_DAY(WidgetID.LOGIN_CLICK_TO_PLAY_GROUP_ID, WidgetID.LoginClickToPlayScreen.MESSAGE_OF_THE_DAY),
FIXED_VIEWPORT(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.Viewport.FIXED_VIEWPORT),
FIXED_VIEWPORT_ROOT_INTERFACE_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.ROOT_INTERFACE_CONTAINER),
FIXED_VIEWPORT_BANK_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.BANK_CONTAINER),
FIXED_VIEWPORT_INTERFACE_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INTERFACE_CONTAINER),
FIXED_VIEWPORT_INVENTORY_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_CONTAINER),
FIXED_VIEWPORT_COMBAT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.COMBAT_TAB),
FIXED_VIEWPORT_STATS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.STATS_TAB),
FIXED_VIEWPORT_QUESTS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.QUESTS_TAB),
FIXED_VIEWPORT_INVENTORY_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_TAB),
FIXED_VIEWPORT_EQUIPMENT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EQUIPMENT_TAB),
FIXED_VIEWPORT_PRAYER_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.PRAYER_TAB),
FIXED_VIEWPORT_MAGIC_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MAGIC_TAB),
FIXED_VIEWPORT_FRIENDS_CHAT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_CHAT_TAB),
FIXED_VIEWPORT_FRIENDS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_TAB),
FIXED_VIEWPORT_IGNORES_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.IGNORES_TAB),
FIXED_VIEWPORT_LOGOUT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.LOGOUT_TAB),
FIXED_VIEWPORT_OPTIONS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.OPTIONS_TAB),
FIXED_VIEWPORT_EMOTES_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EMOTES_TAB),
FIXED_VIEWPORT_MUSIC_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MUSIC_TAB),
FIXED_VIEWPORT_COMBAT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.COMBAT_ICON),
FIXED_VIEWPORT_STATS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.STATS_ICON),
FIXED_VIEWPORT_QUESTS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.QUESTS_ICON),
FIXED_VIEWPORT_INVENTORY_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_ICON),
FIXED_VIEWPORT_EQUIPMENT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EQUIPMENT_ICON),
FIXED_VIEWPORT_PRAYER_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.PRAYER_ICON),
FIXED_VIEWPORT_MAGIC_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MAGIC_ICON),
FIXED_VIEWPORT_FRIENDS_CHAT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_CHAT_ICON),
FIXED_VIEWPORT_FRIENDS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_ICON),
FIXED_VIEWPORT_IGNORES_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.IGNORES_ICON),
FIXED_VIEWPORT_LOGOUT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.LOGOUT_ICON),
FIXED_VIEWPORT_OPTIONS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.OPTIONS_ICON),
FIXED_VIEWPORT_EMOTES_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EMOTES_ICON),
FIXED_VIEWPORT_MUSIC_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MUSIC_ICON),
FIXED_VIEWPORT_MINIMAP(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MINIMAP),
FIXED_VIEWPORT_MINIMAP_DRAW_AREA(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MINIMAP_DRAW_AREA),
RESIZABLE_MINIMAP_WIDGET(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_WIDGET),
RESIZABLE_MINIMAP_DRAW_AREA(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DRAW_AREA),
RESIZABLE_MINIMAP_ORB_HOLDER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_ORB_HOLDER),
RESIZABLE_MINIMAP_LOGOUT_BUTTON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_LOGOUT_BUTTON),
RESIZABLE_MINIMAP_STONES_WIDGET(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_WIDGET),
RESIZABLE_MINIMAP_STONES_DRAW_AREA(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DRAW_AREA),
RESIZABLE_MINIMAP_STONES_ORB_HOLDER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_ORB_HOLDER),
RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX),
RESIZABLE_VIEWPORT_COMBAT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.COMBAT_TAB),
RESIZABLE_VIEWPORT_STATS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.STATS_TAB),
RESIZABLE_VIEWPORT_QUESTS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.QUESTS_TAB),
RESIZABLE_VIEWPORT_INVENTORY_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_TAB),
RESIZABLE_VIEWPORT_EQUIPMENT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EQUIPMENT_TAB),
RESIZABLE_VIEWPORT_PRAYER_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.PRAYER_TAB),
RESIZABLE_VIEWPORT_MAGIC_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MAGIC_TAB),
RESIZABLE_VIEWPORT_FRIENDS_CHAT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_CHAT_TAB),
RESIZABLE_VIEWPORT_FRIENDS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_TAB),
RESIZABLE_VIEWPORT_IGNORES_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.IGNORES_TAB),
RESIZABLE_VIEWPORT_LOGOUT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.LOGOUT_TAB),
RESIZABLE_VIEWPORT_OPTIONS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.OPTIONS_TAB),
RESIZABLE_VIEWPORT_EMOTES_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EMOTES_TAB),
RESIZABLE_VIEWPORT_MUSIC_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MUSIC_TAB),
RESIZABLE_VIEWPORT_COMBAT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.COMBAT_ICON),
RESIZABLE_VIEWPORT_STATS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.STATS_ICON),
RESIZABLE_VIEWPORT_QUESTS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.QUESTS_ICON),
RESIZABLE_VIEWPORT_INVENTORY_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_ICON),
RESIZABLE_VIEWPORT_EQUIPMENT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EQUIPMENT_ICON),
RESIZABLE_VIEWPORT_PRAYER_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.PRAYER_ICON),
RESIZABLE_VIEWPORT_MAGIC_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MAGIC_ICON),
RESIZABLE_VIEWPORT_FRIENDS_CHAT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_CHAT_ICON),
RESIZABLE_VIEWPORT_FRIENDS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_ICON),
RESIZABLE_VIEWPORT_IGNORES_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.IGNORES_ICON),
RESIZABLE_VIEWPORT_LOGOUT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.LOGOUT_ICON),
RESIZABLE_VIEWPORT_OPTIONS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.OPTIONS_ICON),
RESIZABLE_VIEWPORT_EMOTES_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EMOTES_ICON),
RESIZABLE_VIEWPORT_MUSIC_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MUSIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.RESIZABLE_VIEWPORT_BOTTOM_LINE),
RESIZABLE_VIEWPORT_BOTTOM_LINE_LOGOUT_BUTTON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.LOGOUT_BUTTON_OVERLAY),
RESIZABLE_VIEWPORT_BOTTOM_LINE_QUESTS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.QUESTS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_PRAYER_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.PRAYER_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_PRAYER_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.PRAYER_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_EQUIPMENT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.EQUIP_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_COMBAT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.CMB_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_STATS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SKILLS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MAGIC_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SPELL_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MAGIC_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.MAGIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_FRIEND_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.FRIEND_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_FRIEND_CHAT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.FC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_OPTIONS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SETTINGS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_EMOTES_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.EMOTE_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MUSIC_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.MUSIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_CONTAINER),
RESIZABLE_VIEWPORT_INTERFACE_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INTERFACE_CONTAINER),
RESIZABLE_VIEWPORT_INVENTORY_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_CONTAINER),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INTERFACE_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewport.INTERFACE_CONTAINER),
PRAYER_THICK_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.THICK_SKIN),
PRAYER_BURST_OF_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.BURST_OF_STRENGTH),
PRAYER_CLARITY_OF_THOUGHT(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.CLARITY_OF_THOUGHT),
PRAYER_SHARP_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SHARP_EYE),
PRAYER_MYSTIC_WILL(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_WILL),
PRAYER_ROCK_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.ROCK_SKIN),
PRAYER_SUPERHUMAN_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SUPERHUMAN_STRENGTH),
PRAYER_IMPROVED_REFLEXES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.IMPROVED_REFLEXES),
PRAYER_RAPID_RESTORE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RAPID_RESTORE),
PRAYER_RAPID_HEAL(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RAPID_HEAL),
PRAYER_PROTECT_ITEM(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_ITEM),
PRAYER_HAWK_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.HAWK_EYE),
PRAYER_MYSTIC_LORE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_LORE),
PRAYER_STEEL_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.STEEL_SKIN),
PRAYER_ULTIMATE_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.ULTIMATE_STRENGTH),
PRAYER_INCREDIBLE_REFLEXES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.INCREDIBLE_REFLEXES),
PRAYER_PROTECT_FROM_MAGIC(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MAGIC),
PRAYER_PROTECT_FROM_MISSILES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MISSILES),
PRAYER_PROTECT_FROM_MELEE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MELEE),
PRAYER_EAGLE_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.EAGLE_EYE),
PRAYER_MYSTIC_MIGHT(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_MIGHT),
PRAYER_RETRIBUTION(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RETRIBUTION),
PRAYER_REDEMPTION(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.REDEMPTION),
PRAYER_SMITE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SMITE),
PRAYER_PRESERVE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PRESERVE),
PRAYER_CHIVALRY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.CHIVALRY),
PRAYER_PIETY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PIETY),
PRAYER_RIGOUR(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RIGOUR),
PRAYER_AUGURY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.AUGURY),
QUICK_PRAYER_PRAYERS(WidgetID.QUICK_PRAYERS_GROUP_ID, WidgetID.QuickPrayer.PRAYERS),
COMBAT_LEVEL(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.LEVEL),
COMBAT_WEAPON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.WEAPON_NAME),
COMBAT_STYLE_ONE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_ONE),
COMBAT_STYLE_TWO(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_TWO),
COMBAT_STYLE_THREE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_THREE),
COMBAT_STYLE_FOUR(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_FOUR),
COMBAT_SPELLS(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELLS),
COMBAT_DEFENSIVE_SPELL_BOX(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_BOX),
COMBAT_DEFENSIVE_SPELL_ICON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_ICON),
COMBAT_DEFENSIVE_SPELL_SHIELD(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_SHIELD),
COMBAT_DEFENSIVE_SPELL_TEXT(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_TEXT),
COMBAT_SPELL_BOX(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_BOX),
COMBAT_SPELL_ICON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_ICON),
COMBAT_SPELL_TEXT(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_TEXT),
COMBAT_AUTO_RETALIATE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.AUTO_RETALIATE),
COMBAT_SPECIAL_ATTACK(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPECIAL_ATTACK_BAR),
COMBAT_TOOLTIP(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.TOOLTIP),
DIALOG_OPTION(WidgetID.DIALOG_OPTION_GROUP_ID, 0),
MULTI_SKILL_MENU(WidgetID.MULTISKILL_MENU_GROUP_ID, 0),
DIALOG_SPRITE(WidgetID.DIALOG_SPRITE_GROUP_ID, 0),
DIALOG_SPRITE_SPRITE(WidgetID.DIALOG_SPRITE_GROUP_ID, WidgetID.DialogSprite.SPRITE),
DIALOG_SPRITE_TEXT(WidgetID.DIALOG_SPRITE_GROUP_ID, WidgetID.DialogSprite.TEXT),
DIALOG2_SPRITE(WidgetID.DIALOG_SPRITE2_ID, 0),
DIALOG2_SPRITE_SPRITE1(WidgetID.DIALOG_SPRITE2_ID, WidgetID.DialogSprite2.SPRITE1),
DIALOG2_SPRITE_SPRITE2(WidgetID.DIALOG_SPRITE2_ID, WidgetID.DialogSprite2.SPRITE2),
DIALOG2_SPRITE_TEXT(WidgetID.DIALOG_SPRITE2_ID, WidgetID.DialogSprite2.TEXT),
DIALOG2_SPRITE_CONTINUE(WidgetID.DIALOG_SPRITE2_ID, WidgetID.DialogSprite2.CONTINUE),
DIALOG_NPC(WidgetID.DIALOG_NPC_GROUP_ID, 0),
DIALOG_NPC_NAME(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.NAME),
DIALOG_NPC_TEXT(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.TEXT),
DIALOG_NPC_HEAD_MODEL(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.HEAD_MODEL),
DIALOG_NPC_CONTINUE(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.CONTINUE),
DIALOG_PLAYER_NAME(WidgetID.DIALOG_PLAYER_GROUP_ID, WidgetID.DialogPlayer.NAME),
DIALOG_PLAYER_TEXT(WidgetID.DIALOG_PLAYER_GROUP_ID, WidgetID.DialogPlayer.TEXT),
DIALOG_PLAYER_HEAD_MODEL(WidgetID.DIALOG_PLAYER_GROUP_ID, WidgetID.DialogPlayer.HEAD_MODEL),
DIALOG_PLAYER_CONTINUE(WidgetID.DIALOG_PLAYER_GROUP_ID, WidgetID.DialogPlayer.CONTINUE),
DIALOG_NOTIFICATION_TEXT(WidgetID.DIALOG_NOTIFICATION_GROUP_ID, WidgetID.DialogNotification.TEXT),
DIALOG_NOTIFICATION_CONTINUE(WidgetID.DIALOG_NOTIFICATION_GROUP_ID, WidgetID.DialogNotification.CONTINUE),
DIALOG_OPTION_TEXT(WidgetID.DIALOG_OPTION_GROUP_ID, WidgetID.DialogOption.TEXT),
DIALOG_OPTION_OPTION1(WidgetID.DIALOG_OPTION_GROUP_ID, WidgetID.DialogOption.OPTION1),
DIALOG_OPTION_OPTION2(WidgetID.DIALOG_OPTION_GROUP_ID, WidgetID.DialogOption.OPTION2),
DIALOG_OPTION_OPTION3(WidgetID.DIALOG_OPTION_GROUP_ID, WidgetID.DialogOption.OPTION3),
DIALOG_OPTION_OPTION4(WidgetID.DIALOG_OPTION_GROUP_ID, WidgetID.DialogOption.OPTION4),
DIALOG_OPTION_OPTION5(WidgetID.DIALOG_OPTION_GROUP_ID, WidgetID.DialogOption.OPTION5),
DIALOG_PLAYER(WidgetID.DIALOG_PLAYER_GROUP_ID, 0),
PRIVATE_CHAT_MESSAGE(WidgetID.PRIVATE_CHAT, 0),
SLAYER_REWARDS_TOPBAR(WidgetID.SLAYER_REWARDS_GROUP_ID, WidgetID.SlayerRewards.TOP_BAR),
CHATBOX_PARENT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.PARENT),
CHATBOX(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FRAME),
CHATBOX_MESSAGES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.MESSAGES),
CHATBOX_BUTTONS(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.BUTTONS),
CHATBOX_TITLE(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TITLE),
CHATBOX_FULL_INPUT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FULL_INPUT),
CHATBOX_GE_SEARCH_RESULTS(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.GE_SEARCH_RESULTS),
CHATBOX_CONTAINER(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.CONTAINER),
CHATBOX_REPORT_TEXT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.REPORT_TEXT),
CHATBOX_INPUT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.INPUT),
CHATBOX_TRANSPARENT_BACKGROUND(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TRANSPARENT_BACKGROUND),
CHATBOX_TRANSPARENT_LINES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TRANSPARENT_BACKGROUND_LINES),
CHATBOX_MESSAGE_LINES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.MESSAGE_LINES),
CHATBOX_FIRST_MESSAGE(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FIRST_MESSAGE),
CHATBOX_TAB_ALL(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TAB_ALL),
CHATBOX_TAB_GAME(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TAB_GAME),
CHATBOX_TAB_PUBLIC(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TAB_PUBLIC),
CHATBOX_TAB_PRIVATE(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TAB_PRIVATE),
CHATBOX_TAB_CLAN(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TAB_CLAN),
CHATBOX_TAB_TRADE(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TAB_TRADE),
BA_HEAL_WAVE_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_HEAL_CALL_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_HEAL_LISTEN_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.LISTEN),
BA_HEAL_HORN_LISTEN_TEXT(WidgetID.BA_HORN_OF_GLORY, WidgetID.BarbarianAssault.HORN_GLORY.HEALER),
BA_HEAL_ROLE_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_HEAL_ROLE_SPRITE(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_HEAL_TEAMMATE1(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.HLR.TEAMMATE1),
BA_HEAL_TEAMMATE2(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.HLR.TEAMMATE2),
BA_HEAL_TEAMMATE3(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.HLR.TEAMMATE3),
BA_HEAL_TEAMMATE4(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.HLR.TEAMMATE4),
BA_COLL_WAVE_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_COLL_CALL_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_COLL_LISTEN_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.LISTEN),
BA_COLL_HORN_LISTEN_TEXT(WidgetID.BA_HORN_OF_GLORY, WidgetID.BarbarianAssault.HORN_GLORY.COLLECTOR),
BA_COLL_ROLE_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_COLL_ROLE_SPRITE(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_ATK_WAVE_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_ATK_CALL_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.TO_CALL),
BA_ATK_LISTEN_TOP_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.LISTEN_TOP),
BA_ATK_LISTEN_BOTTOM_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.LISTEN_BOTTOM),
BA_ATK_HORN_LISTEN_TEXT(WidgetID.BA_HORN_OF_GLORY, WidgetID.BarbarianAssault.HORN_GLORY.ATTACKER),
BA_ATK_ROLE_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.ROLE),
BA_ATK_ROLE_SPRITE(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.ROLE_SPRITE),
BA_DEF_WAVE_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_DEF_CALL_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_DEF_LISTEN_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.LISTEN),
BA_DEF_HORN_LISTEN_TEXT(WidgetID.BA_HORN_OF_GLORY, WidgetID.BarbarianAssault.HORN_GLORY.DEFENDER),
BA_DEF_ROLE_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_DEF_ROLE_SPRITE(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_REWARD_TEXT(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_TEXT),
BA_RUNNERS_PASSED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.RUNNERS_PASSED),
BA_HITPOINTS_REPLENISHED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.HITPOINTS_REPLENISHED),
BA_WRONG_POISON_PACKS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.WRONG_POISON_PACKS_USED),
BA_EGGS_COLLECTED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.EGGS_COLLECTED),
BA_FAILED_ATTACKER_ATTACKS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.FAILED_ATTACKER_ATTACKS),
BA_RUNNERS_PASSED_POINTS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.RUNNERS_PASSED_POINTS),
BA_RANGERS_KILLED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.RANGERS_KILLED),
BA_FIGHTERS_KILLED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.FIGHTERS_KILLED),
BA_HEALERS_KILLED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.HEALERS_KILLED),
BA_RUNNERS_KILLED(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.RUNNERS_KILLED),
BA_HITPOINTS_REPLENISHED_POINTS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.HITPOINTS_REPLENISHED_POINTS),
BA_WRONG_POISON_PACKS_POINTS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.WRONG_POISON_PACKS_USED_POINTS),
BA_EGGS_COLLECTED_POINTS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.EGGS_COLLECTED_POINTS),
BA_FAILED_ATTACKER_ATTACKS_POINTS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.FAILED_ATTACKER_ATTACKS_POINTS),
BA_HONOUR_POINTS_REWARD(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.HONOUR_POINTS_REWARD),
BA_BASE_POINTS(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_VALUES.BASE_POINTS),
LEVEL_UP(WidgetID.LEVEL_UP_GROUP_ID, 0),
LEVEL_UP_SKILL(WidgetID.LEVEL_UP_GROUP_ID, WidgetID.LevelUp.SKILL),
LEVEL_UP_LEVEL(WidgetID.LEVEL_UP_GROUP_ID, WidgetID.LevelUp.LEVEL),
QUEST_COMPLETED(WidgetID.QUEST_COMPLETED_GROUP_ID, 0),
QUEST_COMPLETED_NAME_TEXT(WidgetID.QUEST_COMPLETED_GROUP_ID, WidgetID.QuestCompleted.NAME_TEXT),
MOTHERLODE_MINE(WidgetID.MOTHERLODE_MINE_GROUP_ID, 0),
THEATRE_OF_BLOOD_PARTY(WidgetID.THEATRE_OF_BLOOD_PARTY_GROUP_ID, WidgetID.TheatreOfBloodParty.CONTAINER),
GWD_KC(WidgetID.GWD_KC_GROUP_ID, WidgetID.GWD.CONTAINER),
PUZZLE_BOX(WidgetID.PUZZLE_BOX_GROUP_ID, WidgetID.PuzzleBox.VISIBLE_BOX),
LIGHT_BOX(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX),
LIGHT_BOX_CONTENTS(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BULB_CONTAINER),
LIGHT_BOX_BUTTON_CONTAINER(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX_BUTTON_CONTAINER),
LIGHT_BOX_BUTTON_A(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_A),
LIGHT_BOX_BUTTON_B(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_B),
LIGHT_BOX_BUTTON_C(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_C),
LIGHT_BOX_BUTTON_D(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_D),
LIGHT_BOX_BUTTON_E(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_E),
LIGHT_BOX_BUTTON_F(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_F),
LIGHT_BOX_BUTTON_G(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_G),
LIGHT_BOX_BUTTON_H(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_H),
LIGHT_BOX_WINDOW(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX_WINDOW),
NIGHTMARE_ZONE(WidgetID.NIGHTMARE_ZONE_GROUP_ID, 0),
RAIDS_POINTS_INFOBOX(WidgetID.RAIDS_GROUP_ID, WidgetID.Raids.POINTS_INFOBOX),
THEATRE_OF_BLOOD_HEALTH_ORBS(WidgetID.THEATRE_OF_BLOOD_GROUP_ID, WidgetID.TheatreOfBlood.ORB_BOX),
THEATRE_OF_BLOOD_BOSS_HEALTH(WidgetID.THEATRE_OF_BLOOD_GROUP_ID, WidgetID.TheatreOfBlood.BOSS_HEALTH_BAR),
THEATRE_OF_BLOOD_RAIDING_PARTY(WidgetID.THEATRE_OF_BLOOD_GROUP_ID, WidgetID.TheatreOfBlood.RAIDING_PARTY),
TOB_PARTY_INTERFACE(WidgetID.TOB_PARTY_GROUP_ID, WidgetID.Tob.PARTY_INTERFACE),
TOB_PARTY_STATS(WidgetID.TOB_PARTY_GROUP_ID, WidgetID.Tob.PARTY_STATS),
BLAST_FURNACE_COFFER(WidgetID.BLAST_FURNACE_GROUP_ID, 2),
PYRAMID_PLUNDER_DATA(WidgetID.PYRAMID_PLUNDER_GROUP_ID, 2),
EXPERIENCE_TRACKER(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, 0),
EXPERIENCE_TRACKER_WIDGET(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, WidgetID.ExperienceTracker.WIDGET),
EXPERIENCE_TRACKER_BOTTOM_BAR(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, WidgetID.ExperienceTracker.BOTTOM_BAR),
FISHING_TRAWLER_TIMER(WidgetID.FISHING_TRAWLER_GROUP_ID, 14),
TITHE_FARM(WidgetID.TITHE_FARM_GROUP_ID, 3),
BARROWS_INFO(WidgetID.BARROWS_GROUP_ID, 0),
BARROWS_BROTHERS(WidgetID.BARROWS_GROUP_ID, WidgetID.Barrows.BARROWS_BROTHERS),
BARROWS_POTENTIAL(WidgetID.BARROWS_GROUP_ID, WidgetID.Barrows.BARROWS_POTENTIAL),
BARROWS_REWARD_INVENTORY(WidgetID.BARROWS_REWARD_GROUP_ID, WidgetID.Barrows.BARROWS_REWARD_INVENTORY),
BARROWS_PUZZLE_PARENT(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.PARENT),
BARROWS_PUZZLE_ANSWER1(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.ANSWER1),
BARROWS_PUZZLE_ANSWER1_CONTAINER(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.ANSWER1_CONTAINER),
BARROWS_PUZZLE_ANSWER2(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.ANSWER2),
BARROWS_PUZZLE_ANSWER2_CONTAINER(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.ANSWER2_CONTAINER),
BARROWS_PUZZLE_ANSWER3(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.ANSWER3),
BARROWS_PUZZLE_ANSWER3_CONTAINER(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.ANSWER3_CONTAINER),
BARROWS_FIRST_PUZZLE(WidgetID.BARROWS_PUZZLE_GROUP_ID, WidgetID.Barrows_Puzzle.SEQUENCE_1),
BLAST_MINE(WidgetID.BLAST_MINE_GROUP_ID, 2),
FAIRY_RING(WidgetID.FAIRY_RING_GROUP_ID, 0),
FAIRY_RING_HEADER(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.HEADER),
FAIRY_RING_LIST(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.LIST),
FAIRY_RING_FAVORITES(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.FAVORITES),
FAIRY_RING_LIST_SEPARATOR(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.SEPARATOR),
FAIRY_RING_LIST_SCROLLBAR(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.SCROLLBAR),
DESTROY_ITEM(WidgetID.DESTROY_ITEM_GROUP_ID, 0),
DESTROY_ITEM_NAME(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_NAME),
DESTROY_ITEM_YES(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_YES),
DESTROY_ITEM_NO(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_NO),
VARROCK_MUSEUM_QUESTION(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_QUESTION),
VARROCK_MUSEUM_FIRST_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_FIRST_ANSWER),
VARROCK_MUSEUM_SECOND_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_SECOND_ANSWER),
VARROCK_MUSEUM_THIRD_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_THIRD_ANSWER),
KILL_LOG_TITLE(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.TITLE),
KILL_LOG_MONSTER(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.MONSTER),
KILL_LOG_KILLS(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.KILLS),
KILL_LOG_STREAK(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.STREAK),
ADVENTURE_LOG(WidgetID.ADVENTURE_LOG_ID, WidgetID.AdventureLog.CONTAINER),
GENERIC_SCROLL_TEXT(WidgetID.GENERIC_SCROLL_GROUP_ID, WidgetID.GenericScroll.TEXT),
WORLD_SWITCHER_LIST(WidgetID.WORLD_SWITCHER_GROUP_ID, WidgetID.WorldSwitcher.WORLD_LIST),
FOSSIL_ISLAND_OXYGENBAR(WidgetID.FOSSIL_ISLAND_OXYGENBAR_ID, WidgetID.FossilOxygen.FOSSIL_ISLAND_OXYGEN_BAR),
FOSSIL_MUSHROOM_TELEPORT(WidgetID.FOSSIL_ISLAND_MUSHROOM_TELE_GROUP_ID, WidgetID.FossilMushroomTeleport.ROOT),
FOSSIL_MUSHROOM_HOUSE(WidgetID.FOSSIL_ISLAND_MUSHROOM_TELE_GROUP_ID, WidgetID.FossilMushroomTeleport.HOUSE_ON_HILL),
FOSSIL_MUSHROOM_VALLEY(WidgetID.FOSSIL_ISLAND_MUSHROOM_TELE_GROUP_ID, WidgetID.FossilMushroomTeleport.VERDANT_VALLEY),
FOSSIL_MUSHROOM_SWAMP(WidgetID.FOSSIL_ISLAND_MUSHROOM_TELE_GROUP_ID, WidgetID.FossilMushroomTeleport.SWAMP),
FOSSIL_MUSHROOM_MEADOW(WidgetID.FOSSIL_ISLAND_MUSHROOM_TELE_GROUP_ID, WidgetID.FossilMushroomTeleport.MUSHROOM_MEADOW),
MINIGAME_TELEPORT_BUTTON(WidgetID.MINIGAME_TAB_ID, WidgetID.Minigames.TELEPORT_BUTTON),
PVP_FOG_OVERLAY(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.FOG_OVERLAY),
PVP_CONTAINER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.PVP_WIDGET_CONTAINER),
PVP_SKULL_CONTAINER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SKULL_CONTAINER),
PVP_SKULL(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SKULL),
PVP_ATTACK_RANGE(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.ATTACK_RANGE),
PVP_WORLD_SAFE_ZONE(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SAFE_ZONE),
PVP_WILDERNESS_LEVEL(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.WILDERNESS_LEVEL),
PVP_BOUNTY_HUNTER_INFO(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.BOUNTY_HUNTER_INFO),
PVP_KILLDEATH_COUNTER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.KILLDEATH_RATIO),
SPELLBOOK(WidgetID.SPELLBOOK_GROUP_ID, 0),
SPELLBOOK_FILTERED_BOUNDS(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FILTERED_SPELLS_BOUNDS),
/* STANDARD SPELL BOOK WIDGETS*/
SPELL_LUMBRIDGE_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LUMBRIDGE_HOME_TELEPORT),
SPELL_WIND_STRIKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WIND_STRIKE),
SPELL_CONFUSE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CONFUSE),
SPELL_ENCHANT_CROSSBOW_BOLT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ENCHANT_CROSSBOW_BOLT),
SPELL_WATER_STRIKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATER_STRIKE),
SPELL_LVL_1_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_1_ENCHANT),
SPELL_EARTH_STRIKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.EARTH_STRIKE),
SPELL_WEAKEN(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WEAKEN),
SPELL_FIRE_STRIKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FIRE_STRIKE),
SPELL_BONES_TO_BANANAS(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BONES_TO_BANANAS),
SPELL_WIND_BOLT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WIND_BOLT),
SPELL_CURSE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CURSE),
SPELL_BIND(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BIND),
SPELL_LOW_LEVEL_ALCHEMY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LOW_LEVEL_ALCHEMY),
SPELL_WATER_BOLT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATER_BOLT),
SPELL_VARROCK_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.VARROCK_TELEPORT),
SPELL_LVL_2_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_2_ENCHANT),
SPELL_EARTH_BOLT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.EARTH_BOLT),
SPELL_LUMBRIDGE_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LUMBRIDGE_TELEPORT),
SPELL_TELEKINETIC_GRAB(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEKINETIC_GRAB),
SPELL_FIRE_BOLT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FIRE_BOLT),
SPELL_FALADOR_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FALADOR_TELEPORT),
SPELL_CRUMBLE_UNDEAD(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CRUMBLE_UNDEAD),
SPELL_TELEPORT_TO_HOUSE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEPORT_TO_HOUSE),
SPELL_WIND_BLAST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WIND_BLAST),
SPELL_SUPERHEAT_ITEM(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SUPERHEAT_ITEM),
SPELL_CAMELOT_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CAMELOT_TELEPORT),
SPELL_WATER_BLAST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATER_BLAST),
SPELL_LVL_3_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_3_ENCHANT),
SPELL_IBAN_BLAST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.IBAN_BLAST),
SPELL_SNARE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SNARE),
SPELL_MAGIC_DART(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.MAGIC_DART),
SPELL_ARDOUGNE_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ARDOUGNE_TELEPORT),
SPELL_EARTH_BLAST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.EARTH_BLAST),
SPELL_HIGH_LEVEL_ALCHEMY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.HIGH_LEVEL_ALCHEMY),
SPELL_CHARGE_WATER_ORB(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CHARGE_WATER_ORB),
SPELL_LVL_4_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_4_ENCHANT),
SPELL_WATCHTOWER_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATCHTOWER_TELEPORT),
SPELL_FIRE_BLAST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FIRE_BLAST),
SPELL_CHARGE_EARTH_ORB(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CHARGE_EARTH_ORB),
SPELL_BONES_TO_PEACHES(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BONES_TO_PEACHES),
SPELL_SARADOMIN_STRIKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SARADOMIN_STRIKE),
SPELL_CLAWS_OF_GUTHIX(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CLAWS_OF_GUTHIX),
SPELL_FLAMES_OF_ZAMORAK(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FLAMES_OF_ZAMORAK),
SPELL_TROLLHEIM_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TROLLHEIM_TELEPORT),
SPELL_WIND_WAVE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WIND_WAVE),
SPELL_CHARGE_FIRE_ORB(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CHARGE_FIRE_ORB),
SPELL_TELEPORT_TO_APE_ATOLL(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEPORT_TO_APE_ATOLL),
SPELL_WATER_WAVE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATER_WAVE),
SPELL_CHARGE_AIR_ORB(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CHARGE_AIR_ORB),
SPELL_VULNERABILITY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.VULNERABILITY),
SPELL_LVL_5_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_5_ENCHANT),
SPELL_TELEPORT_TO_KOUREND(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEPORT_TO_KOUREND),
SPELL_EARTH_WAVE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.EARTH_WAVE),
SPELL_ENFEEBLE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ENFEEBLE),
SPELL_FIRE_WAVE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FIRE_WAVE),
SPELL_ENTANGLE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ENTANGLE),
SPELL_TELEOTHER_LUMBRIDGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEOTHER_LUMBRIDGE),
SPELL_STUN(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.STUN),
SPELL_CHARGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CHARGE),
SPELL_WIND_SURGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WIND_SURGE),
SPELL_TELEOTHER_FALADOR(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEOTHER_FALADOR),
SPELL_WATER_SURGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATER_SURGE),
SPELL_TELE_BLOCK(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_BLOCK),
SPELL_LVL_6_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_6_ENCHANT),
SPELL_TELEOTHER_CAMELOT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELEOTHER_CAMELOT),
SPELL_EARTH_SURGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.EARTH_SURGE),
SPELL_LVL_7_ENCHANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LVL_7_ENCHANT),
SPELL_FIRE_SURGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FIRE_SURGE),
SPELL_BOUNTY_TARGET_TELEPORT2(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BOUNTY_TARGET_TELEPORT),
/* END OF STANDARD SPELL BOOK WIDGETS*/
/* ANCIENT SPELL BOOK WIDGETS*/
SPELL_ICE_RUSH(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ICE_RUSH),
SPELL_ICE_BLITZ(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ICE_BLITZ),
SPELL_ICE_BURST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ICE_BURST),
SPELL_ICE_BARRAGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ICE_BARRAGE),
SPELL_BLOOD_RUSH(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BLOOD_RUSH),
SPELL_BLOOD_BLITZ(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BLOOD_BLITZ),
SPELL_BLOOD_BURST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BLOOD_BURST),
SPELL_BLOOD_BARRAGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BLOOD_BARRAGE),
SPELL_SMOKE_RUSH(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SMOKE_RUSH),
SPELL_SMOKE_BLITZ(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SMOKE_BLITZ),
SPELL_SMOKE_BURST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SMOKE_BURST),
SPELL_SMOKE_BARRAGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SMOKE_BARRAGE),
SPELL_SHADOW_RUSH(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SHADOW_RUSH),
SPELL_SHADOW_BLITZ(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SHADOW_BLITZ),
SPELL_SHADOW_BURST(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SHADOW_BURST),
SPELL_SHADOW_BARRAGE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SHADOW_BARRAGE),
SPELL_PADDEWWA_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.PADDEWWA_TELEPORT),
SPELL_SENNTISTEN_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SENNTISTEN_TELEPORT),
SPELL_KHARYRLL_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.KHARYRLL_TELEPORT),
SPELL_LASSAR_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LASSAR_TELEPORT),
SPELL_DAREEYAK_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.DAREEYAK_TELEPORT),
SPELL_CARRALLANGER_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CARRALLANGER_TELEPORT),
SPELL_ANNAKARL_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ANNAKARL_TELEPORT),
SPELL_GHORROCK_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.GHORROCK_TELEPORT),
SPELL_EDGEVILLE_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.EDGEVILLE_HOME_TELEPORT),
SPELL_BOUNTY_TARGET_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BOUNTY_TARGET_TELEPORT),
/* END OF ANCIENT SPELL BOOK WIDGETS*/
/* LUNAR SPELL BOOK WIDGETS*/
SPELL_LUNAR_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.LUNAR_HOME_TELEPORT),
SPELL_VENGEANCE_OTHER(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.VENGEANCE_OTHER),
SPELL_VENGEANCE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.VENGEANCE),
SPELL_BOUNTY_TARGET_TELEPORT3(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BOUNTY_TARGET_TELEPORT),
SPELL_BAKE_PIE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BAKE_PIE),
SPELL_CURE_PLANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CURE_PLANT),
SPELL_MONSTER_EXAMINE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.MONSTER_EXAMINE),
SPELL_NPC_CONTACT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.NPC_CONTACT),
SPELL_CURE_OTHER(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CURE_OTHER),
SPELL_HUMIDIFY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.HUMIDIFY),
SPELL_MOONCLAN_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.MOONCLAN_TELEPORT),
SPELL_TELE_GROUP_MOONCLAN(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_MOONCLAN),
SPELL_CURE_ME(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CURE_ME),
SPELL_HUNTER_KIT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.HUNTER_KIT),
SPELL_WATERBIRTH_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.WATERBIRTH_TELEPORT),
SPELL_TELE_GROUP_WATERBIRTH(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_WATERBIRTH),
SPELL_CURE_GROUP(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CURE_GROUP),
SPELL_STAT_SPY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.STAT_SPY),
SPELL_BARBARIAN_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BARBARIAN_TELEPORT),
SPELL_TELE_GROUP_BARBARIAN(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_BARBARIAN),
SPELL_SUPERGLASS_MAKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SUPERGLASS_MAKE),
SPELL_TAN_LEATHER(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TAN_LEATHER),
SPELL_KHAZARD_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.KHAZARD_TELEPORT),
SPELL_TELE_GROUP_KHAZARD(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_KHAZARD),
SPELL_DREAM(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.DREAM),
SPELL_STRING_JEWELLERY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.STRING_JEWELLERY),
SPELL_STAT_RESTORE_POT_SHARE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.STAT_RESTORE_POT_SHARE),
SPELL_MAGIC_IMBUE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.MAGIC_IMBUE),
SPELL_FERTILE_SOIL(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FERTILE_SOIL),
SPELL_BOOST_POTION_SHARE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BOOST_POTION_SHARE),
SPELL_FISHING_GUILD_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.FISHING_GUILD_TELEPORT),
SPELL_TELE_GROUP_FISHING_GUILD(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_FISHING_GUILD),
SPELL_PLANK_MAKE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.PLANK_MAKE),
SPELL_CATHERBY_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.CATHERBY_TELEPORT),
SPELL_TELE_GROUP_CATHERBY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_CATHERBY),
SPELL_RECHARGE_DRAGONSTONE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.RECHARGE_DRAGONSTONE),
SPELL_ICE_PLATEAU_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ICE_PLATEAU_TELEPORT),
SPELL_TELE_GROUP_ICE_PLATEAU(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TELE_GROUP_ICE_PLATEAU),
SPELL_ENERGY_TRANSFER(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ENERGY_TRANSFER),
SPELL_HEAL_OTHER(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.HEAL_OTHER),
SPELL_HEAL_GROUP(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.HEAL_GROUP),
SPELL_SPELLBOOK_SWAP(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SPELLBOOK_SWAP),
SPELL_GEOMANCY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.GEOMANCY),
SPELL_SPIN_FLAX(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.SPIN_FLAX),
SPELL_OURANIA_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.OURANIA_TELEPORT),
/* END OF LUNAR SPELL BOOK WIDGETS*/
SPELL_TOOLTIP(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.TOOLTIP),
/* ARCEUUS SPELL BOOK WIDGETS*/
SPELL_KOUREND_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.StandardSpellBook.KOUREND_HOME_TELEPORT),
SPELL_ARCEUUS_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.ARCEUUS_HOME_TELEPORT),
SPELL_BATTLEFRONT_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.BATTLEFRONT_TELEPORT),
SPELL_REANIMATE_GOBLIN(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_GOBLIN),
SPELL_REANIMATE_MONKEY(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_MONKEY),
SPELL_REANIMATE_IMP(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_IMP),
SPELL_REANIMATE_MINOTAUR(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_MINOTAUR),
SPELL_REANIMATE_SCORPION(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_SCORPION),
SPELL_REANIMATE_BEAR(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_BEAR),
SPELL_REANIMATE_UNICORN(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_UNICORN),
SPELL_REANIMATE_DOG(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_DOG),
SPELL_REANIMATE_CHAOS_DRUID(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_CHAOS_DRUID),
SPELL_REANIMATE_GIANT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_GIANT),
SPELL_REANIMATE_OGRE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_OGRE),
SPELL_REANIMATE_ELF(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_ELF),
SPELL_REANIMATE_TROLL(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_TROLL),
SPELL_REANIMATE_HORROR(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_HORROR),
SPELL_REANIMATE_KALPHITE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_KALPHITE),
SPELL_REANIMATE_DAGANNOTH(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_DAGANNOTH),
SPELL_REANIMATE_BLOODVELD(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_BLOODVELD),
SPELL_REANIMATE_TZHAAR(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_TZHAAR),
SPELL_REANIMATE_DEMON(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_DEMON),
SPELL_REANIMATE_AVIANSIE(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_AVIANSIE),
SPELL_REANIMATE_ABYSSAL(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_ABYSSAL),
SPELL_REANIMATE_DRAGON(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.SpellBook.REANIMATE_DRAGON),
/* END OF ARCEUUS SPELL BOOK WIDGETS*/
KOUREND_FAVOUR_OVERLAY(WidgetID.KOUREND_FAVOUR_GROUP_ID, WidgetID.KourendFavour.KOUREND_FAVOUR_OVERLAY),
ZEAH_MESS_HALL_COOKING_DISPLAY(WidgetID.ZEAH_MESS_HALL_GROUP_ID, WidgetID.Zeah.MESS_HALL_COOKING_DISPLAY),
LOOTING_BAG_CONTAINER(WidgetID.LOOTING_BAG_GROUP_ID, WidgetID.LootingBag.LOOTING_BAG_INVENTORY),
SKOTIZO_CONTAINER(WidgetID.SKOTIZO_GROUP_ID, WidgetID.Skotizo.CONTAINER),
MULTICOMBAT_FIXED(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MULTICOMBAT_INDICATOR),
MULTICOMBAT_RESIZEABLE(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewport.MULTICOMBAT_INDICATOR),
FULLSCREEN_MAP_ROOT(WidgetID.FULLSCREEN_MAP_GROUP_ID, WidgetID.FullScreenMap.ROOT),
QUESTLIST_BOX(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.BOX),
QUESTLIST_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.CONTAINER),
QUESTLIST_SCROLLBAR(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.SCROLLBAR),
QUESTLIST_FREE_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.FREE_CONTAINER),
QUESTLIST_MEMBERS_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.MEMBERS_CONTAINER),
QUESTLIST_MINIQUEST_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.MINIQUEST_CONTAINER),
MUSICTAB_INTERFACE(WidgetID.MUSICTAB_GROUP_ID, 1),
MUSICTAB_SONG_BOX(WidgetID.MUSICTAB_GROUP_ID, 2),
MUSICTAB_ALL_SONGS(WidgetID.MUSICTAB_GROUP_ID, 3),
MUSICTAB_SCROLLBAR(WidgetID.MUSICTAB_GROUP_ID, 4),
MUSICTAB_PLAYING(WidgetID.MUSICTAB_GROUP_ID, 5),
MUSICTAB_CURRENT_SONG_NAME(WidgetID.MUSICTAB_GROUP_ID, 6),
MUSICTAB_AUTO_BUTTON_LISTENER(WidgetID.MUSICTAB_GROUP_ID, 7),
MUSICTAB_AUTO_BUTTON(WidgetID.MUSICTAB_GROUP_ID, 8),
MUSICTAB_MANUAL_BUTTON_LISTENER(WidgetID.MUSICTAB_GROUP_ID, 9),
MUSICTAB_MANUAL_BUTTON(WidgetID.MUSICTAB_GROUP_ID, 10),
MUSICTAB_LOOP_BUTTON_LISTENER(WidgetID.MUSICTAB_GROUP_ID, 11),
MUSICTAB_LOOP_BUTTON(WidgetID.MUSICTAB_GROUP_ID, 12),
MUSICTAB_UNLOCKED_SONGS(WidgetID.MUSICTAB_GROUP_ID, 13),
QUESTTAB_QUEST_TAB(WidgetID.QUESTTAB_GROUP_ID, WidgetID.QuestTab.QUEST_TAB),
EQUIPMENT_MELEE_STRENGTH(WidgetID.EQUIPMENT_PAGE_GROUP_ID, WidgetID.EquipmentWidgetIdentifiers.MELEE_STRENGTH),
EQUIPMENT_RANGED_STRENGTH(WidgetID.EQUIPMENT_PAGE_GROUP_ID, WidgetID.EquipmentWidgetIdentifiers.RANGED_STRENGTH),
EQUIPMENT_MAGIC_DAMAGE(WidgetID.EQUIPMENT_PAGE_GROUP_ID, WidgetID.EquipmentWidgetIdentifiers.MAGIC_DAMAGE),
EQUIP_YOUR_CHARACTER(WidgetID.EQUIPMENT_PAGE_GROUP_ID, WidgetID.EquipmentWidgetIdentifiers.EQUIP_YOUR_CHARACTER),
BANK_PIN_TOP_LEFT_TEXT(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.TOP_LEFT_TEXT),
BANK_PIN_EXIT_BUTTON(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.EXIT_BUTTON),
BANK_PIN_FORGOT_BUTTON(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.FORGOT_BUTTON),
BANK_PIN_FIRST_ENTERED(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.FIRST_ENTERED),
BANK_PIN_SECOND_ENTERED(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.SECOND_ENTERED),
BANK_PIN_THIRD_ENTERED(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.THIRD_ENTERED),
BANK_PIN_FOURTH_ENTERED(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.FOURTH_ENTERED),
BANK_PIN_INSTRUCTION_TEXT(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.INSTRUCTION_TEXT),
BANK_PIN_1(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_1),
BANK_PIN_2(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_2),
BANK_PIN_3(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_3),
BANK_PIN_4(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_4),
BANK_PIN_5(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_5),
BANK_PIN_6(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_6),
BANK_PIN_7(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_7),
BANK_PIN_8(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_8),
BANK_PIN_9(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_9),
BANK_PIN_10(WidgetID.BANK_PIN_GROUP_ID, WidgetID.BankPin.BUTTON_10),
XP_DROP_1(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_1),
XP_DROP_2(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_2),
XP_DROP_3(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_3),
XP_DROP_4(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_4),
XP_DROP_5(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_5),
XP_DROP_6(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_6),
XP_DROP_7(WidgetID.EXPERIENCE_DROP_GROUP_ID, WidgetID.ExperienceDrop.DROP_7),
SEED_VAULT_TITLE_CONTAINER(WidgetID.SEED_VAULT_GROUP_ID, WidgetID.SeedVault.TITLE_CONTAINER),
SEED_VAULT_ITEM_CONTAINER(WidgetID.SEED_VAULT_GROUP_ID, WidgetID.SeedVault.ITEM_CONTAINER),
SEED_VAULT_ITEM_TEXT(WidgetID.SEED_VAULT_GROUP_ID, WidgetID.SeedVault.ITEM_TEXT),
SEED_VAULT_INVENTORY_ITEMS_CONTAINER(WidgetID.SEED_VAULT_INVENTORY_GROUP_ID, WidgetID.SeedVault.INVENTORY_ITEM_CONTAINER),
JEWELLERY_BOX_DUEL_RING(WidgetID.JEWELLERY_BOX_GROUP_ID, WidgetID.JewelBox.DUEL_RING),
JEWELLERY_BOX_GAME_NECK(WidgetID.JEWELLERY_BOX_GROUP_ID, WidgetID.JewelBox.GAME_NECK),
JEWELLERY_BOX_COMB_BRAC(WidgetID.JEWELLERY_BOX_GROUP_ID, WidgetID.JewelBox.COMB_BRAC),
JEWELLERY_BOX_SKIL_NECK(WidgetID.JEWELLERY_BOX_GROUP_ID, WidgetID.JewelBox.SKIL_NECK),
JEWELLERY_BOX_RING_OFGP(WidgetID.JEWELLERY_BOX_GROUP_ID, WidgetID.JewelBox.RING_OFGP),
JEWELLERY_BOX_AMUL_GLOR(WidgetID.JEWELLERY_BOX_GROUP_ID, WidgetID.JewelBox.AMUL_GLOR),
OPTIONS_CAMERA_ZOOM_SLIDER_HANDLE(WidgetID.OPTIONS_GROUP_ID, WidgetID.Options.CAMERA_ZOOM_SLIDER_HANDLE),
OPTIONS_MUSIC_SLIDER(WidgetID.OPTIONS_GROUP_ID, WidgetID.Options.MUSIC_SLIDER),
OPTIONS_SOUND_EFFECT_SLIDER(WidgetID.OPTIONS_GROUP_ID, WidgetID.Options.SOUND_EFFECT_SLIDER),
OPTIONS_AREA_SOUND_SLIDER(WidgetID.OPTIONS_GROUP_ID, WidgetID.Options.AREA_SOUND_SLIDER),
ACHIEVEMENT_DIARY_CONTAINER(WidgetID.ACHIEVEMENT_DIARY_GROUP_ID, WidgetID.AchievementDiary.CONTAINER),
SKILLS_CONTAINER(WidgetID.SKILLS_GROUP_ID, WidgetID.Skills.CONTAINER),
TRADING_WITH(WidgetID.PLAYER_TRADE_SCREEN_GROUP_ID, WidgetID.TradeScreen.FIRST_TRADING_WITH),
SECOND_TRADING_WITH(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_TRADING_WITH),
SECOND_TRADING_WITH_ACCEPT_BUTTON(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_ACCEPT_FUNC),
SECOND_TRADING_WITH_ACCEPT_TEXT(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_ACCEPT_TEXT),
SECOND_TRADING_WITH_DECLINE_BUTTON(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_DECLINE_FUNC),
SECOND_TRADING_WITH_DECLINE_TEXT(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_DECLINE_TEXT),
SECOND_TRADING_WITH_MY_OFFER(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_MY_OFFER),
SECOND_TRADING_WITH_THEIR_OFFER(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_THEIR_OFFER),
SECOND_TRADING_WITH_MY_ITEMS(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_MY_ITEMS),
SECOND_TRADING_WITH_THEIR_ITEMS(WidgetID.PLAYER_TRADE_CONFIRM_GROUP_ID, WidgetID.TradeScreen.SECOND_THEIR_ITEMS),
GAUNTLET_TIMER_CONTAINER(WidgetID.GAUNTLET_TIMER_GROUP_ID, WidgetID.GauntletTimer.CONTAINER);
private final int groupId;
private final int childId;
WidgetInfo(int groupId, int childId)
{
this.groupId = groupId;
this.childId = childId;
}
/**
* Gets the ID of the group-child pairing.
*
* @return the ID
*/
public int getId()
{
return groupId << 16 | childId;
}
/**
* Gets the group ID of the pair.
*
* @return the group ID
*/
public int getGroupId()
{
return groupId;
}
/**
* Gets the ID of the child in the group.
*
* @return the child ID
*/
public int getChildId()
{
return childId;
}
/**
* Gets the packed widget ID.
*
* @return the packed ID
*/
public int getPackedId()
{
return groupId << 16 | childId;
}
/**
* Utility method that converts an ID returned by {@link #getId()} back
* to its group ID.
*
* @param id passed group-child ID
* @return the group ID
*/
public static int TO_GROUP(int id)
{
return id >>> 16;
}
/**
* Utility method that converts an ID returned by {@link #getId()} back
* to its child ID.
*
* @param id passed group-child ID
* @return the child ID
*/
public static int TO_CHILD(int id)
{
return id & 0xFFFF;
}
/**
* Packs the group and child IDs into a single integer.
*
* @param groupId the group ID
* @param childId the child ID
* @return the packed ID
*/
public static int PACK(int groupId, int childId)
{
return groupId << 16 | childId;
}
}
| 1 | 16,462 | remove the extra comma and newline | open-osrs-runelite | java |
@@ -1,3 +1,5 @@
+<% @page_title = t('blacklight.saved_searches.page_title', :application_name => application_name) %>
+
<div id="content" class="col-md-9">
<h1 class='page-heading'><%= t('blacklight.saved_searches.title') %></h1> | 1 | <div id="content" class="col-md-9">
<h1 class='page-heading'><%= t('blacklight.saved_searches.title') %></h1>
<%- if current_or_guest_user.blank? -%>
<h2 class='section-heading'><%= t('blacklight.saved_searches.need_login') %></h2>
<%- elsif @searches.blank? -%>
<h2 class='section-heading'><%= t('blacklight.saved_searches.no_searches') %></h2>
<%- else -%>
<p>
<%= link_to t('blacklight.saved_searches.clear.action_title'), clear_saved_searches_path, :method => :delete, :data => { :confirm => t('blacklight.saved_searches.clear.action_confirm') } %>
</p>
<h2 class='section-heading'><%= t('blacklight.saved_searches.list_title') %></h2>
<table class="table table-striped">
<%- @searches.each do |search| -%>
<tr>
<td><%= link_to_previous_search(search.query_params) %></td>
<td><%= button_to t('blacklight.saved_searches.delete'), forget_search_path(search.id) %></td>
</tr>
<%- end -%>
</table>
<%- end -%>
</div>
| 1 | 6,043 | Can we try to use Ruby 1.9-style hashes? | projectblacklight-blacklight | rb |
@@ -120,6 +120,17 @@ func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) {
})
}
+// RegisterGlobalOption registers a unique global option opt with
+// an associated unmarshaling (setup) function. When the global
+// option opt is encountered in a Caddyfile, setupFunc will be
+// called to unmarshal its tokens.
+func RegisterGlobalOption(opt string, setupFunc UnmarshalGlobalFunc) {
+ if _, ok := registeredGlobalOptions[opt]; ok {
+ panic("global option " + opt + " already registered")
+ }
+ registeredGlobalOptions[opt] = setupFunc
+}
+
// Helper is a type which helps setup a value from
// Caddyfile tokens.
type Helper struct { | 1 | // Copyright 2015 Matthew Holt and The Caddy 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 httpcaddyfile
import (
"encoding/json"
"net"
"sort"
"strconv"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
// directiveOrder specifies the order
// to apply directives in HTTP routes.
//
// The root directive goes first in case rewrites or
// redirects depend on existence of files, i.e. the
// file matcher, which must know the root first.
//
// The header directive goes second so that headers
// can be manipulated before doing redirects.
var directiveOrder = []string{
"root",
"header",
"redir",
"rewrite",
// URI manipulation
"uri",
"try_files",
// middleware handlers; some wrap responses
"basicauth",
"request_header",
"encode",
"templates",
// special routing directives
"handle",
"route",
// handlers that typically respond to requests
"respond",
"reverse_proxy",
"php_fastcgi",
"file_server",
}
// directiveIsOrdered returns true if dir is
// a known, ordered (sorted) directive.
func directiveIsOrdered(dir string) bool {
for _, d := range directiveOrder {
if d == dir {
return true
}
}
return false
}
// RegisterDirective registers a unique directive dir with an
// associated unmarshaling (setup) function. When directive dir
// is encountered in a Caddyfile, setupFunc will be called to
// unmarshal its tokens.
func RegisterDirective(dir string, setupFunc UnmarshalFunc) {
if _, ok := registeredDirectives[dir]; ok {
panic("directive " + dir + " already registered")
}
registeredDirectives[dir] = setupFunc
}
// RegisterHandlerDirective is like RegisterDirective, but for
// directives which specifically output only an HTTP handler.
// Directives registered with this function will always have
// an optional matcher token as the first argument.
func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) {
RegisterDirective(dir, func(h Helper) ([]ConfigValue, error) {
if !h.Next() {
return nil, h.ArgErr()
}
matcherSet, ok, err := h.MatcherToken()
if err != nil {
return nil, err
}
if ok {
// strip matcher token; we don't need to
// use the return value here because a
// new dispenser should have been made
// solely for this directive's tokens,
// with no other uses of same slice
h.Dispenser.Delete()
}
h.Dispenser.Reset() // pretend this lookahead never happened
val, err := setupFunc(h)
if err != nil {
return nil, err
}
return h.NewRoute(matcherSet, val), nil
})
}
// Helper is a type which helps setup a value from
// Caddyfile tokens.
type Helper struct {
*caddyfile.Dispenser
// State stores intermediate variables during caddyfile adaptation.
State map[string]interface{}
options map[string]interface{}
warnings *[]caddyconfig.Warning
matcherDefs map[string]caddy.ModuleMap
parentBlock caddyfile.ServerBlock
groupCounter counter
}
// Option gets the option keyed by name.
func (h Helper) Option(name string) interface{} {
return h.options[name]
}
// Caddyfiles returns the list of config files from
// which tokens in the current server block were loaded.
func (h Helper) Caddyfiles() []string {
// first obtain set of names of files involved
// in this server block, without duplicates
files := make(map[string]struct{})
for _, segment := range h.parentBlock.Segments {
for _, token := range segment {
files[token.File] = struct{}{}
}
}
// then convert the set into a slice
filesSlice := make([]string, 0, len(files))
for file := range files {
filesSlice = append(filesSlice, file)
}
return filesSlice
}
// JSON converts val into JSON. Any errors are added to warnings.
func (h Helper) JSON(val interface{}) json.RawMessage {
return caddyconfig.JSON(val, h.warnings)
}
// MatcherToken assumes the next argument token is (possibly) a matcher,
// and if so, returns the matcher set along with a true value. If the next
// token is not a matcher, nil and false is returned. Note that a true
// value may be returned with a nil matcher set if it is a catch-all.
func (h Helper) MatcherToken() (caddy.ModuleMap, bool, error) {
if !h.NextArg() {
return nil, false, nil
}
return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings)
}
// ExtractMatcherSet is like MatcherToken, except this is a higher-level
// method that returns the matcher set described by the matcher token,
// or nil if there is none, and deletes the matcher token from the
// dispenser and resets it as if this look-ahead never happened. Useful
// when wrapping a route (one or more handlers) in a user-defined matcher.
func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
matcherSet, hasMatcher, err := h.MatcherToken()
if err != nil {
return nil, err
}
if hasMatcher {
h.Dispenser.Delete() // strip matcher token
}
h.Dispenser.Reset() // pretend this lookahead never happened
return matcherSet, nil
}
// NewRoute returns config values relevant to creating a new HTTP route.
func (h Helper) NewRoute(matcherSet caddy.ModuleMap,
handler caddyhttp.MiddlewareHandler) []ConfigValue {
mod, err := caddy.GetModule(caddy.GetModuleID(handler))
if err != nil {
*h.warnings = append(*h.warnings, caddyconfig.Warning{
File: h.File(),
Line: h.Line(),
Message: err.Error(),
})
return nil
}
var matcherSetsRaw []caddy.ModuleMap
if matcherSet != nil {
matcherSetsRaw = append(matcherSetsRaw, matcherSet)
}
return []ConfigValue{
{
Class: "route",
Value: caddyhttp.Route{
MatcherSetsRaw: matcherSetsRaw,
HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", mod.ID.Name(), h.warnings)},
},
},
}
}
// GroupRoutes adds the routes (caddyhttp.Route type) in vals to the
// same group, if there is more than one route in vals.
func (h Helper) GroupRoutes(vals []ConfigValue) {
// ensure there's at least two routes; group of one is pointless
var count int
for _, v := range vals {
if _, ok := v.Value.(caddyhttp.Route); ok {
count++
if count > 1 {
break
}
}
}
if count < 2 {
return
}
// now that we know the group will have some effect, do it
groupName := h.groupCounter.nextGroup()
for i := range vals {
if route, ok := vals[i].Value.(caddyhttp.Route); ok {
route.Group = groupName
vals[i].Value = route
}
}
}
// NewBindAddresses returns config values relevant to adding
// listener bind addresses to the config.
func (h Helper) NewBindAddresses(addrs []string) []ConfigValue {
return []ConfigValue{{Class: "bind", Value: addrs}}
}
// ConfigValue represents a value to be added to the final
// configuration, or a value to be consulted when building
// the final configuration.
type ConfigValue struct {
// The kind of value this is. As the config is
// being built, the adapter will look in the
// "pile" for values belonging to a certain
// class when it is setting up a certain part
// of the config. The associated value will be
// type-asserted and placed accordingly.
Class string
// The value to be used when building the config.
// Generally its type is associated with the
// name of the Class.
Value interface{}
directive string
}
func sortRoutes(routes []ConfigValue) {
dirPositions := make(map[string]int)
for i, dir := range directiveOrder {
dirPositions[dir] = i
}
sort.SliceStable(routes, func(i, j int) bool {
// if the directives are different, just use the established directive order
iDir, jDir := routes[i].directive, routes[j].directive
if iDir != jDir {
return dirPositions[iDir] < dirPositions[jDir]
}
// directives are the same; sub-sort by path matcher length if there's
// only one matcher set and one path (this is a very common case and
// usually -- but not always -- helpful/expected, oh well; user can
// always take manual control of order using handler or route blocks)
iRoute, ok := routes[i].Value.(caddyhttp.Route)
if !ok {
return false
}
jRoute, ok := routes[j].Value.(caddyhttp.Route)
if !ok {
return false
}
// decode the path matchers, if there is just one of them
var iPM, jPM caddyhttp.MatchPath
if len(iRoute.MatcherSetsRaw) == 1 {
_ = json.Unmarshal(iRoute.MatcherSetsRaw[0]["path"], &iPM)
}
if len(jRoute.MatcherSetsRaw) == 1 {
_ = json.Unmarshal(jRoute.MatcherSetsRaw[0]["path"], &jPM)
}
// sort by longer path (more specific) first; missing path
// matchers or multi-matchers are treated as zero-length paths
var iPathLen, jPathLen int
if len(iPM) > 0 {
iPathLen = len(iPM[0])
}
if len(jPM) > 0 {
jPathLen = len(jPM[0])
}
return iPathLen > jPathLen
})
}
// parseSegmentAsSubroute parses the segment such that its subdirectives
// are themselves treated as directives, from which a subroute is built
// and returned.
func parseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) {
var allResults []ConfigValue
for h.Next() {
// slice the linear list of tokens into top-level segments
var segments []caddyfile.Segment
for nesting := h.Nesting(); h.NextBlock(nesting); {
segments = append(segments, h.NextSegment())
}
// copy existing matcher definitions so we can augment
// new ones that are defined only in this scope
matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs))
for key, val := range h.matcherDefs {
matcherDefs[key] = val
}
// find and extract any embedded matcher definitions in this scope
for i, seg := range segments {
if strings.HasPrefix(seg.Directive(), matcherPrefix) {
err := parseMatcherDefinitions(caddyfile.NewDispenser(seg), matcherDefs)
if err != nil {
return nil, err
}
segments = append(segments[:i], segments[i+1:]...)
}
}
// with matchers ready to go, evaluate each directive's segment
for _, seg := range segments {
dir := seg.Directive()
dirFunc, ok := registeredDirectives[dir]
if !ok {
return nil, h.Errf("unrecognized directive: %s", dir)
}
subHelper := h
subHelper.Dispenser = caddyfile.NewDispenser(seg)
subHelper.matcherDefs = matcherDefs
results, err := dirFunc(subHelper)
if err != nil {
return nil, h.Errf("parsing caddyfile tokens for '%s': %v", dir, err)
}
for _, result := range results {
result.directive = dir
allResults = append(allResults, result)
}
}
}
return buildSubroute(allResults, h.groupCounter)
}
// serverBlock pairs a Caddyfile server block with
// a "pile" of config values, keyed by class name,
// as well as its parsed keys for convenience.
type serverBlock struct {
block caddyfile.ServerBlock
pile map[string][]ConfigValue // config values obtained from directives
keys []Address
}
// hostsFromKeys returns a list of all the non-empty hostnames found in
// the keys of the server block sb. If logger mode is false, a key with
// an empty hostname portion will return an empty slice, since that
// server block is interpreted to effectively match all hosts. An empty
// string is never added to the slice.
//
// If loggerMode is true, then the non-standard ports of keys will be
// joined to the hostnames. This is to effectively match the Host
// header of requests that come in for that key.
//
// The resulting slice is not sorted but will never have duplicates.
func (sb serverBlock) hostsFromKeys(loggerMode bool) []string {
// ensure each entry in our list is unique
hostMap := make(map[string]struct{})
for _, addr := range sb.keys {
if addr.Host == "" {
if !loggerMode {
// server block contains a key like ":443", i.e. the host portion
// is empty / catch-all, which means to match all hosts
return []string{}
}
// never append an empty string
continue
}
if loggerMode &&
addr.Port != "" &&
addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPPort) &&
addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPSPort) {
hostMap[net.JoinHostPort(addr.Host, addr.Port)] = struct{}{}
} else {
hostMap[addr.Host] = struct{}{}
}
}
// convert map to slice
sblockHosts := make([]string, 0, len(hostMap))
for host := range hostMap {
sblockHosts = append(sblockHosts, host)
}
return sblockHosts
}
// hasHostCatchAllKey returns true if sb has a key that
// omits a host portion, i.e. it "catches all" hosts.
func (sb serverBlock) hasHostCatchAllKey() bool {
for _, addr := range sb.keys {
if addr.Host == "" {
return true
}
}
return false
}
type (
// UnmarshalFunc is a function which can unmarshal Caddyfile
// tokens into zero or more config values using a Helper type.
// These are passed in a call to RegisterDirective.
UnmarshalFunc func(h Helper) ([]ConfigValue, error)
// UnmarshalHandlerFunc is like UnmarshalFunc, except the
// output of the unmarshaling is an HTTP handler. This
// function does not need to deal with HTTP request matching
// which is abstracted away. Since writing HTTP handlers
// with Caddyfile support is very common, this is a more
// convenient way to add a handler to the chain since a lot
// of the details common to HTTP handlers are taken care of
// for you. These are passed to a call to
// RegisterHandlerDirective.
UnmarshalHandlerFunc func(h Helper) (caddyhttp.MiddlewareHandler, error)
)
var registeredDirectives = make(map[string]UnmarshalFunc)
| 1 | 14,667 | Terminology question - these are called "global options" in the code, but the parallel non-global versions of these are called "directives"... Should this be `RegisterGlobalDirective`? Or does that have different semantics? | caddyserver-caddy | go |
@@ -244,7 +244,7 @@ def isTypingProtected():
@rtype: boolean
"""
focusObject=getFocusObject()
- if focusObject and (controlTypes.STATE_PROTECTED in focusObject.states or focusObject.role==controlTypes.ROLE_PASSWORDEDIT):
+ if focusObject and focusObject.isProtected:
return True
else:
return False | 1 | #api.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2012 NVDA Contributors
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""General functions for NVDA"""
import config
import textInfos
import review
import globalVars
from logHandler import log
import ui
import treeInterceptorHandler
import virtualBuffers
import NVDAObjects
import NVDAObjects.IAccessible
import winUser
import controlTypes
import win32clipboard
import win32con
import eventHandler
import braille
import watchdog
import appModuleHandler
#User functions
def getFocusObject():
"""
Gets the current object with focus.
@returns: the object with focus
@rtype: L{NVDAObjects.NVDAObject}
"""
return globalVars.focusObject
def getForegroundObject():
"""Gets the current foreground object.
@returns: the current foreground object
@rtype: L{NVDAObjects.NVDAObject}
"""
return globalVars.foregroundObject
def setForegroundObject(obj):
"""Stores the given object as the current foreground object. (Note: it does not physically change the operating system foreground window, but only allows NVDA to keep track of what it is).
@param obj: the object that will be stored as the current foreground object
@type obj: NVDAObjects.NVDAObject
"""
if not isinstance(obj,NVDAObjects.NVDAObject):
return False
globalVars.foregroundObject=obj
return True
def setFocusObject(obj):
"""Stores an object as the current focus object. (Note: this does not physically change the window with focus in the operating system, but allows NVDA to keep track of the correct object).
Before overriding the last object, this function calls event_loseFocus on the object to notify it that it is loosing focus.
@param obj: the object that will be stored as the focus object
@type obj: NVDAObjects.NVDAObject
"""
if not isinstance(obj,NVDAObjects.NVDAObject):
return False
if globalVars.focusObject:
eventHandler.executeEvent("loseFocus",globalVars.focusObject)
oldFocusLine=globalVars.focusAncestors
#add the old focus to the old focus ancestors, but only if its not None (is none at NVDA initialization)
if globalVars.focusObject:
oldFocusLine.append(globalVars.focusObject)
oldAppModules=[o.appModule for o in oldFocusLine if o and o.appModule]
appModuleHandler.cleanup()
ancestors=[]
tempObj=obj
matchedOld=False
focusDifferenceLevel=0
oldFocusLineLength=len(oldFocusLine)
# Starting from the focus, move up the ancestor chain.
safetyCount=0
while tempObj:
if safetyCount<100:
safetyCount+=1
else:
try:
log.error("Never ending focus ancestry: last object: %s, %s, window class %s, application name %s"%(tempObj.name,controlTypes.roleLabels[tempObj.role],tempObj.windowClassName,tempObj.appModule.appName))
except:
pass
tempObj=getDesktopObject()
# Scan backwards through the old ancestors looking for a match.
for index in xrange(oldFocusLineLength-1,-1,-1):
watchdog.alive()
if tempObj==oldFocusLine[index]:
# Match! The old and new focus ancestors converge at this point.
# Copy the old ancestors up to and including this object.
origAncestors=oldFocusLine[0:index+1]
#make sure to cache the last old ancestor as a parent on the first new ancestor so as not to leave a broken parent cache
if ancestors and origAncestors:
ancestors[0].container=origAncestors[-1]
origAncestors.extend(ancestors)
ancestors=origAncestors
focusDifferenceLevel=index+1
# We don't need to process any more in either this loop or the outer loop; we have all of the ancestors.
matchedOld=True
break
if matchedOld:
break
# We're moving backwards along the ancestor chain, so add this to the start of the list.
ancestors.insert(0,tempObj)
container=tempObj.container
tempObj.container=container # Cache the parent.
tempObj=container
#Remove the final new ancestor as this will be the new focus object
del ancestors[-1]
# #5467: Ensure that the appModule of the real focus is included in the newAppModule list for profile switching
# Rather than an original focus ancestor which happened to match the new focus.
newAppModules=[o.appModule for o in ancestors if o and o.appModule]
if obj.appModule:
newAppModules.append(obj.appModule)
try:
treeInterceptorHandler.cleanup()
except watchdog.CallCancelled:
pass
treeInterceptorObject=None
o=None
watchdog.alive()
for o in ancestors[focusDifferenceLevel:]+[obj]:
try:
treeInterceptorObject=treeInterceptorHandler.update(o)
except:
log.exception("Error updating tree interceptor")
#Always make sure that the focus object's treeInterceptor is forced to either the found treeInterceptor (if its in it) or to None
#This is to make sure that the treeInterceptor does not have to be looked up, which can cause problems for winInputHook
if obj is o or obj in treeInterceptorObject:
obj.treeInterceptor=treeInterceptorObject
else:
obj.treeInterceptor=None
# #3804: handleAppSwitch should be called as late as possible,
# as triggers must not be out of sync with global focus variables.
# setFocusObject shouldn't fail earlier anyway, but it's best to be safe.
appModuleHandler.handleAppSwitch(oldAppModules,newAppModules)
# Set global focus variables.
globalVars.focusDifferenceLevel=focusDifferenceLevel
globalVars.focusObject=obj
globalVars.focusAncestors=ancestors
braille.invalidateCachedFocusAncestors(focusDifferenceLevel)
if config.conf["reviewCursor"]["followFocus"]:
setNavigatorObject(obj,isFocus=True)
return True
def getFocusDifferenceLevel():
return globalVars.focusDifferenceLevel
def getFocusAncestors():
return globalVars.focusAncestors
def getMouseObject():
"""Returns the object that is directly under the mouse"""
return globalVars.mouseObject
def setMouseObject(obj):
"""Tells NVDA to remember the given object as the object that is directly under the mouse"""
globalVars.mouseObject=obj
def getDesktopObject():
"""Get the desktop object"""
return globalVars.desktopObject
def setDesktopObject(obj):
"""Tells NVDA to remember the given object as the desktop object"""
globalVars.desktopObject=obj
def getReviewPosition():
"""Retreaves the current TextInfo instance representing the user's review position. If it is not set, it uses the user's set navigator object and creates a TextInfo from that.
"""
if globalVars.reviewPosition:
return globalVars.reviewPosition
else:
obj=globalVars.navigatorObject
globalVars.reviewPosition,globalVars.reviewPositionObj=review.getPositionForCurrentMode(obj)
return globalVars.reviewPosition
def setReviewPosition(reviewPosition,clearNavigatorObject=True,isCaret=False):
"""Sets a TextInfo instance as the review position.
@param clearNavigatorObject: if true, It sets the current navigator object to C{None}.
In that case, the next time the navigator object is asked for it fetches it from the review position.
@type clearNavigatorObject: bool
@param isCaret: Whether the review position is changed due to caret following.
@type isCaret: bool
"""
globalVars.reviewPosition=reviewPosition.copy()
globalVars.reviewPositionObj=reviewPosition.obj
if clearNavigatorObject: globalVars.navigatorObject=None
# When the review cursor follows the caret and braille is auto tethered to review,
# we should not update braille with the new review position as a tether to focus is due.
if braille.handler.shouldAutoTether and isCaret:
return
braille.handler.handleReviewMove(shouldAutoTether=not isCaret)
def getNavigatorObject():
"""Gets the current navigator object. Navigator objects can be used to navigate around the operating system (with the number pad) with out moving the focus. If the navigator object is not set, it fetches it from the review position.
@returns: the current navigator object
@rtype: L{NVDAObjects.NVDAObject}
"""
if globalVars.navigatorObject:
return globalVars.navigatorObject
else:
if review.getCurrentMode()=='object':
obj=globalVars.reviewPosition.obj
else:
try:
obj=globalVars.reviewPosition.NVDAObjectAtStart
except (NotImplementedError,LookupError):
obj=globalVars.reviewPosition.obj
globalVars.navigatorObject=getattr(obj,'rootNVDAObject',None) or obj
return globalVars.navigatorObject
def setNavigatorObject(obj,isFocus=False):
"""Sets an object to be the current navigator object. Navigator objects can be used to navigate around the operating system (with the number pad) with out moving the focus. It also sets the current review position to None so that next time the review position is asked for, it is created from the navigator object.
@param obj: the object that will be set as the current navigator object
@type obj: NVDAObjects.NVDAObject
@param isFocus: true if the navigator object was set due to a focus change.
@type isFocus: bool
"""
if not isinstance(obj,NVDAObjects.NVDAObject):
return False
globalVars.navigatorObject=obj
oldPos=globalVars.reviewPosition
oldPosObj=globalVars.reviewPositionObj
globalVars.reviewPosition=None
globalVars.reviewPositionObj=None
reviewMode=review.getCurrentMode()
# #3320: If in document review yet there is no document to review the mode should be forced to object.
if reviewMode=='document' and (not isinstance(obj.treeInterceptor,treeInterceptorHandler.DocumentTreeInterceptor) or not obj.treeInterceptor.isReady or obj.treeInterceptor.passThrough):
review.setCurrentMode('object',False)
elif isinstance(obj.treeInterceptor,treeInterceptorHandler.DocumentTreeInterceptor) and obj.treeInterceptor.isReady and not obj.treeInterceptor.passThrough:
if reviewMode=='object':
review.setCurrentMode('document',False)
if isFocus:
globalVars.reviewPosition=obj.treeInterceptor.makeTextInfo(textInfos.POSITION_CARET)
globalVars.reviewPositionObj=globalVars.reviewPosition
eventHandler.executeEvent("becomeNavigatorObject",obj,isFocus=isFocus)
def isTypingProtected():
"""Checks to see if key echo should be suppressed because the focus is currently on an object that has its protected state set.
@returns: True if it should be suppressed, False otherwise.
@rtype: boolean
"""
focusObject=getFocusObject()
if focusObject and (controlTypes.STATE_PROTECTED in focusObject.states or focusObject.role==controlTypes.ROLE_PASSWORDEDIT):
return True
else:
return False
def createStateList(states):
"""Breaks down the given integer in to a list of numbers that are 2 to the power of their position."""
return [x for x in [1<<y for y in xrange(32)] if x&states]
def moveMouseToNVDAObject(obj):
"""Moves the mouse to the given NVDA object's position"""
location=obj.location
if location and (len(location)==4):
(left,top,width,height)=location
x=(left+left+width)/2
y=(top+top+height)/2
winUser.setCursorPos(x,y)
def processPendingEvents(processEventQueue=True):
# Import late to avoid circular import.
import IAccessibleHandler
import JABHandler
import wx
import queueHandler
watchdog.alive()
wx.Yield()
JABHandler.pumpAll()
IAccessibleHandler.pumpAll()
import baseObject
baseObject.AutoPropertyObject.invalidateCaches()
if processEventQueue:
queueHandler.flushQueue(queueHandler.eventQueue)
def copyToClip(text):
"""Copies the given text to the windows clipboard.
@returns: True if it succeeds, False otherwise.
@rtype: boolean
@param text: the text which will be copied to the clipboard
@type text: string
"""
if isinstance(text,basestring) and len(text)>0 and not text.isspace():
try:
win32clipboard.OpenClipboard()
except win32clipboard.error:
return False
try:
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32con.CF_UNICODETEXT, text)
finally:
win32clipboard.CloseClipboard()
win32clipboard.OpenClipboard() # there seems to be a bug so to retrieve unicode text we have to reopen the clipboard
try:
got = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
finally:
win32clipboard.CloseClipboard()
if got == text:
return True
return False
def getClipData():
"""Receives text from the windows clipboard.
@returns: Clipboard text
@rtype: string
"""
text = ""
win32clipboard.OpenClipboard()
try:
text = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
finally:
win32clipboard.CloseClipboard()
return text
def getStatusBar():
"""Obtain the status bar for the current foreground object.
@return: The status bar object or C{None} if no status bar was found.
@rtype: L{NVDAObjects.NVDAObject}
"""
# The status bar is usually at the bottom of the screen.
# Therefore, get the object at the bottom left of the foreground object using screen coordinates.
foreground = getForegroundObject()
location=foreground.location
if not location:
return None
left, top, width, height = location
bottom = top + height - 1
obj = getDesktopObject().objectFromPoint(left, bottom)
# We may have landed in a child of the status bar, so search the ancestry for a status bar.
while obj and not obj.role == controlTypes.ROLE_STATUSBAR:
obj = obj.parent
return obj
def getStatusBarText(obj):
"""Get the text from a status bar.
This includes the name of the status bar and the names and values of all of its children.
@param obj: The status bar.
@type obj: L{NVDAObjects.NVDAObject}
@return: The status bar text.
@rtype: str
"""
text = obj.name or ""
if text:
text += " "
return text + " ".join(chunk for child in obj.children for chunk in (child.name, child.value) if chunk and isinstance(chunk, basestring) and not chunk.isspace())
def filterFileName(name):
"""Replaces invalid characters in a given string to make a windows compatible file name.
@param name: The file name to filter.
@type name: str
@returns: The filtered file name.
@rtype: str
"""
invalidChars=':?*\|<>/"'
for c in invalidChars:
name=name.replace(c,'_')
return name
def getCaretObject():
"""Gets the object which contains the caret.
This is normally the focus object.
However, if the focus object has a tree interceptor which is not in focus mode,
the tree interceptor will be returned.
@return: The object containing the caret.
@rtype: L{baseObject.ScriptableObject}
"""
obj = getFocusObject()
ti = obj.treeInterceptor
if isinstance(ti,treeInterceptorHandler.DocumentTreeInterceptor) and ti.isReady and not ti.passThrough:
return ti
return obj
| 1 | 21,563 | I do not care much, but you could as well just return bool(focusObject and focusObject.isProtected) here and avoid the if check? I know, really trivial. | nvaccess-nvda | py |
@@ -35,3 +35,6 @@ def testCanClickOnALinkThatOverflowsAndFollowIt(driver):
def testClickingALinkMadeUpOfNumbersIsHandledCorrectly(driver):
driver.find_element(By.LINK_TEXT, "333333").click()
WebDriverWait(driver, 3).until(EC.title_is("XHTML Test Page"))
+
+def testCannotClickDisabledButton(driver):
+ WebDriverWait(driver, 3).until(EC.element_to_be_unclickable(By.ID, "disabled-button")) | 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.
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
@pytest.fixture(autouse=True)
def loadPage(pages):
pages.load("clicks.html")
def testCanClickOnALinkThatOverflowsAndFollowIt(driver):
driver.find_element(By.ID, "overflowLink").click()
WebDriverWait(driver, 3).until(EC.title_is("XHTML Test Page"))
def testClickingALinkMadeUpOfNumbersIsHandledCorrectly(driver):
driver.find_element(By.LINK_TEXT, "333333").click()
WebDriverWait(driver, 3).until(EC.title_is("XHTML Test Page"))
| 1 | 16,343 | I believe it's misleading name for the condition. I prefer "element_to_be_disable" We can have a condition, when element is enabled but we can't click it, because another element overlays above it. So, If we use "unclickable" we might mislead people, who use that condition to verify if element can be clicked | SeleniumHQ-selenium | java |
@@ -50,7 +50,7 @@ public class GoLanguageProvider {
@SuppressWarnings("unchecked")
public <Element> GeneratedResult generate(
- Element element, SnippetDescriptor snippetDescriptor, GoGapicContext context) {
+ Element element, SnippetDescriptor snippetDescriptor, Object context) {
GoSnippetSet<Element> snippets =
SnippetSet.createSnippetInterface(
GoSnippetSet.class, | 1 | /* Copyright 2016 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.
*/
package io.gapi.vgen.go;
import com.google.api.tools.framework.snippet.Doc;
import com.google.api.tools.framework.snippet.SnippetSet;
import com.google.api.tools.framework.tools.ToolUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import io.gapi.vgen.GeneratedResult;
import io.gapi.vgen.SnippetDescriptor;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A GoLanguageProvider provides general Go code generation logic.
*/
public class GoLanguageProvider {
/**
* The path to the root of snippet resources.
*/
private static final String SNIPPET_RESOURCE_ROOT =
GoContextCommon.class.getPackage().getName().replace('.', '/');
public <Element> void output(String outputPath, Multimap<Element, GeneratedResult> elements)
throws IOException {
Map<String, Doc> files = new LinkedHashMap<>();
for (GeneratedResult generatedResult : elements.values()) {
files.put(generatedResult.getFilename(), generatedResult.getDoc());
}
ToolUtil.writeFiles(files, outputPath);
}
@SuppressWarnings("unchecked")
public <Element> GeneratedResult generate(
Element element, SnippetDescriptor snippetDescriptor, GoGapicContext context) {
GoSnippetSet<Element> snippets =
SnippetSet.createSnippetInterface(
GoSnippetSet.class,
SNIPPET_RESOURCE_ROOT,
snippetDescriptor.getSnippetInputName(),
ImmutableMap.<String, Object>of("context", context));
String outputFilename = snippets.generateFilename(element).prettyPrint();
Doc body = snippets.generateBody(element);
Doc result = snippets.generateClass(element, body);
return GeneratedResult.create(result, outputFilename);
}
}
| 1 | 14,535 | Do DiscoveryContext and GoGapicContext have a more specific common ancestor than Object? If so, let's use that. | googleapis-gapic-generator | java |
@@ -119,7 +119,7 @@ module Beaker
:timeout => 300,
:fail_mode => 'slow',
:timesync => false,
- :disable_iptables => true,
+ :disable_iptables => false,
:repo_proxy => false,
:package_proxy => false,
:add_el_extras => false, | 1 | module Beaker
module Options
#A class representing the environment variables and preset argument values to be incorporated
#into the Beaker options Object.
class Presets
# This is a constant that describes the variables we want to collect
# from the environment. The keys correspond to the keys in
# `presets` (flattened) The values are an optional array of
# environment variable names to look for. The array structure allows
# us to define multiple environment variables for the same
# configuration value. They are checked in the order they are arrayed
# so that preferred and "fallback" values work as expected.
ENVIRONMENT_SPEC = {
:home => 'HOME',
:project => ['BEAKER_PROJECT', 'BEAKER_project'],
:department => ['BEAKER_DEPARTMENT', 'BEAKER_department'],
:jenkins_build_url => ['BEAKER_BUILD_URL', 'BUILD_URL'],
:consoleport => ['BEAKER_CONSOLEPORT', 'consoleport'],
:is_pe => ['BEAKER_IS_PE', 'IS_PE'],
:pe_dir => ['BEAKER_PE_DIR', 'pe_dist_dir'],
:pe_version_file => ['BEAKER_PE_VERSION_FILE', 'pe_version_file'],
:pe_ver => ['BEAKER_PE_VER', 'pe_ver'],
:forge_host => ['BEAKER_FORGE_HOST', 'forge_host'],
:package_proxy => ['BEAKER_PACKAGE_PROXY'],
:release_apt_repo_url => ['BEAKER_RELEASE_APT_REPO', 'RELEASE_APT_REPO'],
:release_yum_repo_url => ['BEAKER_RELEASE_YUM_REPO', 'RELEASE_YUM_REPO'],
:dev_builds_url => ['BEAKER_DEV_BUILDS_URL', 'DEV_BUILDS_URL'],
}
# Select all environment variables whose name matches provided regex
# @return [Hash] Hash of environment variables
def select_env_by_regex regex
envs = Beaker::Options::OptionsHash.new
ENV.each_pair do | k, v |
if k.to_s =~ /#{regex}/
envs[k] = v
end
end
envs
end
# Takes an environment_spec and searches the processes environment variables accordingly
#
# @param [Hash{Symbol=>Array,String}] env_var_spec the spec of what env vars to search for
#
# @return [Hash] Found environment values
def collect_env_vars( env_var_spec )
env_var_spec.inject({}) do |memo, key_value|
key, value = key_value[0], key_value[1]
set_env_var = Array(value).detect {|possible_variable| ENV[possible_variable] }
memo[key] = ENV[set_env_var] if set_env_var
memo
end
end
# Takes a hash where the values are found environment configuration values
# and formats them to appropriate Beaker configuration values
#
# @param [Hash{Symbol=>String}] found_env_vars Environment variables to munge
#
# @return [Hash] Environment config values formatted appropriately
def format_found_env_vars( found_env_vars )
found_env_vars[:consoleport] &&= found_env_vars[:consoleport].to_i
found_env_vars[:type] = found_env_vars[:is_pe] == 'true' || found_env_vars[:is_pe] == 'yes' ? 'pe' : nil
found_env_vars[:pe_version_file_win] = found_env_vars[:pe_version_file]
found_env_vars
end
# Generates an OptionsHash of the environment variables of interest to Beaker
#
# @return [OptionsHash] The supported environment variables in an OptionsHash,
# empty or nil environment variables are removed from the OptionsHash
def calculate_env_vars
found = Beaker::Options::OptionsHash.new
found = found.merge(format_found_env_vars( collect_env_vars( ENVIRONMENT_SPEC )))
found[:answers] = select_env_by_regex('\\Aq_')
found.delete_if {|key, value| value.nil? or value.empty? }
found
end
# Return an OptionsHash of environment variables used in this run of Beaker
#
# @return [OptionsHash] The supported environment variables in an OptionsHash,
# empty or nil environment variables are removed from the OptionsHash
def env_vars
@env ||= calculate_env_vars
end
# Generates an OptionsHash of preset values for arguments supported by Beaker
#
# @return [OptionsHash] The supported arguments in an OptionsHash
def presets
h = Beaker::Options::OptionsHash.new
h.merge({
:project => 'Beaker',
:department => ENV['USER'] || ENV['USERNAME'] || 'unknown',
:validate => true,
:jenkins_build_url => nil,
:log_level => 'verbose',
:trace_limit => 10,
:"master-start-curl-retries" => 120,
:options_file => nil,
:type => 'pe',
:provision => true,
:preserve_hosts => 'never',
:root_keys => false,
:quiet => false,
:project_root => File.expand_path(File.join(File.dirname(__FILE__), "../")),
:xml_dir => 'junit',
:xml_file => 'beaker_junit.xml',
:xml_stylesheet => 'junit.xsl',
:log_dir => 'log',
:color => true,
:dry_run => false,
:timeout => 300,
:fail_mode => 'slow',
:timesync => false,
:disable_iptables => true,
:repo_proxy => false,
:package_proxy => false,
:add_el_extras => false,
:release_apt_repo_url => "http://apt.puppetlabs.com",
:release_yum_repo_url => "http://yum.puppetlabs.com",
:dev_builds_url => "http://builds.delivery.puppetlabs.net",
:epel_url => "http://mirrors.kernel.org/fedora-epel",
:epel_arch => "i386",
:epel_6_pkg => "epel-release-6-8.noarch.rpm",
:epel_5_pkg => "epel-release-5-4.noarch.rpm",
:consoleport => 443,
:pe_dir => '/opt/enterprise/dists',
:pe_version_file => 'LATEST',
:pe_version_file_win => 'LATEST-win',
:answers => {
:q_puppet_enterpriseconsole_auth_user_email => 'admin@example.com',
:q_puppet_enterpriseconsole_auth_password => '~!@#$%^*-/ aZ',
:q_puppet_enterpriseconsole_smtp_port => 25,
:q_puppet_enterpriseconsole_smtp_use_tls => 'n',
:q_verify_packages => 'y',
:q_puppetdb_password => '~!@#$%^*-/ aZ',
:q_puppetmaster_enterpriseconsole_port => 443,
:q_puppet_enterpriseconsole_auth_database_name => 'console_auth',
:q_puppet_enterpriseconsole_auth_database_user => 'mYu7hu3r',
:q_puppet_enterpriseconsole_database_name => 'console',
:q_puppet_enterpriseconsole_database_user => 'mYc0nS03u3r',
:q_database_root_password => '=ZYdjiP3jCwV5eo9s1MBd',
:q_database_root_user => 'pe-postgres',
:q_database_export_dir => '/tmp',
:q_puppetdb_database_name => 'pe-puppetdb',
:q_puppetdb_database_user => 'mYpdBu3r',
:q_database_port => 5432,
:q_puppetdb_port => 8081,
},
:dot_fog => File.join(ENV['HOME'], '.fog'),
:ec2_yaml => 'config/image_templates/ec2.yaml',
:help => false,
:collect_perf_data => false,
:ssh => {
:config => false,
:paranoid => false,
:timeout => 300,
:auth_methods => ["publickey"],
:port => 22,
:forward_agent => true,
:keys => ["#{ENV['HOME']}/.ssh/id_rsa"],
:user_known_hosts_file => "#{ENV['HOME']}/.ssh/known_hosts",
}
})
end
end
end
end
| 1 | 7,500 | is this the intended behavior now? | voxpupuli-beaker | rb |
@@ -27,6 +27,5 @@ public class TestDutchIJ extends StemmerTestBase {
public void testStemming() {
assertStemsTo("ijs", "ijs");
assertStemsTo("IJs", "ijs");
- assertStemsTo("Ijs");
}
} | 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.analysis.hunspell;
import org.junit.BeforeClass;
public class TestDutchIJ extends StemmerTestBase {
@BeforeClass
public static void beforeClass() throws Exception {
init("IJ.aff", "IJ.dic");
}
public void testStemming() {
assertStemsTo("ijs", "ijs");
assertStemsTo("IJs", "ijs");
assertStemsTo("Ijs");
}
}
| 1 | 40,288 | Hunspell/C++ stems that a bit differently from Lucene, but in a controversial way, so I removed the check instead of changing the expectation | apache-lucene-solr | java |
@@ -172,7 +172,7 @@ func (o *opt) close() {
func (o *opt) runInitOnce() {
o.initOnce.Do(func() {
o.clock = &libkbfs.TestClock{}
- o.clock.Set(time.Unix(0, 0))
+ o.clock.Set(time.Unix(1, 0))
o.users = o.engine.InitTest(o.ver, o.blockSize,
o.blockChangeSize, o.batchSize, o.bwKBps, o.timeout, o.usernames,
o.teams, o.implicitTeams, o.clock, o.journal) | 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 test
import (
"bytes"
"fmt"
"path"
"reflect"
"regexp"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfsmd"
"github.com/keybase/kbfs/libfs"
"github.com/keybase/kbfs/libkbfs"
"github.com/keybase/kbfs/tlf"
)
type m map[string]string
const (
alice = username("alice")
bob = username("bob")
charlie = username("charlie")
eve = username("eve")
)
type opt struct {
ver kbfsmd.MetadataVer
usernames []libkb.NormalizedUsername
teams teamMap
implicitTeams teamMap
tlfName string
expectedCanonicalTlfName string
tlfType tlf.Type
tlfRevision kbfsmd.Revision
users map[libkb.NormalizedUsername]User
stallers map[libkb.NormalizedUsername]*libkbfs.NaïveStaller
tb testing.TB
initOnce sync.Once
engine Engine
blockSize int64
blockChangeSize int64
batchSize int
bwKBps int
timeout time.Duration
clock *libkbfs.TestClock
isParallel bool
journal bool
}
// run{Test,Benchmark}OverMetadataVers are copied from
// libkbfs/bare_root_metadata_test.go, so as to avoid having libkbfs
// depend on testing.
// Also copy testMetadataVers, so that we can set it independently
// from libkbfs tests.
var testMetadataVers = []kbfsmd.MetadataVer{
kbfsmd.InitialExtraMetadataVer, kbfsmd.ImplicitTeamsVer,
}
// runTestOverMetadataVers runs the given test function over all
// metadata versions to test.
func runTestOverMetadataVers(
t *testing.T, f func(t *testing.T, ver kbfsmd.MetadataVer)) {
for _, ver := range testMetadataVers {
ver := ver // capture range variable.
t.Run(ver.String(), func(t *testing.T) {
// Don't do t.Parallel() for now, as FUSE DSL
// tests might not like it.
f(t, ver)
})
}
}
// runBenchmarkOverMetadataVers runs the given benchmark function over
// all metadata versions to test.
func runBenchmarkOverMetadataVers(
b *testing.B, f func(b *testing.B, ver kbfsmd.MetadataVer)) {
for _, ver := range testMetadataVers {
ver := ver // capture range variable.
b.Run(ver.String(), func(b *testing.B) {
f(b, ver)
})
}
}
func runOneTestOrBenchmark(
tb testing.TB, ver kbfsmd.MetadataVer, actions ...optionOp) {
o := &opt{
ver: ver,
tb: tb,
engine: createEngine(tb),
}
defer o.close()
for _, omod := range actions {
omod(o)
}
}
func test(t *testing.T, actions ...optionOp) {
runTestOverMetadataVers(t, func(t *testing.T, ver kbfsmd.MetadataVer) {
runOneTestOrBenchmark(t, ver, actions...)
})
}
func benchmark(b *testing.B, tb testing.TB, actions ...optionOp) {
runBenchmarkOverMetadataVers(
b, func(b *testing.B, ver kbfsmd.MetadataVer) {
runOneTestOrBenchmark(tb, ver, actions...)
})
}
func parallel(actions ...optionOp) optionOp {
return func(o *opt) {
o.isParallel = true
wg := &sync.WaitGroup{}
for _, omod := range actions {
wg.Add(1)
go func(omod optionOp) {
omod(o)
wg.Done()
}(omod)
}
wg.Wait()
}
}
func sequential(actions ...optionOp) optionOp {
return func(o *opt) {
for _, omod := range actions {
omod(o)
}
}
}
type errorList struct {
el []error
}
func (el errorList) Error() string {
return fmt.Sprintf("%v", el.el)
}
func (o *opt) close() {
var el []error
// Make sure Shutdown is called properly for every user, even
// if any of the calls fail.
for _, user := range o.users {
err := o.engine.Shutdown(user)
if err != nil {
el = append(el, err)
}
}
var err error
if len(el) > 0 {
err = errorList{el}
}
o.expectSuccess("Shutdown", err)
}
func (o *opt) runInitOnce() {
o.initOnce.Do(func() {
o.clock = &libkbfs.TestClock{}
o.clock.Set(time.Unix(0, 0))
o.users = o.engine.InitTest(o.ver, o.blockSize,
o.blockChangeSize, o.batchSize, o.bwKBps, o.timeout, o.usernames,
o.teams, o.implicitTeams, o.clock, o.journal)
o.stallers = o.makeStallers()
})
}
func (o *opt) makeStallers() (
stallers map[libkb.NormalizedUsername]*libkbfs.NaïveStaller) {
stallers = make(map[libkb.NormalizedUsername]*libkbfs.NaïveStaller)
for username, user := range o.users {
stallers[username] = o.engine.MakeNaïveStaller(user)
}
return stallers
}
func ntimesString(n int, s string) string {
var bs bytes.Buffer
for i := 0; i < n; i++ {
bs.WriteString(s)
}
return bs.String()
}
type optionOp func(*opt)
func blockSize(n int64) optionOp {
return func(o *opt) {
o.blockSize = n
}
}
func blockChangeSize(n int64) optionOp {
return func(o *opt) {
o.blockChangeSize = n
}
}
func batchSize(n int) optionOp {
return func(o *opt) {
o.batchSize = n
}
}
func bandwidth(n int) optionOp {
return func(o *opt) {
o.bwKBps = n
}
}
func opTimeout(n time.Duration) optionOp {
return func(o *opt) {
o.timeout = n
}
}
func journal() optionOp {
return func(o *opt) {
o.journal = true
}
}
func skip(implementation, reason string) optionOp {
return func(o *opt) {
if o.engine.Name() == implementation {
o.tb.Skip(reason)
}
}
}
func users(ns ...username) optionOp {
return func(o *opt) {
var a []string
for _, u := range ns {
username := libkb.NewNormalizedUsername(string(u))
o.usernames = append(o.usernames, username)
a = append(a, string(username))
}
// Default to the private TLF shared by all the users.
sort.Strings(a)
tlfName := strings.Join(a, ",")
inPrivateTlf(tlfName)(o)
}
}
func team(teamName libkb.NormalizedUsername, writers string,
readers string) optionOp {
return func(o *opt) {
if o.ver < kbfsmd.SegregatedKeyBundlesVer {
o.tb.Skip("mdv2 doesn't support teams")
}
if o.teams == nil {
o.teams = make(teamMap)
}
var writerNames, readerNames []libkb.NormalizedUsername
for _, w := range strings.Split(writers, ",") {
writerNames = append(writerNames, libkb.NormalizedUsername(w))
}
if readers != "" {
for _, r := range strings.Split(readers, ",") {
readerNames = append(readerNames, libkb.NormalizedUsername(r))
}
}
o.teams[teamName] = teamMembers{writerNames, readerNames}
}
}
func implicitTeam(writers string, readers string) optionOp {
return func(o *opt) {
if o.ver < kbfsmd.ImplicitTeamsVer {
o.tb.Skip("mdv2 doesn't support teams")
}
if o.implicitTeams == nil {
o.implicitTeams = make(teamMap)
}
var writerNames, readerNames []libkb.NormalizedUsername
for _, w := range strings.Split(writers, ",") {
writerNames = append(writerNames, libkb.NormalizedUsername(w))
}
isPublic := false
if readers != "" {
for _, r := range strings.Split(readers, ",") {
readerNames = append(readerNames, libkb.NormalizedUsername(r))
}
isPublic = len(readerNames) == 1 && readers == "public"
}
var teamName tlf.CanonicalName
if isPublic {
teamName = tlf.MakeCanonicalName(
writerNames, nil, nil, nil, nil)
} else {
teamName = tlf.MakeCanonicalName(
writerNames, nil, readerNames, nil, nil)
}
o.implicitTeams[libkb.NormalizedUsername(teamName)] =
teamMembers{writerNames, readerNames}
}
}
func inPrivateTlf(name string) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = name
o.tlfType = tlf.Private
}
}
func inPrivateTlfAtRevision(name string, rev kbfsmd.Revision) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = name
o.tlfType = tlf.Private
o.tlfRevision = rev
}
}
func inPrivateTlfNonCanonical(name, expectedCanonicalName string) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = expectedCanonicalName
o.tlfType = tlf.Private
}
}
func inPublicTlf(name string) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = name
o.tlfType = tlf.Public
}
}
func inPublicTlfNonCanonical(name, expectedCanonicalName string) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = expectedCanonicalName
o.tlfType = tlf.Public
}
}
func inSingleTeamTlf(name string) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = name
o.tlfType = tlf.SingleTeam
}
}
func inSingleTeamNonCanonical(name, expectedCanonicalName string) optionOp {
return func(o *opt) {
o.tlfName = name
o.expectedCanonicalTlfName = expectedCanonicalName
o.tlfType = tlf.SingleTeam
}
}
func addNewAssertion(oldAssertion, newAssertion string) optionOp {
return func(o *opt) {
o.tb.Logf("addNewAssertion: %q -> %q", oldAssertion, newAssertion)
for _, u := range o.users {
err := o.engine.AddNewAssertion(u, oldAssertion, newAssertion)
o.expectSuccess("addNewAssertion", err)
}
}
}
func changeTeamName(oldName, newName string) optionOp {
return func(o *opt) {
o.teams[libkb.NormalizedUsername(newName)] =
o.teams[libkb.NormalizedUsername(oldName)]
delete(o.teams, libkb.NormalizedUsername(oldName))
o.tb.Logf("changeTeamName: %q -> %q", oldName, newName)
for _, u := range o.users {
err := o.engine.ChangeTeamName(u, oldName, newName)
o.expectSuccess("changeTeamName", err)
}
}
}
type fileOp struct {
operation func(*ctx) error
flags fileOpFlags
description string
}
type fileOpFlags uint32
const (
Defaults = fileOpFlags(0)
IsInit = fileOpFlags(1)
)
type ctx struct {
*opt
user User
username libkb.NormalizedUsername
rootNode Node
noSyncInit bool
staller *libkbfs.NaïveStaller
}
func runFileOpHelper(c *ctx, fop fileOp) (string, error) {
desc := fmt.Sprintf("(%s) %s", c.username, fop.description)
c.tb.Log(desc)
err := fop.operation(c)
if err != nil {
c.tb.Logf("%s failed with %s", desc, err)
}
return desc, err
}
func runFileOp(c *ctx, fop fileOp) (string, error) {
if c.rootNode == nil && fop.flags&IsInit == 0 {
initOp := initRoot()
desc, err := runFileOpHelper(c, initOp)
if err != nil {
desc = fmt.Sprintf("%s for %s", desc, fop.description)
return desc, err
}
}
return runFileOpHelper(c, fop)
}
func expectError(op fileOp, reasonPrefix string) fileOp {
return fileOp{func(c *ctx) error {
_, err := runFileOp(c, op)
if err == nil {
return fmt.Errorf("Didn't get expected error (success while expecting failure): %q", reasonPrefix)
}
// Real filesystems don't give us the exact errors we wish for.
if c.engine.Name() == "libkbfs" &&
!strings.HasPrefix(err.Error(), reasonPrefix) {
return fmt.Errorf("Got the wrong error: expected prefix %q, got %q", reasonPrefix, err.Error())
}
return nil
}, IsInit, /* So that we can use expectError with e.g. initRoot(). */
fmt.Sprintf("expectError(%s, %s)",
op.description, reasonPrefix)}
}
func noSync() fileOp {
return fileOp{func(c *ctx) error {
c.noSyncInit = true
return nil
}, IsInit, "noSync()"}
}
func (o *opt) expectSuccess(reason string, err error) {
if err != nil {
if o.isParallel {
// FailNow/Fatalf can only be called from the goroutine running the Test
// function. In parallel tests, this is not always true. So we use Errorf
// to mark the test as failed without an implicit FailNow.
o.tb.Errorf("Error %s: %v", reason, err)
} else {
o.tb.Fatalf("Error %s: %v", reason, err)
}
}
}
func addTime(d time.Duration) fileOp {
return fileOp{func(c *ctx) error {
c.clock.Add(d)
return nil
}, Defaults, fmt.Sprintf("addTime(%s)", d)}
}
func as(user username, fops ...fileOp) optionOp {
return func(o *opt) {
o.tb.Log("as:", user)
o.runInitOnce()
u := libkb.NewNormalizedUsername(string(user))
ctx := &ctx{
opt: o,
user: o.users[u],
username: u,
staller: o.stallers[u],
}
for _, fop := range fops {
desc, err := runFileOp(ctx, fop)
ctx.expectSuccess(desc, err)
}
// Sync everything to disk after this round of operations.
if !ctx.noSyncInit {
err := ctx.engine.SyncAll(ctx.user, ctx.tlfName, ctx.tlfType)
ctx.expectSuccess("SyncAll", err)
}
}
}
// initRoot initializes the root for an invocation of as(). Usually
// not called directly.
func initRoot() fileOp {
return fileOp{func(c *ctx) error {
if !c.noSyncInit {
// Do this before GetRootDir so that we pick
// up any TLF name changes.
err := c.engine.SyncFromServer(c.user, c.tlfName, c.tlfType)
if err != nil {
return err
}
}
var root Node
var err error
if c.tlfRevision == kbfsmd.RevisionUninitialized {
root, err = c.engine.GetRootDir(
c.user, c.tlfName, c.tlfType, c.expectedCanonicalTlfName)
} else {
root, err = c.engine.GetRootDirAtRevision(
c.user, c.tlfName, c.tlfType, c.tlfRevision,
c.expectedCanonicalTlfName)
}
if err != nil {
return err
}
c.rootNode = root
return nil
}, IsInit, "initRoot()"}
}
func custom(f func(func(fileOp) error) error) fileOp {
return fileOp{func(c *ctx) error {
return f(func(fop fileOp) error { return fop.operation(c) })
}, Defaults, "custom()"}
}
func mkdir(name string) fileOp {
return fileOp{func(c *ctx) error {
_, _, err := c.getNode(name, createDir, resolveAllSyms)
return err
}, Defaults, fmt.Sprintf("mkdir(%s)", name)}
}
func write(name string, contents string) fileOp {
return writeBS(name, []byte(contents))
}
func writeBS(name string, contents []byte) fileOp {
return pwriteBS(name, contents, 0)
}
func pwriteBS(name string, contents []byte, off int64) fileOp {
return pwriteBSSync(name, contents, off, true)
}
func pwriteBSSync(name string, contents []byte, off int64, sync bool) fileOp {
return fileOp{func(c *ctx) error {
f, _, err := c.getNode(name, createFile, resolveAllSyms)
if err != nil {
return err
}
return c.engine.WriteFile(c.user, f, contents, off, sync)
}, Defaults, fmt.Sprintf("pwriteBSSync(%s, %d bytes, off=%d, sync=%t)",
name, len(contents), off, sync)}
}
func truncate(name string, size uint64) fileOp {
return fileOp{func(c *ctx) error {
f, _, err := c.getNode(name, createFile, resolveAllSyms)
if err != nil {
return err
}
return c.engine.TruncateFile(c.user, f, size, true)
}, Defaults, fmt.Sprintf("truncate(%s, %d)", name, size)}
}
func read(name string, contents string) fileOp {
return preadBS(name, []byte(contents), 0)
}
func preadBS(name string, contents []byte, at int64) fileOp {
return fileOp{func(c *ctx) error {
file, _, err := c.getNode(name, noCreate, resolveAllSyms)
if err != nil {
return err
}
bs := make([]byte, len(contents))
l, err := c.engine.ReadFile(c.user, file, at, bs)
if err != nil {
return err
}
bs = bs[:l]
if !bytes.Equal(bs, contents) {
return fmt.Errorf("Read (name=%s) got=%d, expected=%d bytes: contents=%s differ from expected=%s", name, len(bs), len(contents), bs, contents)
}
return nil
}, Defaults, fmt.Sprintf("preadBS(%s, %d bytes, at=%d)",
name, len(contents), at)}
}
func exists(filename string) fileOp {
return fileOp{func(c *ctx) error {
_, _, err := c.getNode(filename, noCreate, resolveAllSyms)
return err
}, Defaults, fmt.Sprintf("exists(%s)", filename)}
}
func notExists(filename string) fileOp {
return fileOp{func(c *ctx) error {
_, _, err := c.getNode(filename, noCreate, resolveAllSyms)
if err == nil {
return fmt.Errorf("File that should not exist exists: %q", filename)
}
return nil
}, Defaults, fmt.Sprintf("notExists(%s)", filename)}
}
func mkfileexcl(name string) fileOp {
return fileOp{func(c *ctx) error {
_, _, err := c.getNode(name, createFileExcl, resolveAllSyms)
return err
}, Defaults, fmt.Sprintf("mkfileexcl(%s)", name)}
}
func mkfile(name string, contents string) fileOp {
return fileOp{func(c *ctx) error {
f, wasCreated, err := c.getNode(name, createFile, resolveAllSyms)
if err != nil {
return err
}
if !wasCreated {
return fmt.Errorf("File %s already existed when mkfile was called",
name)
}
// Skip the write if the requested contents is empty.
if len(contents) == 0 {
return nil
}
return c.engine.WriteFile(c.user, f, []byte(contents), 0, true)
}, Defaults, fmt.Sprintf("mkfile(%s, %d bytes)", name, len(contents))}
}
func link(fromName, toPath string) fileOp {
return fileOp{func(c *ctx) error {
dir, name := path.Split(fromName)
parent, _, err := c.getNode(dir, noCreate, resolveAllSyms)
if err != nil {
return err
}
return c.engine.CreateLink(c.user, parent, name, toPath)
}, Defaults, fmt.Sprintf("link(%s => %s)", fromName, toPath)}
}
func setex(filepath string, ex bool) fileOp {
return fileOp{func(c *ctx) error {
file, _, err := c.getNode(filepath, noCreate, resolveAllSyms)
if err != nil {
return err
}
return c.engine.SetEx(c.user, file, ex)
}, Defaults, fmt.Sprintf("setex(%s, %t)", filepath, ex)}
}
func setmtime(filepath string, mtime time.Time) fileOp {
return fileOp{func(c *ctx) error {
file, _, err := c.getNode(filepath, noCreate, dontResolveFinalSym)
if err != nil {
return err
}
return c.engine.SetMtime(c.user, file, mtime)
}, Defaults, fmt.Sprintf("setmtime(%s, %s)", filepath, mtime)}
}
func mtime(filepath string, expectedMtime time.Time) fileOp {
return fileOp{func(c *ctx) error {
file, _, err := c.getNode(filepath, noCreate, dontResolveFinalSym)
if err != nil {
return err
}
mtime, err := c.engine.GetMtime(c.user, file)
if err != nil {
return err
}
if !libfs.TimeEqual(mtime, expectedMtime) {
return fmt.Errorf("Mtime (name=%s) got=%s, expected=%s", filepath,
mtime, expectedMtime)
}
return nil
}, Defaults, fmt.Sprintf("mtime(%s, %s)", filepath, expectedMtime)}
}
func rm(filepath string) fileOp {
return fileOp{func(c *ctx) error {
dir, name := path.Split(filepath)
parent, _, err := c.getNode(dir, noCreate, resolveAllSyms)
if err != nil {
return err
}
return c.engine.RemoveEntry(c.user, parent, name)
}, Defaults, fmt.Sprintf("rm(%s)", filepath)}
}
func rmdir(filepath string) fileOp {
return fileOp{func(c *ctx) error {
dir, name := path.Split(filepath)
parent, _, err := c.getNode(dir, noCreate, resolveAllSyms)
if err != nil {
return err
}
return c.engine.RemoveDir(c.user, parent, name)
}, Defaults, fmt.Sprintf("rmdir(%s)", filepath)}
}
func rename(src, dst string) fileOp {
return fileOp{func(c *ctx) error {
sdir, sname := path.Split(src)
sparent, _, err := c.getNode(sdir, noCreate, resolveAllSyms)
if err != nil {
return err
}
ddir, dname := path.Split(dst)
dparent, _, err := c.getNode(ddir, createDir, resolveAllSyms)
if err != nil {
return err
}
return c.engine.Rename(c.user, sparent, sname, dparent, dname)
}, Defaults, fmt.Sprintf("rename(%s => %s)", src, dst)}
}
func disableUpdates() fileOp {
return fileOp{func(c *ctx) error {
err := c.engine.SyncFromServer(c.user, c.tlfName, c.tlfType)
if err != nil {
return err
}
return c.engine.DisableUpdatesForTesting(c.user, c.tlfName, c.tlfType)
}, IsInit, "disableUpdates()"}
}
func stallDelegateOnMDPut() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDPut, 100, true)
return nil
}, Defaults, "stallDelegateOnMDPut()"}
}
func stallOnMDPut() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDPut, 100, false)
return nil
}, Defaults, "stallOnMDPut()"}
}
func waitForStalledMDPut() fileOp {
return fileOp{func(c *ctx) error {
c.staller.WaitForStallMDOp(libkbfs.StallableMDPut)
return nil
}, IsInit, "waitForStalledMDPut()"}
}
func unstallOneMDPut() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UnstallOneMDOp(libkbfs.StallableMDPut)
return nil
}, IsInit, "unstallOneMDPut()"}
}
func undoStallOnMDPut() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UndoStallMDOp(libkbfs.StallableMDPut)
return nil
}, IsInit, "undoStallOnMDPut()"}
}
func stallDelegateOnMDGetForTLF() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDGetForTLF, 100, true)
return nil
}, Defaults, "stallDelegateOnMDGetForTLF()"}
}
func stallOnMDGetForTLF() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDGetForTLF, 100, false)
return nil
}, Defaults, "stallOnMDGetForTLF()"}
}
func waitForStalledMDGetForTLF() fileOp {
return fileOp{func(c *ctx) error {
c.staller.WaitForStallMDOp(libkbfs.StallableMDGetForTLF)
return nil
}, IsInit, "waitForStalledMDGetForTLF()"}
}
func unstallOneMDGetForTLF() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UnstallOneMDOp(libkbfs.StallableMDGetForTLF)
return nil
}, IsInit, "unstallOneMDGetForTLF()"}
}
func undoStallOnMDGetForTLF() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UndoStallMDOp(libkbfs.StallableMDGetForTLF)
return nil
}, IsInit, "undoStallOnMDGetForTLF()"}
}
func stallDelegateOnMDGetRange() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDGetRange, 100, true)
return nil
}, Defaults, "stallDelegateOnMDGetRange()"}
}
func stallOnMDGetRange() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDGetRange, 100, false)
return nil
}, Defaults, "stallOnMDGetRange()"}
}
func waitForStalledMDGetRange() fileOp {
return fileOp{func(c *ctx) error {
c.staller.WaitForStallMDOp(libkbfs.StallableMDGetRange)
return nil
}, IsInit, "waitForStalledMDGetRange()"}
}
func unstallOneMDGetRange() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UnstallOneMDOp(libkbfs.StallableMDGetRange)
return nil
}, IsInit, "unstallOneMDGetRange()"}
}
func undoStallOnMDGetRange() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UndoStallMDOp(libkbfs.StallableMDGetRange)
return nil
}, IsInit, "undoStallOnMDGetRange()"}
}
func stallDelegateOnMDResolveBranch() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDResolveBranch, 100, true)
return nil
}, Defaults, "stallDelegateOnMDResolveBranch()"}
}
func stallOnMDResolveBranch() fileOp {
return fileOp{func(c *ctx) error {
// TODO: Allow test to pass in a more precise maxStalls limit.
c.staller.StallMDOp(libkbfs.StallableMDResolveBranch, 100, false)
return nil
}, Defaults, "stallOnMDResolveBranch()"}
}
func waitForStalledMDResolveBranch() fileOp {
return fileOp{func(c *ctx) error {
c.staller.WaitForStallMDOp(libkbfs.StallableMDResolveBranch)
return nil
}, IsInit, "waitForStalledMDResolveBranch()"}
}
func unstallOneMDResolveBranch() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UnstallOneMDOp(libkbfs.StallableMDResolveBranch)
return nil
}, IsInit, "unstallOneMDResolveBranch()"}
}
func undoStallOnMDResolveBranch() fileOp {
return fileOp{func(c *ctx) error {
c.staller.UndoStallMDOp(libkbfs.StallableMDResolveBranch)
return nil
}, IsInit, "undoStallOnMDResolveBranch()"}
}
func reenableUpdates() fileOp {
return fileOp{func(c *ctx) error {
err := c.engine.ReenableUpdates(c.user, c.tlfName, c.tlfType)
if err != nil {
return err
}
return c.engine.SyncFromServer(c.user, c.tlfName, c.tlfType)
}, IsInit, "reenableUpdates()"}
}
func reenableUpdatesNoSync() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.ReenableUpdates(c.user, c.tlfName, c.tlfType)
}, IsInit, "reenableUpdatesNoSync()"}
}
func forceQuotaReclamation() fileOp {
return fileOp{func(c *ctx) error {
err := c.engine.ForceQuotaReclamation(c.user, c.tlfName, c.tlfType)
if err != nil {
return err
}
// Wait for QR to finish.
return c.engine.SyncFromServer(c.user, c.tlfName, c.tlfType)
}, IsInit, "forceQuotaReclamation()"}
}
func rekey() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.Rekey(c.user, c.tlfName, c.tlfType)
}, IsInit, "rekey()"}
}
func enableJournal() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.EnableJournal(c.user, c.tlfName, c.tlfType)
}, IsInit, "enableJournal()"}
}
func pauseJournal() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.PauseJournal(c.user, c.tlfName, c.tlfType)
}, IsInit, "pauseJournal()"}
}
func resumeJournal() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.ResumeJournal(c.user, c.tlfName, c.tlfType)
}, IsInit, "resumeJournal()"}
}
func flushJournal() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.FlushJournal(c.user, c.tlfName, c.tlfType)
}, IsInit, "flushJournal()"}
}
func checkUnflushedPaths(expectedPaths []string) fileOp {
return fileOp{func(c *ctx) error {
paths, err := c.engine.UnflushedPaths(c.user, c.tlfName, c.tlfType)
if err != nil {
return err
}
sort.Strings(expectedPaths)
sort.Strings(paths)
if !reflect.DeepEqual(expectedPaths, paths) {
return fmt.Errorf("Expected unflushed paths %v, got %v",
expectedPaths, paths)
}
return nil
}, IsInit, fmt.Sprintf("checkUnflushedPaths(%s)", expectedPaths)}
}
func checkPrevRevisions(filepath string, counts []uint8) fileOp {
return fileOp{func(c *ctx) error {
file, _, err := c.getNode(filepath, noCreate, resolveAllSyms)
if err != nil {
return err
}
pr, err := c.engine.GetPrevRevisions(c.user, file)
if err != nil {
return err
}
if len(pr) != len(counts) {
return fmt.Errorf("Wrong number of prev revisions: %v", pr)
}
for i, c := range counts {
if c != pr[i].Count {
return fmt.Errorf("Unexpected prev revision counts: %v", pr)
}
}
return nil
}, Defaults, fmt.Sprintf("prevRevisions(%s, %v)", filepath, counts)}
}
type expectedEdit struct {
tlfName string
tlfType keybase1.FolderType
writer string
files []string
}
func checkUserEditHistory(expectedEdits []expectedEdit) fileOp {
return fileOp{func(c *ctx) error {
history, err := c.engine.UserEditHistory(c.user)
if err != nil {
return err
}
// Convert the history to expected edits.
hEdits := make([]expectedEdit, len(history))
for i, h := range history {
if len(h.History) != 1 {
return fmt.Errorf(
"Unexpected history of size %d: %#v", len(h.History), h)
}
hEdits[i].tlfName = h.Folder.Name
hEdits[i].tlfType = h.Folder.FolderType
hEdits[i].writer = h.History[0].WriterName
for _, we := range h.History[0].Edits {
hEdits[i].files = append(hEdits[i].files, we.Filename)
}
}
if !reflect.DeepEqual(expectedEdits, hEdits) {
return fmt.Errorf("Expected edit history %v, got %v",
expectedEdits, hEdits)
}
return nil
}, Defaults, "checkUserEditHistory()"}
}
func checkDirtyPaths(expectedPaths []string) fileOp {
return fileOp{func(c *ctx) error {
paths, err := c.engine.DirtyPaths(c.user, c.tlfName, c.tlfType)
if err != nil {
return err
}
sort.Strings(expectedPaths)
sort.Strings(paths)
if !reflect.DeepEqual(expectedPaths, paths) {
return fmt.Errorf("Expected dirty paths %v, got %v",
expectedPaths, paths)
}
return nil
}, IsInit, fmt.Sprintf("checkDirtyPaths(%s)", expectedPaths)}
}
func disablePrefetch() fileOp {
return fileOp{func(c *ctx) error {
return c.engine.TogglePrefetch(c.user, false)
}, IsInit, "disablePrefetch()"}
}
func lsfavoritesOp(c *ctx, expected []string, t tlf.Type) error {
favorites, err := c.engine.GetFavorites(c.user, t)
if err != nil {
return err
}
c.tb.Log("lsfavorites", t, "=>", favorites)
expectedMap := make(map[string]bool)
for _, f := range expected {
if !favorites[f] {
return fmt.Errorf("Missing favorite %s", f)
}
expectedMap[f] = true
}
for f := range favorites {
if !expectedMap[f] {
return fmt.Errorf("Unexpected favorite %s", f)
}
}
return nil
}
func lspublicfavorites(contents []string) fileOp {
return fileOp{func(c *ctx) error {
return lsfavoritesOp(c, contents, tlf.Public)
}, Defaults, fmt.Sprintf("lspublicfavorites(%s)", contents)}
}
func lsprivatefavorites(contents []string) fileOp {
return fileOp{func(c *ctx) error {
return lsfavoritesOp(c, contents, tlf.Private)
}, Defaults, fmt.Sprintf("lsprivatefavorites(%s)", contents)}
}
func lsdir(name string, contents m) fileOp {
return fileOp{func(c *ctx) error {
folder, _, err := c.getNode(name, noCreate, resolveAllSyms)
if err != nil {
return err
}
entries, err := c.engine.GetDirChildrenTypes(c.user, folder)
if err != nil {
return err
}
c.tb.Log("lsdir =>", entries)
outer:
for restr, ty := range contents {
re := regexp.MustCompile(restr)
for node, ty2 := range entries {
// Windows does not mark "executable" bits in any way.
if re.MatchString(node) && (ty == ty2 ||
(c.engine.Name() == "dokan" && ty == "EXEC" && ty2 == "FILE")) {
delete(entries, node)
continue outer
}
}
return fmt.Errorf("%s of type %s not found", restr, ty)
}
// and make sure everything is matched
for node, ty := range entries {
return fmt.Errorf("unexpected %s of type %s found in %s", node, ty, name)
}
return nil
}, Defaults, fmt.Sprintf("lsdir(%s, %d bytes)", name, len(contents))}
}
// createType specifies whether getNode should create any nodes that
// don't exist.
type createType int
const (
noCreate createType = iota
createDir
createFile
createFileExcl
)
func (c createType) String() string {
switch c {
case noCreate:
return "noCreate"
case createDir:
return "createDir"
case createFile:
return "createFile"
case createFileExcl:
return "createFileExcl"
default:
return fmt.Sprintf("unknownCreateType:%d", c)
}
}
// symBehavior specifies what getNode should do with symlinks.
type symBehavior int
const (
resolveAllSyms symBehavior = iota
dontResolveFinalSym
)
func (c *ctx) getNode(filepath string, create createType, sym symBehavior) (
Node, bool, error) {
if filepath == "" || filepath == "/" {
return c.rootNode, false, nil
}
if filepath[len(filepath)-1] == '/' {
filepath = filepath[:len(filepath)-1]
}
components := strings.Split(filepath, "/")
c.tb.Log("getNode:", filepath, create, components, len(components))
var symPath string
var err error
var node, parent Node
parent = c.rootNode
wasCreated := false
for i, name := range components {
node, symPath, err = c.engine.Lookup(c.user, parent, name)
c.tb.Log("getNode:", i, name, node, symPath, err)
if i+1 == len(components) { // last element in path
switch {
case err == nil:
if create == createFileExcl {
return nil, false, libkbfs.NameExistsError{}
}
case create == createFileExcl:
c.tb.Log("getNode: CreateFileExcl")
node, err = c.engine.CreateFileExcl(c.user, parent, name)
wasCreated = true
case create == createFile:
c.tb.Log("getNode: CreateFile")
node, err = c.engine.CreateFile(c.user, parent, name)
wasCreated = true
case create == createDir:
c.tb.Log("getNode: CreateDir")
node, err = c.engine.CreateDir(c.user, parent, name)
wasCreated = true
case create == noCreate:
// let it error!
default:
panic("unreachable")
}
} else { // intermediate element in path
if err != nil && create != noCreate {
c.tb.Log("getNode: CreateDir")
node, err = c.engine.CreateDir(c.user, parent, name)
wasCreated = true
} // otherwise let it error!
}
if err != nil {
return nil, false, err
}
parent = node
// If this is a symlink, and either we're supposed to resolve
// all symlinks or this isn't the final one in the path, then
// go ahead and recurse on the resolved path.
if len(symPath) > 0 &&
(sym == resolveAllSyms || i != len(components)-1) {
var tmp []string
if symPath[0] == '/' {
tmp = []string{symPath}
} else {
tmp = components[:i]
tmp = append(tmp, symPath)
}
tmp = append(tmp, components[i+1:]...)
newpath := path.Clean(path.Join(tmp...))
c.tb.Log("getNode: symlink ", symPath, " redirecting to ", newpath)
return c.getNode(newpath, create, sym)
}
}
return node, wasCreated, nil
}
// crnameAtTime returns the name of a conflict file, at a given
// duration past the default time.
func crnameAtTime(path string, user username, d time.Duration) string {
cre := libkbfs.WriterDeviceDateConflictRenamer{}
return cre.ConflictRenameHelper(time.Unix(0, 0).Add(d), string(user),
"dev1", path)
}
// crnameAtTimeEsc returns the name of a conflict file with regular
// expression escapes, at a given duration past the default time.
func crnameAtTimeEsc(path string, user username, d time.Duration) string {
return regexp.QuoteMeta(crnameAtTime(path, user, d))
}
// crname returns the name of a conflict file.
func crname(path string, user username) string {
return crnameAtTime(path, user, 0)
}
// crnameEsc returns the name of a conflict file with regular expression escapes.
func crnameEsc(path string, user username) string {
return crnameAtTimeEsc(path, user, 0)
}
type silentBenchmark struct{ testing.TB }
func (silentBenchmark) Log(args ...interface{}) {}
func (silentBenchmark) Logf(format string, args ...interface{}) {}
| 1 | 19,942 | I'm curious why this is needed? | keybase-kbfs | go |
@@ -742,7 +742,7 @@ void Combat::doCombat(Creature* caster, Creature* target) const
}
*/
- if (caster && params.distanceEffect != CONST_ANI_NONE) {
+ if (caster && target && params.distanceEffect != CONST_ANI_NONE) {
addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect);
}
} | 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include "combat.h"
#include "game.h"
#include "weapons.h"
#include "configmanager.h"
#include "events.h"
extern Game g_game;
extern Weapons* g_weapons;
extern ConfigManager g_config;
extern Events* g_events;
namespace {
MatrixArea createArea(const std::vector<uint32_t>& vec, uint32_t rows)
{
uint32_t cols;
if (rows == 0) {
cols = 0;
} else {
cols = vec.size() / rows;
}
MatrixArea area{rows, cols};
uint32_t x = 0;
uint32_t y = 0;
for (uint32_t value : vec) {
if (value == 1 || value == 3) {
area(y, x) = true;
}
if (value == 2 || value == 3) {
area.setCenter(y, x);
}
++x;
if (cols == x) {
x = 0;
++y;
}
}
return area;
}
std::vector<Tile*> getList(const MatrixArea& area, const Position& targetPos, const Direction dir)
{
auto casterPos = getNextPosition(dir, targetPos);
std::vector<Tile*> vec;
auto center = area.getCenter();
Position tmpPos(targetPos.x - center.first, targetPos.y - center.second, targetPos.z);
for (uint32_t row = 0; row < area.getRows(); ++row, ++tmpPos.y) {
for (uint32_t col = 0; col < area.getCols(); ++col, ++tmpPos.x) {
if (area(row, col)) {
if (g_game.isSightClear(casterPos, tmpPos, true)) {
Tile* tile = g_game.map.getTile(tmpPos);
if (!tile) {
tile = new StaticTile(tmpPos.x, tmpPos.y, tmpPos.z);
g_game.map.setTile(tmpPos, tile);
}
vec.push_back(tile);
}
}
}
tmpPos.x -= area.getCols();
}
return vec;
}
std::vector<Tile*> getCombatArea(const Position& centerPos, const Position& targetPos, const AreaCombat* area)
{
if (targetPos.z >= MAP_MAX_LAYERS) {
return {};
}
if (area) {
return getList(area->getArea(centerPos, targetPos), targetPos, getDirectionTo(targetPos, centerPos));
}
Tile* tile = g_game.map.getTile(targetPos);
if (!tile) {
tile = new StaticTile(targetPos.x, targetPos.y, targetPos.z);
g_game.map.setTile(targetPos, tile);
}
return {tile};
}
}
CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const
{
CombatDamage damage;
damage.origin = params.origin;
damage.primary.type = params.combatType;
if (formulaType == COMBAT_FORMULA_DAMAGE) {
damage.primary.value = normal_random(
static_cast<int32_t>(mina),
static_cast<int32_t>(maxa)
);
} else if (creature) {
int32_t min, max;
if (creature->getCombatValues(min, max)) {
damage.primary.value = normal_random(min, max);
} else if (Player* player = creature->getPlayer()) {
if (params.valueCallback) {
params.valueCallback->getMinMaxValues(player, damage);
} else if (formulaType == COMBAT_FORMULA_LEVELMAGIC) {
int32_t levelFormula = player->getLevel() * 2 + player->getMagicLevel() * 3;
damage.primary.value = normal_random(std::fma(levelFormula, mina, minb), std::fma(levelFormula, maxa, maxb));
} else if (formulaType == COMBAT_FORMULA_SKILL) {
Item* tool = player->getWeapon();
const Weapon* weapon = g_weapons->getWeapon(tool);
if (weapon) {
damage.primary.value = normal_random(minb, std::fma(weapon->getWeaponDamage(player, target, tool, true), maxa, maxb));
damage.secondary.type = weapon->getElementType();
damage.secondary.value = weapon->getElementDamage(player, target, tool);
} else {
damage.primary.value = normal_random(minb, maxb);
}
}
}
}
return damage;
}
CombatType_t Combat::ConditionToDamageType(ConditionType_t type)
{
switch (type) {
case CONDITION_FIRE:
return COMBAT_FIREDAMAGE;
case CONDITION_ENERGY:
return COMBAT_ENERGYDAMAGE;
case CONDITION_BLEEDING:
return COMBAT_PHYSICALDAMAGE;
case CONDITION_DROWN:
return COMBAT_DROWNDAMAGE;
case CONDITION_POISON:
return COMBAT_EARTHDAMAGE;
case CONDITION_FREEZING:
return COMBAT_ICEDAMAGE;
case CONDITION_DAZZLED:
return COMBAT_HOLYDAMAGE;
case CONDITION_CURSED:
return COMBAT_DEATHDAMAGE;
default:
break;
}
return COMBAT_NONE;
}
ConditionType_t Combat::DamageToConditionType(CombatType_t type)
{
switch (type) {
case COMBAT_FIREDAMAGE:
return CONDITION_FIRE;
case COMBAT_ENERGYDAMAGE:
return CONDITION_ENERGY;
case COMBAT_DROWNDAMAGE:
return CONDITION_DROWN;
case COMBAT_EARTHDAMAGE:
return CONDITION_POISON;
case COMBAT_ICEDAMAGE:
return CONDITION_FREEZING;
case COMBAT_HOLYDAMAGE:
return CONDITION_DAZZLED;
case COMBAT_DEATHDAMAGE:
return CONDITION_CURSED;
case COMBAT_PHYSICALDAMAGE:
return CONDITION_BLEEDING;
default:
return CONDITION_NONE;
}
}
bool Combat::isPlayerCombat(const Creature* target)
{
if (target->getPlayer()) {
return true;
}
if (target->isSummon() && target->getMaster()->getPlayer()) {
return true;
}
return false;
}
ReturnValue Combat::canTargetCreature(Player* attacker, Creature* target)
{
if (attacker == target) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
if (!attacker->hasFlag(PlayerFlag_IgnoreProtectionZone)) {
//pz-zone
if (attacker->getZone() == ZONE_PROTECTION) {
return RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE;
}
if (target->getZone() == ZONE_PROTECTION) {
return RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE;
}
//nopvp-zone
if (isPlayerCombat(target)) {
if (attacker->getZone() == ZONE_NOPVP) {
return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE;
}
if (target->getZone() == ZONE_NOPVP) {
return RETURNVALUE_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE;
}
}
}
if (attacker->hasFlag(PlayerFlag_CannotUseCombat) || !target->isAttackable()) {
if (target->getPlayer()) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE;
}
if (target->getPlayer()) {
if (isProtected(attacker, target->getPlayer())) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
if (attacker->hasSecureMode() && !Combat::isInPvpZone(attacker, target) && attacker->getSkullClient(target->getPlayer()) == SKULL_NONE) {
return RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS;
}
}
return Combat::canDoCombat(attacker, target);
}
ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive)
{
if (tile->hasProperty(CONST_PROP_BLOCKPROJECTILE)) {
return RETURNVALUE_NOTENOUGHROOM;
}
if (tile->hasFlag(TILESTATE_FLOORCHANGE)) {
return RETURNVALUE_NOTENOUGHROOM;
}
if (tile->getTeleportItem()) {
return RETURNVALUE_NOTENOUGHROOM;
}
if (caster) {
const Position& casterPosition = caster->getPosition();
const Position& tilePosition = tile->getPosition();
if (casterPosition.z < tilePosition.z) {
return RETURNVALUE_FIRSTGODOWNSTAIRS;
} else if (casterPosition.z > tilePosition.z) {
return RETURNVALUE_FIRSTGOUPSTAIRS;
}
if (const Player* player = caster->getPlayer()) {
if (player->hasFlag(PlayerFlag_IgnoreProtectionZone)) {
return RETURNVALUE_NOERROR;
}
}
}
//pz-zone
if (aggressive && tile->hasFlag(TILESTATE_PROTECTIONZONE)) {
return RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE;
}
return g_events->eventCreatureOnAreaCombat(caster, tile, aggressive);
}
bool Combat::isInPvpZone(const Creature* attacker, const Creature* target)
{
return attacker->getZone() == ZONE_PVP && target->getZone() == ZONE_PVP;
}
bool Combat::isProtected(const Player* attacker, const Player* target)
{
uint32_t protectionLevel = g_config.getNumber(ConfigManager::PROTECTION_LEVEL);
if (target->getLevel() < protectionLevel || attacker->getLevel() < protectionLevel) {
return true;
}
if (!attacker->getVocation()->allowsPvp() || !target->getVocation()->allowsPvp()) {
return true;
}
if (attacker->getSkull() == SKULL_BLACK && attacker->getSkullClient(target) == SKULL_NONE) {
return true;
}
return false;
}
ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target)
{
if (!attacker) {
return g_events->eventCreatureOnTargetCombat(attacker, target);
}
if (const Player* targetPlayer = target->getPlayer()) {
if (targetPlayer->hasFlag(PlayerFlag_CannotBeAttacked)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
if (const Player* attackerPlayer = attacker->getPlayer()) {
if (attackerPlayer->hasFlag(PlayerFlag_CannotAttackPlayer)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
if (isProtected(attackerPlayer, targetPlayer)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
//nopvp-zone
const Tile* targetPlayerTile = targetPlayer->getTile();
if (targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE)) {
return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE;
} else if (attackerPlayer->getTile()->hasFlag(TILESTATE_NOPVPZONE) && !targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE | TILESTATE_PROTECTIONZONE)) {
return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE;
}
}
if (attacker->isSummon()) {
if (const Player* masterAttackerPlayer = attacker->getMaster()->getPlayer()) {
if (masterAttackerPlayer->hasFlag(PlayerFlag_CannotAttackPlayer)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
if (targetPlayer->getTile()->hasFlag(TILESTATE_NOPVPZONE)) {
return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE;
}
if (isProtected(masterAttackerPlayer, targetPlayer)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
}
}
} else if (target->getMonster()) {
if (const Player* attackerPlayer = attacker->getPlayer()) {
if (attackerPlayer->hasFlag(PlayerFlag_CannotAttackMonster)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE;
}
if (target->isSummon() && target->getMaster()->getPlayer() && target->getZone() == ZONE_NOPVP) {
return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE;
}
} else if (attacker->getMonster()) {
const Creature* targetMaster = target->getMaster();
if (!targetMaster || !targetMaster->getPlayer()) {
const Creature* attackerMaster = attacker->getMaster();
if (!attackerMaster || !attackerMaster->getPlayer()) {
return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE;
}
}
}
}
if (g_game.getWorldType() == WORLD_TYPE_NO_PVP) {
if (attacker->getPlayer() || (attacker->isSummon() && attacker->getMaster()->getPlayer())) {
if (target->getPlayer()) {
if (!isInPvpZone(attacker, target)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER;
}
}
if (target->isSummon() && target->getMaster()->getPlayer()) {
if (!isInPvpZone(attacker, target)) {
return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE;
}
}
}
}
return g_events->eventCreatureOnTargetCombat(attacker, target);
}
void Combat::setPlayerCombatValues(formulaType_t formulaType, double mina, double minb, double maxa, double maxb)
{
this->formulaType = formulaType;
this->mina = mina;
this->minb = minb;
this->maxa = maxa;
this->maxb = maxb;
}
bool Combat::setParam(CombatParam_t param, uint32_t value)
{
switch (param) {
case COMBAT_PARAM_TYPE: {
params.combatType = static_cast<CombatType_t>(value);
return true;
}
case COMBAT_PARAM_EFFECT: {
params.impactEffect = static_cast<uint8_t>(value);
return true;
}
case COMBAT_PARAM_DISTANCEEFFECT: {
params.distanceEffect = static_cast<uint8_t>(value);
return true;
}
case COMBAT_PARAM_BLOCKARMOR: {
params.blockedByArmor = (value != 0);
return true;
}
case COMBAT_PARAM_BLOCKSHIELD: {
params.blockedByShield = (value != 0);
return true;
}
case COMBAT_PARAM_TARGETCASTERORTOPMOST: {
params.targetCasterOrTopMost = (value != 0);
return true;
}
case COMBAT_PARAM_CREATEITEM: {
params.itemId = value;
return true;
}
case COMBAT_PARAM_AGGRESSIVE: {
params.aggressive = (value != 0);
return true;
}
case COMBAT_PARAM_DISPEL: {
params.dispelType = static_cast<ConditionType_t>(value);
return true;
}
case COMBAT_PARAM_USECHARGES: {
params.useCharges = (value != 0);
return true;
}
}
return false;
}
int32_t Combat::getParam(CombatParam_t param)
{
switch (param) {
case COMBAT_PARAM_TYPE:
return static_cast<int32_t>(params.combatType);
case COMBAT_PARAM_EFFECT:
return static_cast<int32_t>(params.impactEffect);
case COMBAT_PARAM_DISTANCEEFFECT:
return static_cast<int32_t>(params.distanceEffect);
case COMBAT_PARAM_BLOCKARMOR:
return params.blockedByArmor ? 1 : 0;
case COMBAT_PARAM_BLOCKSHIELD:
return params.blockedByShield ? 1 : 0;
case COMBAT_PARAM_TARGETCASTERORTOPMOST:
return params.targetCasterOrTopMost ? 1 : 0;
case COMBAT_PARAM_CREATEITEM:
return params.itemId;
case COMBAT_PARAM_AGGRESSIVE:
return params.aggressive ? 1 : 0;
case COMBAT_PARAM_DISPEL:
return static_cast<int32_t>(params.dispelType);
case COMBAT_PARAM_USECHARGES:
return params.useCharges ? 1 : 0;
default:
return std::numeric_limits<int32_t>().max();
}
}
bool Combat::setCallback(CallBackParam_t key)
{
switch (key) {
case CALLBACK_PARAM_LEVELMAGICVALUE: {
params.valueCallback.reset(new ValueCallback(COMBAT_FORMULA_LEVELMAGIC));
return true;
}
case CALLBACK_PARAM_SKILLVALUE: {
params.valueCallback.reset(new ValueCallback(COMBAT_FORMULA_SKILL));
return true;
}
case CALLBACK_PARAM_TARGETTILE: {
params.tileCallback.reset(new TileCallback());
return true;
}
case CALLBACK_PARAM_TARGETCREATURE: {
params.targetCallback.reset(new TargetCallback());
return true;
}
}
return false;
}
CallBack* Combat::getCallback(CallBackParam_t key)
{
switch (key) {
case CALLBACK_PARAM_LEVELMAGICVALUE:
case CALLBACK_PARAM_SKILLVALUE: {
return params.valueCallback.get();
}
case CALLBACK_PARAM_TARGETTILE: {
return params.tileCallback.get();
}
case CALLBACK_PARAM_TARGETCREATURE: {
return params.targetCallback.get();
}
}
return nullptr;
}
void Combat::combatTileEffects(const SpectatorVec& spectators, Creature* caster, Tile* tile, const CombatParams& params)
{
if (params.itemId != 0) {
uint16_t itemId = params.itemId;
switch (itemId) {
case ITEM_FIREFIELD_PERSISTENT_FULL:
itemId = ITEM_FIREFIELD_PVP_FULL;
break;
case ITEM_FIREFIELD_PERSISTENT_MEDIUM:
itemId = ITEM_FIREFIELD_PVP_MEDIUM;
break;
case ITEM_FIREFIELD_PERSISTENT_SMALL:
itemId = ITEM_FIREFIELD_PVP_SMALL;
break;
case ITEM_ENERGYFIELD_PERSISTENT:
itemId = ITEM_ENERGYFIELD_PVP;
break;
case ITEM_POISONFIELD_PERSISTENT:
itemId = ITEM_POISONFIELD_PVP;
break;
case ITEM_MAGICWALL_PERSISTENT:
itemId = ITEM_MAGICWALL;
break;
case ITEM_WILDGROWTH_PERSISTENT:
itemId = ITEM_WILDGROWTH;
break;
default:
break;
}
if (caster) {
Player* casterPlayer;
if (caster->isSummon()) {
casterPlayer = caster->getMaster()->getPlayer();
} else {
casterPlayer = caster->getPlayer();
}
if (casterPlayer) {
if (g_game.getWorldType() == WORLD_TYPE_NO_PVP || tile->hasFlag(TILESTATE_NOPVPZONE)) {
if (itemId == ITEM_FIREFIELD_PVP_FULL) {
itemId = ITEM_FIREFIELD_NOPVP;
} else if (itemId == ITEM_POISONFIELD_PVP) {
itemId = ITEM_POISONFIELD_NOPVP;
} else if (itemId == ITEM_ENERGYFIELD_PVP) {
itemId = ITEM_ENERGYFIELD_NOPVP;
} else if (itemId == ITEM_MAGICWALL) {
itemId = ITEM_MAGICWALL_NOPVP;
} else if (itemId == ITEM_WILDGROWTH) {
itemId = ITEM_WILDGROWTH_NOPVP;
}
} else if (itemId == ITEM_FIREFIELD_PVP_FULL || itemId == ITEM_POISONFIELD_PVP || itemId == ITEM_ENERGYFIELD_PVP) {
casterPlayer->addInFightTicks();
}
}
}
Item* item = Item::CreateItem(itemId);
if (caster) {
item->setOwner(caster->getID());
}
ReturnValue ret = g_game.internalAddItem(tile, item);
if (ret == RETURNVALUE_NOERROR) {
g_game.startDecay(item);
} else {
delete item;
}
}
if (params.tileCallback) {
params.tileCallback->onTileCombat(caster, tile);
}
if (params.impactEffect != CONST_ME_NONE) {
Game::addMagicEffect(spectators, tile->getPosition(), params.impactEffect);
}
}
void Combat::postCombatEffects(Creature* caster, const Position& pos, const CombatParams& params)
{
if (caster && params.distanceEffect != CONST_ANI_NONE) {
addDistanceEffect(caster, caster->getPosition(), pos, params.distanceEffect);
}
}
void Combat::addDistanceEffect(Creature* caster, const Position& fromPos, const Position& toPos, uint8_t effect)
{
if (effect == CONST_ANI_WEAPONTYPE) {
if (!caster) {
return;
}
Player* player = caster->getPlayer();
if (!player) {
return;
}
switch (player->getWeaponType()) {
case WEAPON_AXE:
effect = CONST_ANI_WHIRLWINDAXE;
break;
case WEAPON_SWORD:
effect = CONST_ANI_WHIRLWINDSWORD;
break;
case WEAPON_CLUB:
effect = CONST_ANI_WHIRLWINDCLUB;
break;
default:
effect = CONST_ANI_NONE;
break;
}
}
if (effect != CONST_ANI_NONE) {
g_game.addDistanceEffect(fromPos, toPos, effect);
}
}
void Combat::doCombat(Creature* caster, Creature* target) const
{
//target combat callback function
if (params.combatType != COMBAT_NONE) {
CombatDamage damage = getCombatDamage(caster, target);
bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR);
if ((caster == target || canCombat) && params.impactEffect != CONST_ME_NONE) {
g_game.addMagicEffect(target->getPosition(), params.impactEffect);
}
if (canCombat) {
doTargetCombat(caster, target, damage, params);
}
} else {
if (!params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR)) {
SpectatorVec spectators;
g_game.map.getSpectators(spectators, target->getPosition(), true, true);
if (params.origin != ORIGIN_MELEE) {
for (const auto& condition : params.conditionList) {
if (caster == target || !target->isImmune(condition->getType())) {
Condition* conditionCopy = condition->clone();
conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID());
target->addCombatCondition(conditionCopy);
}
}
}
if (params.dispelType == CONDITION_PARALYZE) {
target->removeCondition(CONDITION_PARALYZE);
} else {
target->removeCombatCondition(params.dispelType);
}
combatTileEffects(spectators, caster, target->getTile(), params);
if (params.targetCallback) {
params.targetCallback->onTargetCombat(caster, target);
}
/*
if (params.impactEffect != CONST_ME_NONE) {
g_game.addMagicEffect(target->getPosition(), params.impactEffect);
}
*/
if (caster && params.distanceEffect != CONST_ANI_NONE) {
addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect);
}
}
}
}
void Combat::doCombat(Creature* caster, const Position& position) const
{
//area combat callback function
if (params.combatType != COMBAT_NONE) {
CombatDamage damage = getCombatDamage(caster, nullptr);
doAreaCombat(caster, position, area.get(), damage, params);
} else {
auto tiles = caster ? getCombatArea(caster->getPosition(), position, area.get()) : getCombatArea(position, position, area.get());
SpectatorVec spectators;
uint32_t maxX = 0;
uint32_t maxY = 0;
//calculate the max viewable range
for (Tile* tile : tiles) {
const Position& tilePos = tile->getPosition();
uint32_t diff = Position::getDistanceX(tilePos, position);
if (diff > maxX) {
maxX = diff;
}
diff = Position::getDistanceY(tilePos, position);
if (diff > maxY) {
maxY = diff;
}
}
const int32_t rangeX = maxX + Map::maxViewportX;
const int32_t rangeY = maxY + Map::maxViewportY;
g_game.map.getSpectators(spectators, position, true, true, rangeX, rangeX, rangeY, rangeY);
postCombatEffects(caster, position, params);
for (Tile* tile : tiles) {
if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) {
continue;
}
combatTileEffects(spectators, caster, tile, params);
if (CreatureVector* creatures = tile->getCreatures()) {
const Creature* topCreature = tile->getTopCreature();
for (Creature* creature : *creatures) {
if (params.targetCasterOrTopMost) {
if (caster && caster->getTile() == tile) {
if (creature != caster) {
continue;
}
} else if (creature != topCreature) {
continue;
}
}
if (!params.aggressive || (caster != creature && Combat::canDoCombat(caster, creature) == RETURNVALUE_NOERROR)) {
for (const auto& condition : params.conditionList) {
if (caster == creature || !creature->isImmune(condition->getType())) {
Condition* conditionCopy = condition->clone();
if (caster) {
conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID());
}
//TODO: infight condition until all aggressive conditions has ended
creature->addCombatCondition(conditionCopy);
}
}
}
if (params.dispelType == CONDITION_PARALYZE) {
creature->removeCondition(CONDITION_PARALYZE);
} else {
creature->removeCombatCondition(params.dispelType);
}
if (params.targetCallback) {
params.targetCallback->onTargetCombat(caster, creature);
}
if (params.targetCasterOrTopMost) {
break;
}
}
}
}
}
}
void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params)
{
if (caster && target && params.distanceEffect != CONST_ANI_NONE) {
addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect);
}
Player* casterPlayer = caster ? caster->getPlayer() : nullptr;
bool success = false;
if (damage.primary.type != COMBAT_MANADRAIN) {
if (g_game.combatBlockHit(damage, caster, target, params.blockedByShield, params.blockedByArmor, params.itemId != 0, params.ignoreResistances)) {
return;
}
if (casterPlayer) {
Player* targetPlayer = target ? target->getPlayer() : nullptr;
if (targetPlayer && casterPlayer != targetPlayer && targetPlayer->getSkull() != SKULL_BLACK && damage.primary.type != COMBAT_HEALING) {
damage.primary.value /= 2;
damage.secondary.value /= 2;
}
if (!damage.critical && damage.primary.type != COMBAT_HEALING && damage.origin != ORIGIN_CONDITION) {
uint16_t chance = casterPlayer->getSpecialSkill(SPECIALSKILL_CRITICALHITCHANCE);
uint16_t skill = casterPlayer->getSpecialSkill(SPECIALSKILL_CRITICALHITAMOUNT);
if (chance > 0 && skill > 0 && normal_random(1, 100) <= chance) {
damage.primary.value += std::round(damage.primary.value * (skill / 100.));
damage.secondary.value += std::round(damage.secondary.value * (skill / 100.));
damage.critical = true;
}
}
}
success = g_game.combatChangeHealth(caster, target, damage);
} else {
success = g_game.combatChangeMana(caster, target, damage);
}
if (success) {
if (damage.blockType == BLOCK_NONE || damage.blockType == BLOCK_ARMOR) {
for (const auto& condition : params.conditionList) {
if (caster == target || !target->isImmune(condition->getType())) {
Condition* conditionCopy = condition->clone();
if (caster) {
conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID());
}
//TODO: infight condition until all aggressive conditions has ended
target->addCombatCondition(conditionCopy);
}
}
}
if (damage.critical) {
g_game.addMagicEffect(target->getPosition(), CONST_ME_CRITICAL_DAMAGE);
}
if (!damage.leeched && damage.primary.type != COMBAT_HEALING && casterPlayer && damage.origin != ORIGIN_CONDITION) {
CombatDamage leechCombat;
leechCombat.origin = ORIGIN_NONE;
leechCombat.leeched = true;
int32_t totalDamage = std::abs(damage.primary.value + damage.secondary.value);
if (casterPlayer->getHealth() < casterPlayer->getMaxHealth()) {
uint16_t chance = casterPlayer->getSpecialSkill(SPECIALSKILL_LIFELEECHCHANCE);
uint16_t skill = casterPlayer->getSpecialSkill(SPECIALSKILL_LIFELEECHAMOUNT);
if (chance > 0 && skill > 0 && normal_random(1, 100) <= chance) {
leechCombat.primary.value = std::round(totalDamage * (skill / 100.));
g_game.combatChangeHealth(nullptr, casterPlayer, leechCombat);
casterPlayer->sendMagicEffect(casterPlayer->getPosition(), CONST_ME_MAGIC_RED);
}
}
if (casterPlayer->getMana() < casterPlayer->getMaxMana()) {
uint16_t chance = casterPlayer->getSpecialSkill(SPECIALSKILL_MANALEECHCHANCE);
uint16_t skill = casterPlayer->getSpecialSkill(SPECIALSKILL_MANALEECHAMOUNT);
if (chance > 0 && skill > 0 && normal_random(1, 100) <= chance) {
leechCombat.primary.value = std::round(totalDamage * (skill / 100.));
g_game.combatChangeMana(nullptr, casterPlayer, leechCombat);
casterPlayer->sendMagicEffect(casterPlayer->getPosition(), CONST_ME_MAGIC_BLUE);
}
}
}
if (params.dispelType == CONDITION_PARALYZE) {
target->removeCondition(CONDITION_PARALYZE);
} else {
target->removeCombatCondition(params.dispelType);
}
}
if (params.targetCallback) {
params.targetCallback->onTargetCombat(caster, target);
}
}
void Combat::doAreaCombat(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params)
{
auto tiles = caster ? getCombatArea(caster->getPosition(), position, area) : getCombatArea(position, position, area);
Player* casterPlayer = caster ? caster->getPlayer() : nullptr;
int32_t criticalPrimary = 0;
int32_t criticalSecondary = 0;
if (!damage.critical && damage.primary.type != COMBAT_HEALING && casterPlayer && damage.origin != ORIGIN_CONDITION) {
uint16_t chance = casterPlayer->getSpecialSkill(SPECIALSKILL_CRITICALHITCHANCE);
uint16_t skill = casterPlayer->getSpecialSkill(SPECIALSKILL_CRITICALHITAMOUNT);
if (chance > 0 && skill > 0 && uniform_random(1, 100) <= chance) {
criticalPrimary = std::round(damage.primary.value * (skill / 100.));
criticalSecondary = std::round(damage.secondary.value * (skill / 100.));
damage.critical = true;
}
}
uint32_t maxX = 0;
uint32_t maxY = 0;
//calculate the max viewable range
for (Tile* tile : tiles) {
const Position& tilePos = tile->getPosition();
uint32_t diff = Position::getDistanceX(tilePos, position);
if (diff > maxX) {
maxX = diff;
}
diff = Position::getDistanceY(tilePos, position);
if (diff > maxY) {
maxY = diff;
}
}
const int32_t rangeX = maxX + Map::maxViewportX;
const int32_t rangeY = maxY + Map::maxViewportY;
SpectatorVec spectators;
g_game.map.getSpectators(spectators, position, true, true, rangeX, rangeX, rangeY, rangeY);
postCombatEffects(caster, position, params);
std::vector<Creature*> toDamageCreatures;
toDamageCreatures.reserve(100);
for (Tile* tile : tiles) {
if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) {
continue;
}
combatTileEffects(spectators, caster, tile, params);
if (CreatureVector* creatures = tile->getCreatures()) {
const Creature* topCreature = tile->getTopCreature();
for (Creature* creature : *creatures) {
if (params.targetCasterOrTopMost) {
if (caster && caster->getTile() == tile) {
if (creature != caster) {
continue;
}
} else if (creature != topCreature) {
continue;
}
}
if (!params.aggressive || (caster != creature && Combat::canDoCombat(caster, creature) == RETURNVALUE_NOERROR)) {
toDamageCreatures.push_back(creature);
if (params.targetCasterOrTopMost) {
break;
}
}
}
}
}
CombatDamage leechCombat;
leechCombat.origin = ORIGIN_NONE;
leechCombat.leeched = true;
for (Creature* creature : toDamageCreatures) {
CombatDamage damageCopy = damage; // we cannot avoid copying here, because we don't know if it's player combat or not, so we can't modify the initial damage.
bool playerCombatReduced = false;
if ((damageCopy.primary.value < 0 || damageCopy.secondary.value < 0) && caster) {
Player* targetPlayer = creature->getPlayer();
if (casterPlayer && targetPlayer && casterPlayer != targetPlayer && targetPlayer->getSkull() != SKULL_BLACK) {
damageCopy.primary.value /= 2;
damageCopy.secondary.value /= 2;
playerCombatReduced = true;
}
}
if (damageCopy.critical) {
damageCopy.primary.value += playerCombatReduced ? criticalPrimary / 2 : criticalPrimary;
damageCopy.secondary.value += playerCombatReduced ? criticalSecondary / 2 : criticalSecondary;
g_game.addMagicEffect(creature->getPosition(), CONST_ME_CRITICAL_DAMAGE);
}
bool success = false;
if (damageCopy.primary.type != COMBAT_MANADRAIN) {
if (g_game.combatBlockHit(damageCopy, caster, creature, params.blockedByShield, params.blockedByArmor, params.itemId != 0, params.ignoreResistances)) {
continue;
}
success = g_game.combatChangeHealth(caster, creature, damageCopy);
} else {
success = g_game.combatChangeMana(caster, creature, damageCopy);
}
if (success) {
if (damage.blockType == BLOCK_NONE || damage.blockType == BLOCK_ARMOR) {
for (const auto& condition : params.conditionList) {
if (caster == creature || !creature->isImmune(condition->getType())) {
Condition* conditionCopy = condition->clone();
if (caster) {
conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID());
}
//TODO: infight condition until all aggressive conditions has ended
creature->addCombatCondition(conditionCopy);
}
}
}
int32_t totalDamage = std::abs(damageCopy.primary.value + damageCopy.secondary.value);
if (casterPlayer && !damage.leeched && damage.primary.type != COMBAT_HEALING && damage.origin != ORIGIN_CONDITION) {
int32_t targetsCount = toDamageCreatures.size();
if (casterPlayer->getHealth() < casterPlayer->getMaxHealth()) {
uint16_t chance = casterPlayer->getSpecialSkill(SPECIALSKILL_LIFELEECHCHANCE);
uint16_t skill = casterPlayer->getSpecialSkill(SPECIALSKILL_LIFELEECHAMOUNT);
if (chance > 0 && skill > 0 && normal_random(1, 100) <= chance) {
leechCombat.primary.value = std::ceil(totalDamage * ((skill / 100.) + ((targetsCount - 1) * ((skill / 100.) / 10.))) / targetsCount);
g_game.combatChangeHealth(nullptr, casterPlayer, leechCombat);
casterPlayer->sendMagicEffect(casterPlayer->getPosition(), CONST_ME_MAGIC_RED);
}
}
if (casterPlayer->getMana() < casterPlayer->getMaxMana()) {
uint16_t chance = casterPlayer->getSpecialSkill(SPECIALSKILL_MANALEECHCHANCE);
uint16_t skill = casterPlayer->getSpecialSkill(SPECIALSKILL_MANALEECHAMOUNT);
if (chance > 0 && skill > 0 && normal_random(1, 100) <= chance) {
leechCombat.primary.value = std::ceil(totalDamage * ((skill / 100.) + ((targetsCount - 1) * ((skill / 100.) / 10.))) / targetsCount);
g_game.combatChangeMana(nullptr, casterPlayer, leechCombat);
casterPlayer->sendMagicEffect(casterPlayer->getPosition(), CONST_ME_MAGIC_BLUE);
}
}
}
if (params.dispelType == CONDITION_PARALYZE) {
creature->removeCondition(CONDITION_PARALYZE);
} else {
creature->removeCombatCondition(params.dispelType);
}
}
if (params.targetCallback) {
params.targetCallback->onTargetCombat(caster, creature);
}
}
}
//**********************************************************//
void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage) const
{
//onGetPlayerMinMaxValues(...)
if (!scriptInterface->reserveScriptEnv()) {
std::cout << "[Error - ValueCallback::getMinMaxValues] Call stack overflow" << std::endl;
return;
}
ScriptEnvironment* env = scriptInterface->getScriptEnv();
if (!env->setCallbackId(scriptId, scriptInterface)) {
scriptInterface->resetScriptEnv();
return;
}
lua_State* L = scriptInterface->getLuaState();
scriptInterface->pushFunction(scriptId);
LuaScriptInterface::pushUserdata<Player>(L, player);
LuaScriptInterface::setMetatable(L, -1, "Player");
int parameters = 1;
switch (type) {
case COMBAT_FORMULA_LEVELMAGIC: {
//onGetPlayerMinMaxValues(player, level, maglevel)
lua_pushnumber(L, player->getLevel());
lua_pushnumber(L, player->getMagicLevel());
parameters += 2;
break;
}
case COMBAT_FORMULA_SKILL: {
//onGetPlayerMinMaxValues(player, attackSkill, attackValue, attackFactor)
Item* tool = player->getWeapon();
const Weapon* weapon = g_weapons->getWeapon(tool);
Item* item = nullptr;
int32_t attackValue = 7;
if (weapon) {
attackValue = tool->getAttack();
if (tool->getWeaponType() == WEAPON_AMMO) {
item = player->getWeapon(true);
if (item) {
attackValue += item->getAttack();
}
}
damage.secondary.type = weapon->getElementType();
damage.secondary.value = weapon->getElementDamage(player, nullptr, tool);
}
lua_pushnumber(L, player->getWeaponSkill(item ? item : tool));
lua_pushnumber(L, attackValue);
lua_pushnumber(L, player->getAttackFactor());
parameters += 3;
break;
}
default: {
std::cout << "ValueCallback::getMinMaxValues - unknown callback type" << std::endl;
scriptInterface->resetScriptEnv();
return;
}
}
int size0 = lua_gettop(L);
if (lua_pcall(L, parameters, 2, 0) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L));
} else {
damage.primary.value = normal_random(
LuaScriptInterface::getNumber<int32_t>(L, -2),
LuaScriptInterface::getNumber<int32_t>(L, -1)
);
lua_pop(L, 2);
}
if ((lua_gettop(L) + parameters + 1) != size0) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
scriptInterface->resetScriptEnv();
}
//**********************************************************//
void TileCallback::onTileCombat(Creature* creature, Tile* tile) const
{
//onTileCombat(creature, pos)
if (!scriptInterface->reserveScriptEnv()) {
std::cout << "[Error - TileCallback::onTileCombat] Call stack overflow" << std::endl;
return;
}
ScriptEnvironment* env = scriptInterface->getScriptEnv();
if (!env->setCallbackId(scriptId, scriptInterface)) {
scriptInterface->resetScriptEnv();
return;
}
lua_State* L = scriptInterface->getLuaState();
scriptInterface->pushFunction(scriptId);
if (creature) {
LuaScriptInterface::pushUserdata<Creature>(L, creature);
LuaScriptInterface::setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
LuaScriptInterface::pushPosition(L, tile->getPosition());
scriptInterface->callFunction(2);
}
//**********************************************************//
void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const
{
//onTargetCombat(creature, target)
if (!scriptInterface->reserveScriptEnv()) {
std::cout << "[Error - TargetCallback::onTargetCombat] Call stack overflow" << std::endl;
return;
}
ScriptEnvironment* env = scriptInterface->getScriptEnv();
if (!env->setCallbackId(scriptId, scriptInterface)) {
scriptInterface->resetScriptEnv();
return;
}
lua_State* L = scriptInterface->getLuaState();
scriptInterface->pushFunction(scriptId);
if (creature) {
LuaScriptInterface::pushUserdata<Creature>(L, creature);
LuaScriptInterface::setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
if (target) {
LuaScriptInterface::pushUserdata<Creature>(L, target);
LuaScriptInterface::setCreatureMetatable(L, -1, target);
} else {
lua_pushnil(L);
}
int size0 = lua_gettop(L);
if (lua_pcall(L, 2, 0 /*nReturnValues*/, 0) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L));
}
if ((lua_gettop(L) + 2 /*nParams*/ + 1) != size0) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
scriptInterface->resetScriptEnv();
}
//**********************************************************//
MatrixArea MatrixArea::flip() const {
Container newArr(arr.size());
for (uint32_t i = 0; i < rows; ++i) {
// assign rows, top to bottom, to the current rows, bottom to top
newArr[std::slice(i * cols, cols, 1)] = arr[std::slice((rows - i - 1) * cols, cols, 1)];
}
return {{cols - center.first - 1, center.second}, rows, cols, std::move(newArr)};
}
MatrixArea MatrixArea::mirror() const {
Container newArr(arr.size());
for (uint32_t i = 0; i < cols; ++i) {
// assign cols, left to right, to the current rows, right to left
newArr[std::slice(i, cols, rows)] = arr[std::slice(cols - i - 1, cols, rows)];
}
return {{center.first, rows - center.second - 1}, rows, cols, std::move(newArr)};
}
MatrixArea MatrixArea::transpose() const {
return {{center.second, center.first}, rows, cols, arr[std::gslice(0, {cols, rows}, {1, cols})]};
}
MatrixArea MatrixArea::rotate90() const {
Container newArr(arr.size());
for (uint32_t i = 0; i < rows; ++i) {
// assign rows, top to bottom, to the current cols, right to left
newArr[std::slice(i, cols, rows)] = arr[std::slice((rows - i - 1) * cols, cols, 1)];
}
return {{rows - center.second - 1, center.first}, cols, rows, std::move(newArr)};
}
MatrixArea MatrixArea::rotate180() const {
Container newArr(arr.size());
std::reverse_copy(std::begin(arr), std::end(arr), std::begin(newArr));
return {{cols - center.first - 1, rows - center.second - 1}, rows, cols, std::move(newArr)};
}
MatrixArea MatrixArea::rotate270() const {
Container newArr(arr.size());
for (uint32_t i = 0; i < cols; ++i) {
// assign cols, left to right, to the current rows, bottom to top
newArr[std::slice(i * rows, rows, 1)] = arr[std::slice(cols - i - 1, rows, cols)];
}
return {{center.second, cols - center.first - 1}, cols, rows, std::move(newArr)};
}
const MatrixArea& AreaCombat::getArea(const Position& centerPos, const Position& targetPos) const {
int32_t dx = Position::getOffsetX(targetPos, centerPos);
int32_t dy = Position::getOffsetY(targetPos, centerPos);
Direction dir;
if (dx < 0) {
dir = DIRECTION_WEST;
} else if (dx > 0) {
dir = DIRECTION_EAST;
} else if (dy < 0) {
dir = DIRECTION_NORTH;
} else {
dir = DIRECTION_SOUTH;
}
if (hasExtArea) {
if (dx < 0 && dy < 0) {
dir = DIRECTION_NORTHWEST;
} else if (dx > 0 && dy < 0) {
dir = DIRECTION_NORTHEAST;
} else if (dx < 0 && dy > 0) {
dir = DIRECTION_SOUTHWEST;
} else if (dx > 0 && dy > 0) {
dir = DIRECTION_SOUTHEAST;
}
}
if (dir >= areas.size()) {
// this should not happen. it means we forgot to call setupArea.
static MatrixArea empty;
return empty;
}
return areas[dir];
}
void AreaCombat::setupArea(const std::vector<uint32_t>& vec, uint32_t rows)
{
auto area = createArea(vec, rows);
if (areas.size() == 0) {
areas.resize(4);
}
areas[DIRECTION_EAST] = area.rotate90();
areas[DIRECTION_SOUTH] = area.rotate180();
areas[DIRECTION_WEST] = area.rotate270();
areas[DIRECTION_NORTH] = std::move(area);
}
void AreaCombat::setupArea(int32_t length, int32_t spread)
{
uint32_t rows = length;
int32_t cols = 1;
if (spread != 0) {
cols = ((length - (length % spread)) / spread) * 2 + 1;
}
int32_t colSpread = cols;
std::vector<uint32_t> vec;
vec.reserve(rows * cols);
for (uint32_t y = 1; y <= rows; ++y) {
int32_t mincol = cols - colSpread + 1;
int32_t maxcol = cols - (cols - colSpread);
for (int32_t x = 1; x <= cols; ++x) {
if (y == rows && x == ((cols - (cols % 2)) / 2) + 1) {
vec.push_back(3);
} else if (x >= mincol && x <= maxcol) {
vec.push_back(1);
} else {
vec.push_back(0);
}
}
if (spread > 0 && y % spread == 0) {
--colSpread;
}
}
setupArea(vec, rows);
}
void AreaCombat::setupArea(int32_t radius)
{
int32_t area[13][13] = {
{0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0},
{0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0},
{0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0},
{0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0},
{0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0},
{8, 7, 6, 5, 4, 2, 1, 2, 4, 5, 6, 7, 8},
{0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0},
{0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0},
{0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0},
{0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0},
{0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0}
};
std::vector<uint32_t> vec;
vec.reserve(13 * 13);
for (auto& row : area) {
for (int cell : row) {
if (cell == 1) {
vec.push_back(3);
} else if (cell > 0 && cell <= radius) {
vec.push_back(1);
} else {
vec.push_back(0);
}
}
}
setupArea(vec, 13);
}
void AreaCombat::setupAreaRing(int32_t ring)
{
int32_t area[13][13] = {
{0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 7, 6, 6, 6, 7, 0, 0, 0, 0},
{0, 0, 0, 7, 6, 5, 5, 5, 6, 7, 0, 0, 0},
{0, 0, 7, 6, 5, 4, 4, 4, 5, 6, 7, 0, 0},
{0, 7, 6, 5, 4, 3, 3, 3, 4, 5, 6, 7, 0},
{7, 6, 5, 4, 3, 2, 0, 2, 3, 4, 5, 6, 7},
{7, 6, 5, 4, 3, 0, 1, 0, 3, 4, 5, 6, 7},
{7, 6, 5, 4, 3, 2, 0, 2, 3, 4, 5, 6, 7},
{0, 7, 6, 5, 4, 3, 3, 3, 4, 5, 6, 7, 0},
{0, 0, 7, 6, 5, 4, 4, 4, 5, 6, 7, 0, 0},
{0, 0, 0, 7, 6, 5, 5, 5, 6, 7, 0, 0, 0},
{0, 0, 0, 0, 7, 6, 6, 6, 7, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0}
};
std::vector<uint32_t> vec;
vec.reserve(13 * 13);
for (auto& row : area) {
for (int cell : row) {
if (cell == 1) {
vec.push_back(3);
} else if (cell > 0 && cell == ring) {
vec.push_back(1);
} else {
vec.push_back(0);
}
}
}
setupArea(vec, 13);
}
void AreaCombat::setupExtArea(const std::vector<uint32_t>& vec, uint32_t rows)
{
if (vec.empty()) {
return;
}
hasExtArea = true;
auto area = createArea(vec, rows);
areas.resize(8);
areas[DIRECTION_NORTHEAST] = area.mirror();
areas[DIRECTION_SOUTHWEST] = area.flip();
areas[DIRECTION_SOUTHEAST] = area.transpose();
areas[DIRECTION_NORTHWEST] = std::move(area);
}
//**********************************************************//
void MagicField::onStepInField(Creature* creature)
{
//remove magic walls/wild growth
if (id == ITEM_MAGICWALL || id == ITEM_WILDGROWTH || id == ITEM_MAGICWALL_SAFE || id == ITEM_WILDGROWTH_SAFE || isBlocking()) {
if (!creature->isInGhostMode()) {
g_game.internalRemoveItem(this, 1);
}
return;
}
//remove magic walls/wild growth (only nopvp tiles/world)
if (id == ITEM_MAGICWALL_NOPVP || id == ITEM_WILDGROWTH_NOPVP) {
if (g_game.getWorldType() == WORLD_TYPE_NO_PVP || getTile()->hasFlag(TILESTATE_NOPVPZONE)) {
g_game.internalRemoveItem(this, 1);
}
return;
}
const ItemType& it = items[getID()];
if (it.conditionDamage) {
Condition* conditionCopy = it.conditionDamage->clone();
uint32_t ownerId = getOwner();
if (ownerId) {
bool harmfulField = true;
if (g_game.getWorldType() == WORLD_TYPE_NO_PVP || getTile()->hasFlag(TILESTATE_NOPVPZONE)) {
Creature* owner = g_game.getCreatureByID(ownerId);
if (owner) {
if (owner->getPlayer() || (owner->isSummon() && owner->getMaster()->getPlayer())) {
harmfulField = false;
}
}
}
Player* targetPlayer = creature->getPlayer();
if (targetPlayer) {
Player* attackerPlayer = g_game.getPlayerByID(ownerId);
if (attackerPlayer) {
if (Combat::isProtected(attackerPlayer, targetPlayer)) {
harmfulField = false;
}
}
}
if (!harmfulField || (OTSYS_TIME() - createTime <= 5000) || creature->hasBeenAttacked(ownerId)) {
conditionCopy->setParam(CONDITION_PARAM_OWNER, ownerId);
}
}
creature->addCondition(conditionCopy);
}
}
| 1 | 19,520 | I do not see how that changes anything, as the target is operated on many times before that line? | otland-forgottenserver | cpp |
@@ -513,7 +513,7 @@ $(document).ready(function() {
app.addSubMenuForType("web", "analytics", {code: "analytics-geo", url: "#/analytics/geo", text: "sidebar.analytics.geo", priority: 30});
app.addSubMenuForType("web", "analytics", {code: "analytics-sessions", url: "#/analytics/sessions", text: "sidebar.analytics.session", priority: 20});
app.addSubMenuForType("web", "analytics", {code: "analytics-users", url: "#/analytics/users", text: "sidebar.analytics.users", priority: 10});
- app.addSubMenuForType("web", "analytics", {code: "analytics-loyalty", url: "#/analytics/loyalty", text: "sidebar.analytics.user-loyalty", priority: 15});
+ app.addSubMenuForType("web", "analytics", {code: "analytics-loyalty", url: "#/analytics/loyalty", text: "sidebar.analytics.visitor-loyalty", priority: 15});
}
app.addAppSwitchCallback(function(appId) { | 1 | /*global countlyAnalyticsAPI, countlyAuth, CountlyHelpers, countlyView, _, WebDashboardView, countlyLocation, countlyTotalUsers, countlySources, countlyWebDashboard, countlyCommon, countlyGlobal, countlySession, Handlebars, app, $, jQuery*/
window.WebDashboardView = countlyView.extend({
featureName: 'web',
selectedView: "#draw-total-sessions",
selectedMap: "#map-list-sessions",
initialize: function() {
this.curMap = "map-list-sessions";
this.template = Handlebars.compile($("#dashboard-template").html());
},
beforeRender: function(isRefresh) {
this.maps = {
"map-list-sessions": {id: 'total', label: jQuery.i18n.map["sidebar.analytics.sessions"], type: 'number', metric: "t"},
"map-list-users": {id: 'total', label: jQuery.i18n.map["sidebar.analytics.users"], type: 'number', metric: "u"},
"map-list-new": {id: 'total', label: jQuery.i18n.map["common.table.new-users"], type: 'number', metric: "n"}
};
//do not wait on country initialization
countlyTotalUsers.initialize("countries");
var defs = [countlyAnalyticsAPI.initialize(["platforms", "sources", "browser"]), countlySession.initialize(), countlyWebDashboard.initialize(isRefresh), countlyTotalUsers.initialize("users"), countlyCommon.getGraphNotes([countlyCommon.ACTIVE_APP_ID])];
return $.when.apply($, defs).then(function() {});
},
afterRender: function() {
if (countlyGlobal.config.use_google) {
var self = this;
countlyLocation.drawGeoChart({height: 330, metric: self.maps[self.curMap]});
}
},
pageScript: function() {
$("#total-user-estimate-ind").on("click", function() {
CountlyHelpers.alert($("#total-user-estimate-exp").html(), "black");
});
var self = this;
$("#big-numbers-container").find(".big-numbers .inner").click(function() {
$("#big-numbers-container").find(".big-numbers").removeClass("active");
$(this).parent(".big-numbers").addClass("active");
var elID = $(this).find('.select').attr("id");
if (self.selectedView === "#" + elID) {
return true;
}
self.selectedView = "#" + elID;
self.drawGraph();
});
if (countlyGlobal.config.use_google) {
this.countryList();
$(".map-list").find(".data-type-selector-group .selector").click(function() {
$(".map-list").find(".data-type-selector-group .selector").removeClass("active");
$(this).addClass("active");
self.curMap = $(this).attr("id");
self.selectedMap = "#" + self.curMap;
countlyLocation.refreshGeoChart(self.maps[self.curMap]);
self.countryList();
});
}
app.localize();
},
drawGraph: function() {
var sessionDP = {};
switch (this.selectedView) {
case "#draw-total-users":
sessionDP = countlySession.getUserDPActive();
break;
case "#draw-new-users":
sessionDP = countlySession.getUserDPNew();
break;
case "#draw-total-sessions":
sessionDP = countlySession.getSessionDPTotal();
break;
case "#draw-time-spent":
sessionDP = countlySession.getDurationDPAvg();
break;
case "#draw-total-time-spent":
sessionDP = countlySession.getDurationDP();
break;
case "#draw-avg-events-served":
sessionDP = countlySession.getEventsDPAvg();
break;
}
_.defer(function() {
countlyCommon.drawTimeGraph(sessionDP.chartDP, "#dashboard-graph", null, null, null, [countlyCommon.ACTIVE_APP_ID]);
});
},
renderCommon: function(isRefresh, isDateChange) {
var sessionData = countlySession.getSessionData(),
locationData = countlyLocation.getLocationData({maxCountries: 7});
this.locationData = locationData;
sessionData["page-title"] = jQuery.i18n.map["sidebar.dashboard"];
sessionData.usage = [
{
"title": jQuery.i18n.map["common.total-sessions"],
"material-icon": "timeline",
"data": sessionData.usage['total-sessions'],
"id": "draw-total-sessions",
"help": "dashboard.total-sessions"
},
{
"title": jQuery.i18n.map["common.total-users"],
"ion-icon": "ion-person-stalker",
"data": sessionData.usage['total-users'],
"id": "draw-total-users",
"help": "dashboard.total-users"
},
{
"title": jQuery.i18n.map["common.new-users"],
"ion-icon": "ion-person-add",
"data": sessionData.usage['new-users'],
"id": "draw-new-users",
"help": "dashboard.new-users"
},
{
"title": jQuery.i18n.map["dashboard.time-spent"],
"ion-icon": "ion-android-time",
"data": sessionData.usage['total-duration'],
"id": "draw-total-time-spent",
"help": "dashboard.total-time-spent"
},
{
"title": jQuery.i18n.map["dashboard.avg-time-spent"],
"material-icon": "timelapse",
"data": sessionData.usage['avg-duration-per-session'],
"id": "draw-time-spent",
"help": "dashboard.avg-time-spent2"
},
{
"title": jQuery.i18n.map["dashboard.avg-reqs-received"],
"material-icon": "compare_arrows",
"data": sessionData.usage['avg-events'],
"id": "draw-avg-events-served",
"help": "dashboard.avg-reqs-received"
}
];
sessionData.bars = [
{
"title": jQuery.i18n.map["common.bar.top-platform"],
"data": countlyAnalyticsAPI.getTop('platforms'),
"help": "dashboard.top-platforms"
},
{
"title": jQuery.i18n.map["common.bar.top-sources"],
"data": countlyAnalyticsAPI.getTop('sources'),
"help": "dashboard.top-sources"
},
{
"title": jQuery.i18n.map["common.bar.top-browsers"],
"data": countlyAnalyticsAPI.getTop('browser'),
"help": "dashboard.top-browsers"
},
{
"title": jQuery.i18n.map["common.bar.top-users"],
"data": countlySession.getTopUserBars(),
"help": "dashboard.top-users"
}
];
this.templateData = sessionData;
if (!isRefresh) {
$(this.el).html(this.template(this.templateData));
CountlyHelpers.applyColors();
$('.data-type-selector-group').find('div').removeClass('active');
$(this.selectedMap).addClass('active');
if (!countlyGlobal.config.use_google) {
$(".map-list.geo-switch").hide();
}
$(".map-list").after('<table id="last-visitors" class="d-table help-zone-vb" cellpadding="0" cellspacing="0"></table>');
var users = countlyWebDashboard.getLatestUsers();
var sort = 3;
var columns = [
{
"mData": function(row) {
var img = (!row.cc) ? "unknown" : (row.cc + "").toLowerCase();
var name = (!row.cc) ? jQuery.i18n.map["common.unknown"] : row.cc + "";
var c = '<div class="flag ' + img + '" style="margin-top: 2px; background-image: url(images/flags/' + img + '.png);"></div>' + name;
if (row.cty && row.cty !== jQuery.i18n.map["common.unknown"]) {
c += " (" + row.cty + ")";
}
return c;
},
"sType": "string",
"sTitle": jQuery.i18n.map["countries.table.country"],
"bSortable": false,
"sClass": "break web-15"
},
{
"mData": function(row) {
return (!row.p) ? jQuery.i18n.map["common.unknown"] : row.p;
},
"sType": "string",
"sTitle": jQuery.i18n.map["platforms.table.platform"],
"bSortable": false
}
];
if (users[0] && users[0].brw) {
columns.push({
"mData": function(row) {
return (!row.brw) ? jQuery.i18n.map["common.unknown"] : row.brw;
},
"sType": "string",
"sTitle": jQuery.i18n.map["web.browser"],
"bSortable": false
});
sort++;
}
if (users[0] && users[0].lv) {
columns.push({
"mData": function(row) {
return (!row.lv) ? jQuery.i18n.map["common.unknown"] : row.lv;
},
"sType": "string",
"sTitle": jQuery.i18n.map["web.views.view"],
"bSortable": false,
"sClass": "trim web-20"
});
sort++;
}
if (users[0] && users[0].src) {
columns.push({
"mData": function(row) {
if (!row.src) {
return jQuery.i18n.map["common.unknown"];
}
else {
row.src = row.src.replace(/./g, ".").replace(/&#46;/g, '.'); if (row.src.indexOf("http") === 0) {
return "<a href='" + row.src + "' target='_blank'>" + ((typeof countlySources !== "undefined") ? countlySources.getSourceName(row.src) : row.src) + "</a>";
}
else {
return (typeof countlySources !== "undefined") ? countlySources.getSourceName(row.src) : row.src;
}
}
},
"sType": "string",
"sTitle": jQuery.i18n.map["web.from-source"],
"bSortable": false,
"sClass": "break web-20"
});
sort++;
}
columns.push({
"mData": function(row) {
return (!row.sc) ? 0 : row.sc;
},
"sType": "numeric",
"sTitle": jQuery.i18n.map["web.total-sessions"],
"bSortable": false
},
{
"mData": function(row, type) {
if (type === "display") {
return (row.lac) ? countlyCommon.formatTimeAgo(row.lac) : jQuery.i18n.map["web.never"];
}
else {
return (row.lac) ? row.lac : 0;
}
},
"sType": "format-ago",
"sTitle": jQuery.i18n.map["web.last-seen"],
"bSortable": false
},
{
"mData": function(row) {
return countlyCommon.formatTime((row.tsd) ? parseInt(row.tsd) : 0);
},
"sType": "numeric",
"sTitle": jQuery.i18n.map["web.time-spent"],
"bSortable": false
});
this.latestdtable = $('#last-visitors').dataTable($.extend({}, $.fn.dataTable.defaults, {
"aaData": users,
"iDisplayLength": 10,
"aoColumns": columns
}));
this.latestdtable.stickyTableHeaders();
this.latestdtable.fnSort([ [sort, 'desc'] ]);
$("#last-visitors_wrapper .dataTable-top .search-table-data").hide();
$("#last-visitors_wrapper .dataTable-top .save-table-data").hide();
$("#last-visitors_wrapper .dataTable-top").append("<div style='font:15px Ubuntu,Helvetica,sans-serif; color:#636363; margin-left:10px; margin-top: 8px; text-transform: uppercase;'>" + jQuery.i18n.map["web.latest-visitors"] + "</div>");
$(this.selectedView).parents(".big-numbers").addClass("active");
this.pageScript();
if (!isDateChange) {
this.drawGraph();
}
app.graphNotesView.addNotesMenuLink(this);
}
if (!countlyGlobal.config.use_google) {
this.countryTable(isRefresh);
}
else {
countlyLocation.refreshGeoChart(this.maps[this.curMap]);
}
},
restart: function() {
this.refresh(true);
},
refresh: function(isFromIdle) {
var self = this;
$.when(this.beforeRender(true)).then(function() {
if (app.activeView !== self) {
return false;
}
self.renderCommon(true);
CountlyHelpers.refreshTable(self.latestdtable, countlyWebDashboard.getLatestUsers());
var newPage = $("<div>" + self.template(self.templateData) + "</div>");
$(".dashboard-summary").replaceWith(newPage.find(".dashboard-summary"));
$(".widget-header .title").replaceWith(newPage.find(".widget-header .title"));
$("#big-numbers-container").find(".big-numbers").each(function(i, el) {
var newEl = $(newPage.find("#big-numbers-container .big-numbers")[i]);
if (isFromIdle) {
$(el).find(".number").replaceWith(newEl.find(".number"));
}
else {
var currNumberEl = $(el).find(".number .value"),
currNumberVal = parseFloat(currNumberEl.text()) || 0,
currNumPost = currNumberEl.text().replace(currNumberVal, ''),
targetValue = parseFloat(newEl.find(".number .value").text()),
targetPost = newEl.find(".number .value").text().replace(targetValue, '');
if (targetValue !== currNumberVal) {
if (targetValue < currNumberVal || (targetPost.length && targetPost !== currNumPost)) {
$(el).find(".number").replaceWith(newEl.find(".number"));
}
else {
jQuery({someValue: currNumberVal, currEl: currNumberEl}).animate({someValue: targetValue}, {
duration: 2000,
easing: 'easeInOutQuint',
step: function() {
if ((targetValue + "").indexOf(".") === -1) {
this.currEl.text(Math.round(this.someValue) + targetPost);
}
else {
this.currEl.text(parseFloat((this.someValue).toFixed(1)) + targetPost);
}
}
});
}
}
}
$(el).find(".trend").replaceWith(newEl.find(".trend"));
$(el).find(".spark").replaceWith(newEl.find(".spark"));
});
self.drawGraph();
$(".usparkline").peity("bar", { width: "100%", height: "30", colour: "#83C986", strokeColour: "#83C986", strokeWidth: 2 });
$(".dsparkline").peity("bar", { width: "100%", height: "30", colour: "#DB6E6E", strokeColour: "#DB6E6E", strokeWidth: 2 });
if (newPage.find("#map-list-right").length === 0) {
$("#map-list-right").remove();
}
if ($("#map-list-right").length) {
$("#map-list-right").replaceWith(newPage.find("#map-list-right"));
}
else {
$(".widget.map-list").prepend(newPage.find("#map-list-right"));
}
self.pageScript();
});
},
countryList: function() {
var self = this;
$("#map-list-right").empty();
var country;
var type = self.curMap === "map-list-sessions" ? "t" : self.curMap === "map-list-users" ? "u" : self.curMap === "map-list-new" ? "n" : "";
self.locationData = countlyLocation.orderByType(type, self.locationData);
for (var i = 0; i < self.locationData.length; i++) {
country = self.locationData[i];
$("#map-list-right").append('<div class="map-list-item">' +
'<div class="flag ' + country.code + '" style="background-image:url(\'' + countlyGlobal.cdn + 'images/flags/' + country.code + '.png\');"></div>' +
'<div class="country-name">' + country.country + '</div>' +
'<div class="total">' + country[self.maps[self.curMap].metric] + '</div>' +
'</div>');
}
if (self.locationData.length === 0) {
$("#geo-chart-outer").addClass("empty");
}
else {
$("#geo-chart-outer").removeClass("empty");
}
},
countryTable: function(refresh) {
var self = this;
if (!refresh) {
$(".map-list").after('<table id="countries-alternative" class="d-table help-zone-vb" cellpadding="0" cellspacing="0"></table>');
this.country_dtable = $('#countries-alternative').dataTable($.extend({}, $.fn.dataTable.defaults, {
"aaData": self.locationData,
"iDisplayLength": 10,
"aoColumns": [
{ "mData": "country_flag", "sType": "string", "sTitle": jQuery.i18n.map["countries.table.country"]},
{ "mData": "t", "sType": "numeric", "sTitle": jQuery.i18n.map["common.table.total-sessions"]},
{ "mData": "u", "sType": "numeric", "sTitle": jQuery.i18n.map["common.table.total-users"]},
{ "mData": "n", "sType": "numeric", "sTitle": jQuery.i18n.map["common.table.new-users"]}
]
}));
this.country_dtable.stickyTableHeaders();
this.country_dtable.fnSort([ [1, 'desc'] ]);
$("#countries-alternative_wrapper .dataTable-top .search-table-data").hide();
$("#countries-alternative_wrapper .dataTable-top .save-table-data").hide();
$("#countries-alternative_wrapper .dataTable-top .dataTables_paginate").hide();
$("#countries-alternative_wrapper .dataTable-top .DTTT_container").hide();
$("#countries-alternative_wrapper .dataTable-top").append("<div style='font:13px Ubuntu,Helvetica,sans-serif; color:#636363; margin-right:10px; padding: 10px; float: right;'><a href='#/analytics/countries'>" + jQuery.i18n.map["common.go-to-countries"] + " <i class='fa fa-chevron-right' aria-hidden='true'></i></a></div>");
$("#countries-alternative_wrapper .dataTable-top").append("<div style='font:15px Ubuntu,Helvetica,sans-serif; color:#636363; margin-left:10px; margin-top: 8px; text-transform: uppercase;'>" + jQuery.i18n.map["sidebar.analytics.countries"] + "</div>");
}
else {
CountlyHelpers.refreshTable(self.country_dtable, countlyLocation.getLocationData({maxCountries: 10}));
}
},
destroy: function() {
$("#content-top").html("");
}
});
app.addAppType("web", WebDashboardView);
app.addAppSetting("app_domain", {
toDisplay: function(appId, elem) {
$(elem).text(countlyGlobal.apps[appId].app_domain);
},
toInput: function(appId, elem) {
$(elem).val(countlyGlobal.apps[appId].app_domain);
},
toSave: function(appId, args, elem) {
var domainEvent = $(elem).val();
args.app_domain = domainEvent;
},
toInject: function() {
var addApp = '<tr class="appmng-domain">' +
'<td>' +
'<span data-localize="management-applications.app-domain"></span>' +
'</td>' +
'<td>' +
'<input type="text" value="" class="app-write-settings" data-id="app_domain" placeholder="Enter website domain..." data-localize="placeholder.app-domain-key" id="app-add-app-domain"></span>' +
'</td>' +
'</tr>';
var addFirstApp = '<div class="add-app-input-wrapper" id="first-app-domain-setting">' +
'<label class="add-app-input-label" data-localize="management-applications.app-domain"></label><label class="add-app-input-optional-text">Optional</label>' +
'<input value="" placeholder="Enter application name..." placeholder="Enter website domain..." class="add-app-input-text" data-localize="placeholder.app-domain-key" id="first-app-add-app-domain">' +
'</div>';
$('#add-first-app > div:nth-child(4)').after(addFirstApp);
$("#add-new-app table .table-add").before(addApp);
var editApp = '<tr class="appmng-domain">' +
'<td>' +
'<span data-localize="management-applications.app-domain"></span>' +
'</td>' +
'<td id="app-edit-domain">' +
'<div class="read app-read-settings" data-id="app_domain"></div>' +
'<div class="edit">' +
'<input type="text" value="" class="app-write-settings" data-id="app_domain" data-localize="placeholder.app-domain-key" id="app-edit-app-domain"></span>' +
'</div>' +
'</td>' +
'</tr>';
$(".app-details table .table-edit").before(editApp);
}
});
app.addPageScript("/manage/apps", function() {
var appId = countlyCommon.ACTIVE_APP_ID;
if (!countlyGlobal.apps[appId] || countlyGlobal.apps[appId].type === "web") {
$(".appmng-domain").show();
$('#first-app-domain-setting').show();
}
else {
$(".appmng-domain").hide();
$('#first-app-domain-setting').hide();
}
});
app.addAppManagementSwitchCallback(function(appId, type) {
if (type === "web") {
$(".appmng-domain").show();
$('#first-app-domain-setting').show();
}
else {
$(".appmng-domain").hide();
$('#first-app-domain-setting').hide();
}
});
app.webDashboardView = new WebDashboardView();
$(document).ready(function() {
if (countlyAuth.validateRead('core')) {
app.addSubMenuForType("web", "analytics", {code: "analytics-technology", url: "#/analytics/technology", text: "sidebar.analytics.technology", priority: 40});
app.addSubMenuForType("web", "analytics", {code: "analytics-geo", url: "#/analytics/geo", text: "sidebar.analytics.geo", priority: 30});
app.addSubMenuForType("web", "analytics", {code: "analytics-sessions", url: "#/analytics/sessions", text: "sidebar.analytics.session", priority: 20});
app.addSubMenuForType("web", "analytics", {code: "analytics-users", url: "#/analytics/users", text: "sidebar.analytics.users", priority: 10});
app.addSubMenuForType("web", "analytics", {code: "analytics-loyalty", url: "#/analytics/loyalty", text: "sidebar.analytics.user-loyalty", priority: 15});
}
app.addAppSwitchCallback(function(appId) {
if (countlyGlobal.apps[appId].type === "web") {
//views = page views
jQuery.i18n.map["drill.lv"] = jQuery.i18n.map["web.drill.lv"];
jQuery.i18n.map["views.title"] = jQuery.i18n.map["web.views.title"];
jQuery.i18n.map["views.view"] = jQuery.i18n.map["web.views.view"];
//crashes = errors
jQuery.i18n.map["crashes.title"] = jQuery.i18n.map["web.crashes.title"];
jQuery.i18n.map["crashes.unresolved-crashes"] = jQuery.i18n.map["web.crashes.unresolved-crashes"];
jQuery.i18n.map["crashes.groupid"] = jQuery.i18n.map["web.crashes.groupid"];
jQuery.i18n.map["crashes.crashed"] = jQuery.i18n.map["web.crashes.crashed"];
jQuery.i18n.map["crashes.last-crash"] = jQuery.i18n.map["web.crashes.last-crash"];
jQuery.i18n.map["crashes.online"] = jQuery.i18n.map["web.crashes.online"];
jQuery.i18n.map["crashes.muted"] = jQuery.i18n.map["web.crashes.muted"];
jQuery.i18n.map["crashes.background"] = jQuery.i18n.map["web.crashes.background"];
jQuery.i18n.map["crashes.back-to-crashes"] = jQuery.i18n.map["web.crashes.back-to-crashes"];
jQuery.i18n.map["crashes.back-to-crash"] = jQuery.i18n.map["web.crashes.back-to-crash"];
jQuery.i18n.map["crashes.crashes-by"] = jQuery.i18n.map["web.crashes.crashes-by"];
jQuery.i18n.map["crashes.unique"] = jQuery.i18n.map["web.crashes.unique"];
jQuery.i18n.map["crashes.rate"] = jQuery.i18n.map["web.crashes.rate"];
jQuery.i18n.map["crashes.top-crash"] = jQuery.i18n.map["web.crashes.top-crash"];
jQuery.i18n.map["crashes.new-crashes"] = jQuery.i18n.map["web.crashes.new-crashes"];
jQuery.i18n.map["crashes.fatality"] = jQuery.i18n.map["web.crashes.fatality"];
jQuery.i18n.map["crashes.nonfatal-crashes"] = jQuery.i18n.map["web.crashes.nonfatal-crashes"];
jQuery.i18n.map["crashes.confirm-delete"] = jQuery.i18n.map["web.crashes.confirm-delete"];
jQuery.i18n.map["drill.crash"] = jQuery.i18n.map["web.drill.crash"];
jQuery.i18n.map["drill.crash-segments"] = jQuery.i18n.map["web.drill.crash-segments"];
jQuery.i18n.map["userdata.crashes"] = jQuery.i18n.map["web.userdata.crashes"];
//users = visitors
jQuery.i18n.map["common.total-users"] = jQuery.i18n.map["web.common.total-users"];
jQuery.i18n.map["common.new-users"] = jQuery.i18n.map["web.common.new-users"];
jQuery.i18n.map["common.returning-users"] = jQuery.i18n.map["web.common.returning-users"];
jQuery.i18n.map["common.number-of-users"] = jQuery.i18n.map["web.common.number-of-users"];
jQuery.i18n.map["common.table.total-users"] = jQuery.i18n.map["web.common.table.total-users"];
jQuery.i18n.map["common.table.new-users"] = jQuery.i18n.map["web.common.table.new-users"];
jQuery.i18n.map["common.table.returning-users"] = jQuery.i18n.map["web.common.table.returning-users"];
jQuery.i18n.map["common.bar.top-users"] = jQuery.i18n.map["web.common.bar.top-users"];
jQuery.i18n.map["sidebar.analytics.users"] = jQuery.i18n.map["web.sidebar.analytics.users"];
jQuery.i18n.map["sidebar.analytics.user-loyalty"] = jQuery.i18n.map["web.sidebar.analytics.user-loyalty"];
jQuery.i18n.map["users.title"] = jQuery.i18n.map["web.users.title"];
jQuery.i18n.map["crashes.users"] = jQuery.i18n.map["web.crashes.users"];
jQuery.i18n.map["crashes.affected-users"] = jQuery.i18n.map["web.crashes.affected-users"];
jQuery.i18n.map["crashes.public-users"] = jQuery.i18n.map["web.crashes.public-users"];
jQuery.i18n.map["drill.users"] = jQuery.i18n.map["web.drill.users"];
jQuery.i18n.map["drill.times-users"] = jQuery.i18n.map["web.drill.times-users"];
jQuery.i18n.map["drill.sum-users"] = jQuery.i18n.map["web.drill.sum-users"];
jQuery.i18n.map["funnels.total-users"] = jQuery.i18n.map["web.funnels.total-users"];
jQuery.i18n.map["funnels.users"] = jQuery.i18n.map["web.funnels.users"];
jQuery.i18n.map["common.online-users"] = jQuery.i18n.map["web.common.online-users"];
jQuery.i18n.map["live.new-users"] = jQuery.i18n.map["web.live.new-users"];
jQuery.i18n.map["populator.amount-users"] = jQuery.i18n.map["web.populator.amount-users"];
jQuery.i18n.map["sidebar.engagement.retention"] = jQuery.i18n.map["web.sidebar.engagement.retention"];
jQuery.i18n.map["retention.users-first-session"] = jQuery.i18n.map["web.retention.users-first-session"];
jQuery.i18n.map["userdata.title"] = jQuery.i18n.map["web.userdata.title"];
jQuery.i18n.map["userdata.users"] = jQuery.i18n.map["web.userdata.users"];
jQuery.i18n.map["userdata.user"] = jQuery.i18n.map["web.userdata.user"];
jQuery.i18n.map["userdata.back-to-list"] = jQuery.i18n.map["web.userdata.back-to-list"];
jQuery.i18n.map["userdata.no-users"] = jQuery.i18n.map["web.userdata.no-users"];
jQuery.i18n.map["attribution.per-user"] = jQuery.i18n.map["web.attribution.per-user"];
jQuery.i18n.map["attribution.user-conversion"] = jQuery.i18n.map["web.attribution.user-conversion"];
jQuery.i18n.map["attribution.organic"] = jQuery.i18n.map["web.attribution.organic"];
jQuery.i18n.map["reports.total_users"] = jQuery.i18n.map["web.reports.total_users"];
jQuery.i18n.map["reports.new_users"] = jQuery.i18n.map["web.reports.new_users"];
jQuery.i18n.map["reports.paying_users"] = jQuery.i18n.map["web.reports.paying_users"];
jQuery.i18n.map["reports.messaging_users"] = jQuery.i18n.map["web.reports.messaging_users"];
jQuery.i18n.map["reports.returning_users"] = jQuery.i18n.map["web.reports.returning_users"];
jQuery.i18n.map["common.per-user"] = jQuery.i18n.map["web.common.per-user"];
jQuery.i18n.map["common.per-paying-user"] = jQuery.i18n.map["web.common.per-paying-user"];
jQuery.i18n.map["common.users"] = jQuery.i18n.map["web.common.users"];
jQuery.i18n.map["attribution.installs"] = jQuery.i18n.map["web.attribution.installs"];
jQuery.i18n.map["attribution.cost-install"] = jQuery.i18n.map["web.attribution.cost-install"];
jQuery.i18n.map["sources.title"] = jQuery.i18n.map["web.sources.title"];
jQuery.i18n.map["sources.source"] = jQuery.i18n.map["web.sources.source"];
}
});
}); | 1 | 14,500 | Same user/visitor thing. | Countly-countly-server | js |
@@ -167,6 +167,13 @@ exit /B %errorlevel%
reg_query_command = %Q(reg query "#{reg_key}" /v "RememberedPuppetAgentStartupMode" | findstr #{msi_opts['PUPPET_AGENT_STARTUP_MODE']})
on host, Command.new(reg_query_command, [], { :cmdexe => true })
+ # (PA-620) environment.bat should be run before any cmd.exe shell command
+ # in order to properly set up environment variables
+ auto_run_key = "HKLM\\SOFTWARE\\Microsoft\\Command Processor\AutoRun"
+ # TODO What's the best way to get the actual path to the script, respecting arch differences?
+ environment_script = "C:\\Program Files\\Puppet Labs\\Puppet\bin\\environment.bat"
+ reg_add_command = %Q(reg add "#{auto_run_key}" /v "PuppetEnvironment" /d "#{environment_script}")
+
# emit the misc/versions.txt file which contains component versions for
# puppet, facter, hiera, pxp-agent, packaging and vendored Ruby
[ | 1 | module Beaker
module DSL
module InstallUtils
#
# This module contains methods useful for Windows installs
#
module WindowsUtils
# Given a host, returns it's system TEMP path
#
# @param [Host] host An object implementing {Beaker::Hosts}'s interface.
#
# @return [String] system temp path
def get_system_temp_path(host)
host.system_temp_path
end
alias_method :get_temp_path, :get_system_temp_path
# Generates commands to be inserted into a Windows batch file to launch an MSI install
# @param [String] msi_path The path of the MSI - can be a local Windows style file path like
# c:\temp\puppet.msi OR a url like https://download.com/puppet.msi or file://c:\temp\puppet.msi
# @param [Hash{String=>String}] msi_opts MSI installer options
# See https://docs.puppetlabs.com/guides/install_puppet/install_windows.html#msi-properties
# @param [String] log_path The path to write the MSI log - must be a local Windows style file path
#
# @api private
def msi_install_script(msi_path, msi_opts, log_path)
# msiexec requires backslashes in file paths launched under cmd.exe start /w
url_pattern = /^(https?|file):\/\//
msi_path = msi_path.gsub(/\//, "\\") if msi_path !~ url_pattern
msi_params = msi_opts.map{|k, v| "#{k}=#{v}"}.join(' ')
# msiexec requires quotes around paths with backslashes - c:\ or file://c:\
# not strictly needed for http:// but it simplifies this code
batch_contents = <<-BATCH
start /w msiexec.exe /i \"#{msi_path}\" /qn /L*V #{log_path} #{msi_params}
exit /B %errorlevel%
BATCH
end
# Given a host, path to MSI and MSI options, will create a batch file
# on the host, returning the path to the randomized batch file and
# the randomized log file
#
# @param [Host] host An object implementing {Beaker::Hosts}'s interface.
# @param [String] msi_path The path of the MSI - can be a local Windows
# style file path like c:\temp\puppet.msi OR a url like
# https://download.com/puppet.msi or file://c:\temp\puppet.msi
# @param [Hash{String=>String}] msi_opts MSI installer options
# See https://docs.puppetlabs.com/guides/install_puppet/install_windows.html#msi-properties
#
# @api private
# @return [String, String] path to the batch file, patch to the log file
def create_install_msi_batch_on(host, msi_path, msi_opts)
timestamp = Time.new.strftime('%Y-%m-%d_%H.%M.%S')
tmp_path = host.system_temp_path
tmp_path.gsub!('/', '\\')
batch_name = "install-puppet-msi-#{timestamp}.bat"
batch_path = "#{tmp_path}#{host.scp_separator}#{batch_name}"
log_path = "#{tmp_path}\\install-puppet-#{timestamp}.log"
Tempfile.open(batch_name) do |tmp_file|
batch_contents = msi_install_script(msi_path, msi_opts, log_path)
File.open(tmp_file.path, 'w') { |file| file.puts(batch_contents) }
host.do_scp_to(tmp_file.path, batch_path, {})
end
return batch_path, log_path
end
# Given hosts construct a PATH that includes puppetbindir, facterbindir and hierabindir
# @param [Host, Array<Host>, String, Symbol] hosts One or more hosts to act upon,
# or a role (String or Symbol) that identifies one or more hosts.
# @param [String] msi_path The path of the MSI - can be a local Windows style file path like
# c:\temp\puppet.msi OR a url like https://download.com/puppet.msi or file://c:\temp\puppet.msi
# @param [Hash{String=>String}] msi_opts MSI installer options
# See https://docs.puppetlabs.com/guides/install_puppet/install_windows.html#msi-properties
# @option msi_opts [String] INSTALLIDIR Where Puppet and its dependencies should be installed.
# (Defaults vary based on operating system and intaller architecture)
# Requires Puppet 2.7.12 / PE 2.5.0
# @option msi_opts [String] PUPPET_MASTER_SERVER The hostname where the puppet master server can be reached.
# (Defaults to puppet)
# Requires Puppet 2.7.12 / PE 2.5.0
# @option msi_opts [String] PUPPET_CA_SERVER The hostname where the CA puppet master server can be reached, if you are using multiple masters and only one of them is acting as the CA.
# (Defaults the value of PUPPET_MASTER_SERVER)
# Requires Puppet 2.7.12 / PE 2.5.0
# @option msi_opts [String] PUPPET_AGENT_CERTNAME The node’s certificate name, and the name it uses when requesting catalogs. This will set a value for
# (Defaults to the node's fqdn as discovered by facter fqdn)
# Requires Puppet 2.7.12 / PE 2.5.0
# @option msi_opts [String] PUPPET_AGENT_ENVIRONMENT The node’s environment.
# (Defaults to production)
# Requires Puppet 3.3.1 / PE 3.1.0
# @option msi_opts [String] PUPPET_AGENT_STARTUP_MODE Whether the puppet agent service should run (or be allowed to run)
# (Defaults to Manual - valid values are Automatic, Manual or Disabled)
# Requires Puppet 3.4.0 / PE 3.2.0
# @option msi_opts [String] PUPPET_AGENT_ACCOUNT_USER Whether the puppet agent service should run (or be allowed to run)
# (Defaults to LocalSystem)
# Requires Puppet 3.4.0 / PE 3.2.0
# @option msi_opts [String] PUPPET_AGENT_ACCOUNT_PASSWORD The password to use for puppet agent’s user account
# (No default)
# Requires Puppet 3.4.0 / PE 3.2.0
# @option msi_opts [String] PUPPET_AGENT_ACCOUNT_DOMAIN The domain of puppet agent’s user account.
# (Defaults to .)
# Requires Puppet 3.4.0 / PE 3.2.0
# @option opts [Boolean] :debug output the MSI installation log when set to true
# otherwise do not output log (false; default behavior)
#
# @example
# install_msi_on(hosts, 'c:\puppet.msi', {:debug => true})
#
# @api private
def install_msi_on(hosts, msi_path, msi_opts = {}, opts = {})
block_on hosts do | host |
msi_opts['PUPPET_AGENT_STARTUP_MODE'] ||= 'Manual'
batch_path, log_file = create_install_msi_batch_on(host, msi_path, msi_opts)
# begin / rescue here so that we can reuse existing error msg propagation
begin
# 1641 = ERROR_SUCCESS_REBOOT_INITIATED
# 3010 = ERROR_SUCCESS_REBOOT_REQUIRED
on host, Command.new("\"#{batch_path}\"", [], { :cmdexe => true }), :acceptable_exit_codes => [0, 1641, 3010]
rescue
on host, Command.new("type \"#{log_file}\"", [], { :cmdexe => true })
raise
end
if opts[:debug]
on host, Command.new("type \"#{log_file}\"", [], { :cmdexe => true })
end
if !host.is_cygwin?
# HACK: for some reason, post install we need to refresh the connection to make puppet available for execution
host.close
end
# verify service status post install
# if puppet service exists, then pe-puppet is not queried
# if puppet service does not exist, pe-puppet is queried and that exit code is used
# therefore, this command will always exit 0 if either service is installed
#
# We also take advantage of this output to verify the startup
# settings are honored as supplied to the MSI
on host, Command.new("sc qc puppet || sc qc pe-puppet", [], { :cmdexe => true }) do |result|
output = result.stdout
startup_mode = msi_opts['PUPPET_AGENT_STARTUP_MODE'].upcase
search = case startup_mode
when 'AUTOMATIC'
{ :code => 2, :name => 'AUTO_START' }
when 'MANUAL'
{ :code => 3, :name => 'DEMAND_START' }
when 'DISABLED'
{ :code => 4, :name => 'DISABLED' }
end
if output !~ /^\s+START_TYPE\s+:\s+#{search[:code]}\s+#{search[:name]}/
raise "puppet service startup mode did not match supplied MSI option '#{startup_mode}'"
end
end
# (PA-514) value for PUPPET_AGENT_STARTUP_MODE should be present in
# registry and honored after install/upgrade.
reg_key = host.is_x86_64? ? "HKLM\\SOFTWARE\\Wow6432Node\\Puppet Labs\\PuppetInstaller" :
"HKLM\\SOFTWARE\\Puppet Labs\\PuppetInstaller"
reg_query_command = %Q(reg query "#{reg_key}" /v "RememberedPuppetAgentStartupMode" | findstr #{msi_opts['PUPPET_AGENT_STARTUP_MODE']})
on host, Command.new(reg_query_command, [], { :cmdexe => true })
# emit the misc/versions.txt file which contains component versions for
# puppet, facter, hiera, pxp-agent, packaging and vendored Ruby
[
"\\\"%ProgramFiles%\\Puppet Labs\\puppet\\misc\\versions.txt\\\"",
"\\\"%ProgramFiles(x86)%\\Puppet Labs\\puppet\\misc\\versions.txt\\\""
].each do |path|
on host, Command.new("\"if exist #{path} type #{path}\"", [], { :cmdexe => true })
end
end
end
# Installs a specified msi path on given hosts
# @param [Host, Array<Host>, String, Symbol] hosts One or more hosts to act upon,
# or a role (String or Symbol) that identifies one or more hosts.
# @param [String] msi_path The path of the MSI - can be a local Windows style file path like
# c:\temp\foo.msi OR a url like https://download.com/foo.msi or file://c:\temp\foo.msi
# @param [Hash{String=>String}] msi_opts MSI installer options
# @option opts [Boolean] :debug output the MSI installation log when set to true
# otherwise do not output log (false; default behavior)
#
# @example
# generic_install_msi_on(hosts, 'https://releases.hashicorp.com/vagrant/1.8.4/vagrant_1.8.4.msi', {}, {:debug => true})
#
# @api private
def generic_install_msi_on(hosts, msi_path, msi_opts = {}, opts = {})
block_on hosts do | host |
batch_path, log_file = create_install_msi_batch_on(host, msi_path, msi_opts)
# begin / rescue here so that we can reuse existing error msg propagation
begin
# 1641 = ERROR_SUCCESS_REBOOT_INITIATED
# 3010 = ERROR_SUCCESS_REBOOT_REQUIRED
on host, Command.new("\"#{batch_path}\"", [], { :cmdexe => true }), :acceptable_exit_codes => [0, 1641, 3010]
rescue
on host, Command.new("type \"#{log_file}\"", [], { :cmdexe => true })
raise
end
if opts[:debug]
on host, Command.new("type \"#{log_file}\"", [], { :cmdexe => true })
end
if !host.is_cygwin?
# HACK: for some reason, post install we need to refresh the connection to make puppet available for execution
host.close
end
end
end
end
end
end
end
| 1 | 13,991 | This is not the correct path on all hosts. How can I correctly determine whether I will need to look in `Program Files` or `Program Files (x86)` for the script? | voxpupuli-beaker | rb |
@@ -73,8 +73,15 @@ namespace OpenTelemetry.Exporter.Jaeger.Implementation
this.maxFlushIntervalTimer.Elapsed += async (sender, args) =>
{
- await this.FlushAsyncInternal(false, CancellationToken.None).ConfigureAwait(false);
- };
+ try
+ {
+ await this.FlushAsyncInternal(false, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ JaegerExporterEventSource.Log.FailedToSend(ex);
+ }
+ };
}
public Process Process { get; internal set; } | 1 | // <copyright file="JaegerUdpBatcher.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.Linq;
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Trace.Export;
using Thrift.Protocol;
using Thrift.Transport;
namespace OpenTelemetry.Exporter.Jaeger.Implementation
{
internal class JaegerUdpBatcher : IJaegerUdpBatcher
{
private readonly int maxPacketSize;
private readonly TProtocolFactory protocolFactory;
private readonly TTransport clientTransport;
private readonly JaegerThriftClient thriftClient;
private readonly InMemoryTransport memoryTransport;
private readonly TProtocol memoryProtocol;
private readonly SemaphoreSlim flushLock = new SemaphoreSlim(1);
private readonly TimeSpan maxFlushInterval;
private readonly System.Timers.Timer maxFlushIntervalTimer;
private Dictionary<string, Process> processCache;
private int batchByteSize;
private bool disposedValue = false; // To detect redundant calls
public JaegerUdpBatcher(JaegerExporterOptions options, TTransport clientTransport = null)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.MaxFlushInterval <= TimeSpan.Zero)
{
options.MaxFlushInterval = TimeSpan.FromSeconds(10);
}
this.maxPacketSize = (!options.MaxPacketSize.HasValue || options.MaxPacketSize <= 0) ? JaegerExporterOptions.DefaultMaxPacketSize : options.MaxPacketSize.Value;
this.protocolFactory = new TCompactProtocol.Factory();
this.clientTransport = clientTransport ?? new JaegerThriftClientTransport(options.AgentHost, options.AgentPort);
this.thriftClient = new JaegerThriftClient(this.protocolFactory.GetProtocol(this.clientTransport));
this.memoryTransport = new InMemoryTransport(16000);
this.memoryProtocol = this.protocolFactory.GetProtocol(this.memoryTransport);
this.Process = new Process(options.ServiceName, options.ProcessTags);
this.maxFlushInterval = options.MaxFlushInterval;
this.maxFlushIntervalTimer = new System.Timers.Timer
{
AutoReset = false,
Enabled = false,
Interval = this.maxFlushInterval.TotalMilliseconds,
};
this.maxFlushIntervalTimer.Elapsed += async (sender, args) =>
{
await this.FlushAsyncInternal(false, CancellationToken.None).ConfigureAwait(false);
};
}
public Process Process { get; internal set; }
internal Dictionary<string, Batch> CurrentBatches { get; } = new Dictionary<string, Batch>();
public async ValueTask<int> AppendAsync(SpanData span, CancellationToken cancellationToken)
{
if (this.processCache == null)
{
this.Process.Message = this.BuildThriftMessage(this.Process).ToArray();
this.processCache = new Dictionary<string, Process>
{
[this.Process.ServiceName] = this.Process,
};
}
var jaegerSpan = span.ToJaegerSpan();
var spanServiceName = jaegerSpan.PeerServiceName ?? this.Process.ServiceName;
if (!this.processCache.TryGetValue(spanServiceName, out var spanProcess))
{
spanProcess = new Process(spanServiceName, this.Process.Tags);
spanProcess.Message = this.BuildThriftMessage(spanProcess).ToArray();
this.processCache.Add(spanServiceName, spanProcess);
}
var spanMessage = this.BuildThriftMessage(jaegerSpan);
jaegerSpan.Return();
if (spanMessage.Count + spanProcess.Message.Length > this.maxPacketSize)
{
throw new JaegerExporterException($"ThriftSender received a span that was too large, size = {spanMessage.Count + spanProcess.Message.Length}, max = {this.maxPacketSize}", null);
}
var spanTotalBytesNeeded = spanMessage.Count;
var flushedSpanCount = 0;
await this.flushLock.WaitAsync().ConfigureAwait(false);
try
{
if (!this.CurrentBatches.TryGetValue(spanServiceName, out var spanBatch))
{
spanBatch = new Batch(spanProcess)
{
SpanMessages = new List<BufferWriterMemory>(),
};
this.CurrentBatches.Add(spanServiceName, spanBatch);
spanTotalBytesNeeded += spanProcess.Message.Length;
}
// flush if current batch size plus new span size equals or exceeds max batch size
if (this.batchByteSize + spanTotalBytesNeeded >= this.maxPacketSize)
{
flushedSpanCount = await this.FlushAsyncInternal(true, cancellationToken).ConfigureAwait(false);
// Flushing effectively erases the spanBatch we were working on, so we have to rebuild it.
spanBatch.SpanMessages.Clear();
spanTotalBytesNeeded = spanMessage.Count + spanProcess.Message.Length;
this.CurrentBatches.Add(spanServiceName, spanBatch);
}
else
{
this.maxFlushIntervalTimer.Enabled = true;
}
// add span to batch and wait for more spans
spanBatch.SpanMessages.Add(spanMessage);
this.batchByteSize += spanTotalBytesNeeded;
}
finally
{
this.flushLock.Release();
}
return flushedSpanCount;
}
public ValueTask<int> FlushAsync(CancellationToken cancellationToken) => this.FlushAsyncInternal(false, cancellationToken);
public ValueTask<int> CloseAsync(CancellationToken cancellationToken) => this.FlushAsyncInternal(false, cancellationToken);
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing).
this.Dispose(true);
}
protected async Task SendAsync(Dictionary<string, Batch> batches, CancellationToken cancellationToken)
{
try
{
foreach (var batch in batches)
{
await this.thriftClient.WriteBatchAsync(
batch.Value.Process.Message,
batch.Value.SpanMessages,
cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)
{
throw new JaegerExporterException($"Could not send {batches.Select(b => b.Value.SpanMessages.Count()).Sum()} spans", ex);
}
}
protected virtual void Dispose(bool disposing)
{
try
{
this.CloseAsync(CancellationToken.None).GetAwaiter().GetResult();
}
catch
{
}
if (!this.disposedValue)
{
if (disposing)
{
this.maxFlushIntervalTimer.Dispose();
this.thriftClient.Dispose();
this.clientTransport.Dispose();
this.memoryProtocol.Dispose();
this.flushLock.Dispose();
}
this.disposedValue = true;
}
}
private async ValueTask<int> FlushAsyncInternal(bool lockAlreadyHeld, CancellationToken cancellationToken)
{
if (!lockAlreadyHeld)
{
await this.flushLock.WaitAsync().ConfigureAwait(false);
}
try
{
this.maxFlushIntervalTimer.Enabled = false;
int n = this.CurrentBatches.Sum(b => b.Value.SpanMessages.Count);
if (n == 0)
{
return 0;
}
try
{
await this.SendAsync(this.CurrentBatches, cancellationToken).ConfigureAwait(false);
}
finally
{
this.CurrentBatches.Clear();
this.batchByteSize = 0;
this.memoryTransport.Reset();
}
return n;
}
finally
{
if (!lockAlreadyHeld)
{
this.flushLock.Release();
}
}
}
private BufferWriterMemory BuildThriftMessage(Process process)
{
var task = process.WriteAsync(this.memoryProtocol, CancellationToken.None);
#if DEBUG
if (task.Status != TaskStatus.RanToCompletion)
{
throw new InvalidOperationException();
}
#endif
return this.memoryTransport.ToBuffer();
}
// Prevents boxing of JaegerSpan struct.
private BufferWriterMemory BuildThriftMessage(in JaegerSpan jaegerSpan)
{
var task = jaegerSpan.WriteAsync(this.memoryProtocol, CancellationToken.None);
#if DEBUG
if (task.Status != TaskStatus.RanToCompletion)
{
throw new InvalidOperationException();
}
#endif
return this.memoryTransport.ToBuffer();
}
}
}
| 1 | 14,109 | I think it would be better to move this try/catch block inside of the `FlushAsyncInternal` function as there are a few of places that can call it, eg event timer (here), AppendAsync, FlushAsync and CloseAsync. | open-telemetry-opentelemetry-dotnet | .cs |
@@ -79,6 +79,7 @@ final class IndexingChain implements Accountable {
// Holds fields seen in each document
private PerField[] fields = new PerField[1];
+ private PerField[] docFields = new PerField[10];
private final InfoStream infoStream;
private final ByteBlockPool.Allocator byteBlockAllocator;
private final LiveIndexWriterConfig indexWriterConfig; | 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.index;
import java.io.Closeable;
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 java.util.function.Consumer;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.codecs.DocValuesFormat;
import org.apache.lucene.codecs.NormsConsumer;
import org.apache.lucene.codecs.NormsFormat;
import org.apache.lucene.codecs.NormsProducer;
import org.apache.lucene.codecs.PointsFormat;
import org.apache.lucene.codecs.PointsWriter;
import org.apache.lucene.codecs.VectorFormat;
import org.apache.lucene.codecs.VectorWriter;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.VectorField;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.ByteBlockPool;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefHash.MaxBytesLengthExceededException;
import org.apache.lucene.util.Counter;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.IntBlockPool;
import org.apache.lucene.util.RamUsageEstimator;
/** Default general purpose indexing chain, which handles indexing all types of fields. */
final class IndexingChain implements Accountable {
final Counter bytesUsed = Counter.newCounter();
final FieldInfos.Builder fieldInfos;
// Writes postings and term vectors:
final TermsHash termsHash;
// Writes stored fields
final StoredFieldsConsumer storedFieldsConsumer;
final TermVectorsConsumer termVectorsWriter;
// NOTE: I tried using Hash Map<String,PerField>
// but it was ~2% slower on Wiki and Geonames with Java
// 1.7.0_25:
private PerField[] fieldHash = new PerField[2];
private int hashMask = 1;
private int totalFieldCount;
private long nextFieldGen;
// Holds fields seen in each document
private PerField[] fields = new PerField[1];
private final InfoStream infoStream;
private final ByteBlockPool.Allocator byteBlockAllocator;
private final LiveIndexWriterConfig indexWriterConfig;
private final int indexCreatedVersionMajor;
private final Consumer<Throwable> abortingExceptionConsumer;
private boolean hasHitAbortingException;
IndexingChain(
int indexCreatedVersionMajor,
SegmentInfo segmentInfo,
Directory directory,
FieldInfos.Builder fieldInfos,
LiveIndexWriterConfig indexWriterConfig,
Consumer<Throwable> abortingExceptionConsumer) {
this.indexCreatedVersionMajor = indexCreatedVersionMajor;
byteBlockAllocator = new ByteBlockPool.DirectTrackingAllocator(bytesUsed);
IntBlockPool.Allocator intBlockAllocator = new IntBlockAllocator(bytesUsed);
this.indexWriterConfig = indexWriterConfig;
assert segmentInfo.getIndexSort() == indexWriterConfig.getIndexSort();
this.fieldInfos = fieldInfos;
this.infoStream = indexWriterConfig.getInfoStream();
this.abortingExceptionConsumer = abortingExceptionConsumer;
if (segmentInfo.getIndexSort() == null) {
storedFieldsConsumer =
new StoredFieldsConsumer(indexWriterConfig.getCodec(), directory, segmentInfo);
termVectorsWriter =
new TermVectorsConsumer(
intBlockAllocator,
byteBlockAllocator,
directory,
segmentInfo,
indexWriterConfig.getCodec());
} else {
storedFieldsConsumer =
new SortingStoredFieldsConsumer(indexWriterConfig.getCodec(), directory, segmentInfo);
termVectorsWriter =
new SortingTermVectorsConsumer(
intBlockAllocator,
byteBlockAllocator,
directory,
segmentInfo,
indexWriterConfig.getCodec());
}
termsHash =
new FreqProxTermsWriter(
intBlockAllocator, byteBlockAllocator, bytesUsed, termVectorsWriter);
}
private void onAbortingException(Throwable th) {
assert th != null;
this.hasHitAbortingException = true;
abortingExceptionConsumer.accept(th);
}
private LeafReader getDocValuesLeafReader() {
return new DocValuesLeafReader() {
@Override
public NumericDocValues getNumericDocValues(String field) {
PerField pf = getPerField(field);
if (pf == null) {
return null;
}
if (pf.fieldInfo.getDocValuesType() == DocValuesType.NUMERIC) {
return (NumericDocValues) pf.docValuesWriter.getDocValues();
}
return null;
}
@Override
public BinaryDocValues getBinaryDocValues(String field) {
PerField pf = getPerField(field);
if (pf == null) {
return null;
}
if (pf.fieldInfo.getDocValuesType() == DocValuesType.BINARY) {
return (BinaryDocValues) pf.docValuesWriter.getDocValues();
}
return null;
}
@Override
public SortedDocValues getSortedDocValues(String field) throws IOException {
PerField pf = getPerField(field);
if (pf == null) {
return null;
}
if (pf.fieldInfo.getDocValuesType() == DocValuesType.SORTED) {
return (SortedDocValues) pf.docValuesWriter.getDocValues();
}
return null;
}
@Override
public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
PerField pf = getPerField(field);
if (pf == null) {
return null;
}
if (pf.fieldInfo.getDocValuesType() == DocValuesType.SORTED_NUMERIC) {
return (SortedNumericDocValues) pf.docValuesWriter.getDocValues();
}
return null;
}
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
PerField pf = getPerField(field);
if (pf == null) {
return null;
}
if (pf.fieldInfo.getDocValuesType() == DocValuesType.SORTED_SET) {
return (SortedSetDocValues) pf.docValuesWriter.getDocValues();
}
return null;
}
@Override
public FieldInfos getFieldInfos() {
return fieldInfos.finish();
}
};
}
private Sorter.DocMap maybeSortSegment(SegmentWriteState state) throws IOException {
Sort indexSort = state.segmentInfo.getIndexSort();
if (indexSort == null) {
return null;
}
LeafReader docValuesReader = getDocValuesLeafReader();
List<IndexSorter.DocComparator> comparators = new ArrayList<>();
for (int i = 0; i < indexSort.getSort().length; i++) {
SortField sortField = indexSort.getSort()[i];
IndexSorter sorter = sortField.getIndexSorter();
if (sorter == null) {
throw new UnsupportedOperationException("Cannot sort index using sort field " + sortField);
}
comparators.add(sorter.getDocComparator(docValuesReader, state.segmentInfo.maxDoc()));
}
Sorter sorter = new Sorter(indexSort);
// returns null if the documents are already sorted
return sorter.sort(
state.segmentInfo.maxDoc(), comparators.toArray(IndexSorter.DocComparator[]::new));
}
Sorter.DocMap flush(SegmentWriteState state) throws IOException {
// NOTE: caller (DocumentsWriterPerThread) handles
// aborting on any exception from this method
Sorter.DocMap sortMap = maybeSortSegment(state);
int maxDoc = state.segmentInfo.maxDoc();
long t0 = System.nanoTime();
writeNorms(state, sortMap);
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", ((System.nanoTime() - t0) / 1000000) + " msec to write norms");
}
SegmentReadState readState =
new SegmentReadState(
state.directory,
state.segmentInfo,
state.fieldInfos,
IOContext.READ,
state.segmentSuffix);
t0 = System.nanoTime();
writeDocValues(state, sortMap);
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", ((System.nanoTime() - t0) / 1000000) + " msec to write docValues");
}
t0 = System.nanoTime();
writePoints(state, sortMap);
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", ((System.nanoTime() - t0) / 1000000) + " msec to write points");
}
t0 = System.nanoTime();
writeVectors(state, sortMap);
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", ((System.nanoTime() - t0) / 1000000) + " msec to write vectors");
}
// it's possible all docs hit non-aborting exceptions...
t0 = System.nanoTime();
storedFieldsConsumer.finish(maxDoc);
storedFieldsConsumer.flush(state, sortMap);
if (infoStream.isEnabled("IW")) {
infoStream.message(
"IW", ((System.nanoTime() - t0) / 1000000) + " msec to finish stored fields");
}
t0 = System.nanoTime();
Map<String, TermsHashPerField> fieldsToFlush = new HashMap<>();
for (int i = 0; i < fieldHash.length; i++) {
PerField perField = fieldHash[i];
while (perField != null) {
if (perField.invertState != null) {
fieldsToFlush.put(perField.fieldInfo.name, perField.termsHashPerField);
}
perField = perField.next;
}
}
try (NormsProducer norms =
readState.fieldInfos.hasNorms()
? state.segmentInfo.getCodec().normsFormat().normsProducer(readState)
: null) {
NormsProducer normsMergeInstance = null;
if (norms != null) {
// Use the merge instance in order to reuse the same IndexInput for all terms
normsMergeInstance = norms.getMergeInstance();
}
termsHash.flush(fieldsToFlush, state, sortMap, normsMergeInstance);
}
if (infoStream.isEnabled("IW")) {
infoStream.message(
"IW",
((System.nanoTime() - t0) / 1000000) + " msec to write postings and finish vectors");
}
// Important to save after asking consumer to flush so
// consumer can alter the FieldInfo* if necessary. EG,
// FreqProxTermsWriter does this with
// FieldInfo.storePayload.
t0 = System.nanoTime();
indexWriterConfig
.getCodec()
.fieldInfosFormat()
.write(state.directory, state.segmentInfo, "", state.fieldInfos, IOContext.DEFAULT);
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", ((System.nanoTime() - t0) / 1000000) + " msec to write fieldInfos");
}
return sortMap;
}
/** Writes all buffered points. */
private void writePoints(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {
PointsWriter pointsWriter = null;
boolean success = false;
try {
for (int i = 0; i < fieldHash.length; i++) {
PerField perField = fieldHash[i];
while (perField != null) {
if (perField.pointValuesWriter != null) {
if (perField.fieldInfo.getPointDimensionCount() == 0) {
// BUG
throw new AssertionError(
"segment="
+ state.segmentInfo
+ ": field=\""
+ perField.fieldInfo.name
+ "\" has no points but wrote them");
}
if (pointsWriter == null) {
// lazy init
PointsFormat fmt = state.segmentInfo.getCodec().pointsFormat();
if (fmt == null) {
throw new IllegalStateException(
"field=\""
+ perField.fieldInfo.name
+ "\" was indexed as points but codec does not support points");
}
pointsWriter = fmt.fieldsWriter(state);
}
perField.pointValuesWriter.flush(state, sortMap, pointsWriter);
perField.pointValuesWriter = null;
} else if (perField.fieldInfo.getPointDimensionCount() != 0) {
// BUG
throw new AssertionError(
"segment="
+ state.segmentInfo
+ ": field=\""
+ perField.fieldInfo.name
+ "\" has points but did not write them");
}
perField = perField.next;
}
}
if (pointsWriter != null) {
pointsWriter.finish();
}
success = true;
} finally {
if (success) {
IOUtils.close(pointsWriter);
} else {
IOUtils.closeWhileHandlingException(pointsWriter);
}
}
}
/** Writes all buffered doc values (called from {@link #flush}). */
private void writeDocValues(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {
DocValuesConsumer dvConsumer = null;
boolean success = false;
try {
for (int i = 0; i < fieldHash.length; i++) {
PerField perField = fieldHash[i];
while (perField != null) {
if (perField.docValuesWriter != null) {
if (perField.fieldInfo.getDocValuesType() == DocValuesType.NONE) {
// BUG
throw new AssertionError(
"segment="
+ state.segmentInfo
+ ": field=\""
+ perField.fieldInfo.name
+ "\" has no docValues but wrote them");
}
if (dvConsumer == null) {
// lazy init
DocValuesFormat fmt = state.segmentInfo.getCodec().docValuesFormat();
dvConsumer = fmt.fieldsConsumer(state);
}
perField.docValuesWriter.flush(state, sortMap, dvConsumer);
perField.docValuesWriter = null;
} else if (perField.fieldInfo.getDocValuesType() != DocValuesType.NONE) {
// BUG
throw new AssertionError(
"segment="
+ state.segmentInfo
+ ": field=\""
+ perField.fieldInfo.name
+ "\" has docValues but did not write them");
}
perField = perField.next;
}
}
// TODO: catch missing DV fields here? else we have
// null/"" depending on how docs landed in segments?
// but we can't detect all cases, and we should leave
// this behavior undefined. dv is not "schemaless": it's column-stride.
success = true;
} finally {
if (success) {
IOUtils.close(dvConsumer);
} else {
IOUtils.closeWhileHandlingException(dvConsumer);
}
}
if (state.fieldInfos.hasDocValues() == false) {
if (dvConsumer != null) {
// BUG
throw new AssertionError(
"segment=" + state.segmentInfo + ": fieldInfos has no docValues but wrote them");
}
} else if (dvConsumer == null) {
// BUG
throw new AssertionError(
"segment=" + state.segmentInfo + ": fieldInfos has docValues but did not wrote them");
}
}
/** Writes all buffered vectors. */
private void writeVectors(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {
VectorWriter vectorWriter = null;
boolean success = false;
try {
for (int i = 0; i < fieldHash.length; i++) {
PerField perField = fieldHash[i];
while (perField != null) {
if (perField.vectorValuesWriter != null) {
if (perField.fieldInfo.getVectorDimension() == 0) {
// BUG
throw new AssertionError(
"segment="
+ state.segmentInfo
+ ": field=\""
+ perField.fieldInfo.name
+ "\" has no vectors but wrote them");
}
if (vectorWriter == null) {
// lazy init
VectorFormat fmt = state.segmentInfo.getCodec().vectorFormat();
if (fmt == null) {
throw new IllegalStateException(
"field=\""
+ perField.fieldInfo.name
+ "\" was indexed as vectors but codec does not support vectors");
}
vectorWriter = fmt.fieldsWriter(state);
}
perField.vectorValuesWriter.flush(sortMap, vectorWriter);
perField.vectorValuesWriter = null;
} else if (perField.fieldInfo.getVectorDimension() != 0) {
// BUG
throw new AssertionError(
"segment="
+ state.segmentInfo
+ ": field=\""
+ perField.fieldInfo.name
+ "\" has vectors but did not write them");
}
perField = perField.next;
}
}
if (vectorWriter != null) {
vectorWriter.finish();
}
success = true;
} finally {
if (success) {
IOUtils.close(vectorWriter);
} else {
IOUtils.closeWhileHandlingException(vectorWriter);
}
}
}
private void writeNorms(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {
boolean success = false;
NormsConsumer normsConsumer = null;
try {
if (state.fieldInfos.hasNorms()) {
NormsFormat normsFormat = state.segmentInfo.getCodec().normsFormat();
assert normsFormat != null;
normsConsumer = normsFormat.normsConsumer(state);
for (FieldInfo fi : state.fieldInfos) {
PerField perField = getPerField(fi.name);
assert perField != null;
// we must check the final value of omitNorms for the fieldinfo: it could have
// changed for this field since the first time we added it.
if (fi.omitsNorms() == false && fi.getIndexOptions() != IndexOptions.NONE) {
assert perField.norms != null : "field=" + fi.name;
perField.norms.finish(state.segmentInfo.maxDoc());
perField.norms.flush(state, sortMap, normsConsumer);
}
}
}
success = true;
} finally {
if (success) {
IOUtils.close(normsConsumer);
} else {
IOUtils.closeWhileHandlingException(normsConsumer);
}
}
}
@SuppressWarnings("try")
void abort() throws IOException {
// finalizer will e.g. close any open files in the term vectors writer:
try (Closeable finalizer = termsHash::abort) {
storedFieldsConsumer.abort();
} finally {
Arrays.fill(fieldHash, null);
}
}
private void rehash() {
int newHashSize = (fieldHash.length * 2);
assert newHashSize > fieldHash.length;
PerField newHashArray[] = new PerField[newHashSize];
// Rehash
int newHashMask = newHashSize - 1;
for (int j = 0; j < fieldHash.length; j++) {
PerField fp0 = fieldHash[j];
while (fp0 != null) {
final int hashPos2 = fp0.fieldInfo.name.hashCode() & newHashMask;
PerField nextFP0 = fp0.next;
fp0.next = newHashArray[hashPos2];
newHashArray[hashPos2] = fp0;
fp0 = nextFP0;
}
}
fieldHash = newHashArray;
hashMask = newHashMask;
}
/** Calls StoredFieldsWriter.startDocument, aborting the segment if it hits any exception. */
private void startStoredFields(int docID) throws IOException {
try {
storedFieldsConsumer.startDocument(docID);
} catch (Throwable th) {
onAbortingException(th);
throw th;
}
}
/** Calls StoredFieldsWriter.finishDocument, aborting the segment if it hits any exception. */
private void finishStoredFields() throws IOException {
try {
storedFieldsConsumer.finishDocument();
} catch (Throwable th) {
onAbortingException(th);
throw th;
}
}
void processDocument(int docID, Iterable<? extends IndexableField> document) throws IOException {
// How many indexed field names we've seen (collapses
// multiple field instances by the same name):
int fieldCount = 0;
long fieldGen = nextFieldGen++;
// NOTE: we need two passes here, in case there are
// multi-valued fields, because we must process all
// instances of a given field at once, since the
// analyzer is free to reuse TokenStream across fields
// (i.e., we cannot have more than one TokenStream
// running "at once"):
termsHash.startDocument();
startStoredFields(docID);
try {
for (IndexableField field : document) {
fieldCount = processField(docID, field, fieldGen, fieldCount);
}
} finally {
if (hasHitAbortingException == false) {
// Finish each indexed field name seen in the document:
for (int i = 0; i < fieldCount; i++) {
fields[i].finish(docID);
}
finishStoredFields();
}
}
try {
termsHash.finishDocument(docID);
} catch (Throwable th) {
// Must abort, on the possibility that on-disk term
// vectors are now corrupt:
abortingExceptionConsumer.accept(th);
throw th;
}
}
private int processField(int docID, IndexableField field, long fieldGen, int fieldCount)
throws IOException {
String fieldName = field.name();
IndexableFieldType fieldType = field.fieldType();
PerField fp = null;
if (fieldType.indexOptions() == null) {
throw new NullPointerException(
"IndexOptions must not be null (field: \"" + field.name() + "\")");
}
// Invert indexed fields:
if (fieldType.indexOptions() != IndexOptions.NONE) {
fp = getOrAddField(fieldName, fieldType, true);
boolean first = fp.fieldGen != fieldGen;
fp.invert(docID, field, first);
if (first) {
fields[fieldCount++] = fp;
fp.fieldGen = fieldGen;
}
} else {
verifyUnIndexedFieldType(fieldName, fieldType);
}
// Add stored fields:
if (fieldType.stored()) {
if (fp == null) {
fp = getOrAddField(fieldName, fieldType, false);
}
String value = field.stringValue();
if (value != null && value.length() > IndexWriter.MAX_STORED_STRING_LENGTH) {
throw new IllegalArgumentException(
"stored field \""
+ field.name()
+ "\" is too large ("
+ value.length()
+ " characters) to store");
}
try {
storedFieldsConsumer.writeField(fp.fieldInfo, field);
} catch (Throwable th) {
onAbortingException(th);
throw th;
}
}
DocValuesType dvType = fieldType.docValuesType();
if (dvType == null) {
throw new NullPointerException(
"docValuesType must not be null (field: \"" + fieldName + "\")");
}
if (dvType != DocValuesType.NONE) {
if (fp == null) {
fp = getOrAddField(fieldName, fieldType, false);
}
indexDocValue(docID, fp, dvType, field);
}
if (fieldType.pointDimensionCount() != 0) {
if (fp == null) {
fp = getOrAddField(fieldName, fieldType, false);
}
indexPoint(docID, fp, field);
}
if (fieldType.vectorDimension() != 0) {
if (fp == null) {
fp = getOrAddField(fieldName, fieldType, false);
}
indexVector(docID, fp, field);
}
return fieldCount;
}
private static void verifyUnIndexedFieldType(String name, IndexableFieldType ft) {
if (ft.storeTermVectors()) {
throw new IllegalArgumentException(
"cannot store term vectors "
+ "for a field that is not indexed (field=\""
+ name
+ "\")");
}
if (ft.storeTermVectorPositions()) {
throw new IllegalArgumentException(
"cannot store term vector positions "
+ "for a field that is not indexed (field=\""
+ name
+ "\")");
}
if (ft.storeTermVectorOffsets()) {
throw new IllegalArgumentException(
"cannot store term vector offsets "
+ "for a field that is not indexed (field=\""
+ name
+ "\")");
}
if (ft.storeTermVectorPayloads()) {
throw new IllegalArgumentException(
"cannot store term vector payloads "
+ "for a field that is not indexed (field=\""
+ name
+ "\")");
}
}
/** Called from processDocument to index one field's point */
private void indexPoint(int docID, PerField fp, IndexableField field) {
int pointDimensionCount = field.fieldType().pointDimensionCount();
int pointIndexDimensionCount = field.fieldType().pointIndexDimensionCount();
int dimensionNumBytes = field.fieldType().pointNumBytes();
// Record dimensions for this field; this setter will throw IllegalArgExc if
// the dimensions were already set to something different:
if (fp.fieldInfo.getPointDimensionCount() == 0) {
fieldInfos.globalFieldNumbers.setDimensions(
fp.fieldInfo.number,
fp.fieldInfo.name,
pointDimensionCount,
pointIndexDimensionCount,
dimensionNumBytes);
}
fp.fieldInfo.setPointDimensions(
pointDimensionCount, pointIndexDimensionCount, dimensionNumBytes);
if (fp.pointValuesWriter == null) {
fp.pointValuesWriter = new PointValuesWriter(byteBlockAllocator, bytesUsed, fp.fieldInfo);
}
fp.pointValuesWriter.addPackedValue(docID, field.binaryValue());
}
private void validateIndexSortDVType(Sort indexSort, String fieldToValidate, DocValuesType dvType)
throws IOException {
for (SortField sortField : indexSort.getSort()) {
IndexSorter sorter = sortField.getIndexSorter();
if (sorter == null) {
throw new IllegalStateException("Cannot sort index with sort order " + sortField);
}
sorter.getDocComparator(
new DocValuesLeafReader() {
@Override
public NumericDocValues getNumericDocValues(String field) {
if (Objects.equals(field, fieldToValidate) && dvType != DocValuesType.NUMERIC) {
throw new IllegalArgumentException(
"SortField "
+ sortField
+ " expected field ["
+ field
+ "] to be NUMERIC but it is ["
+ dvType
+ "]");
}
return DocValues.emptyNumeric();
}
@Override
public BinaryDocValues getBinaryDocValues(String field) {
if (Objects.equals(field, fieldToValidate) && dvType != DocValuesType.BINARY) {
throw new IllegalArgumentException(
"SortField "
+ sortField
+ " expected field ["
+ field
+ "] to be BINARY but it is ["
+ dvType
+ "]");
}
return DocValues.emptyBinary();
}
@Override
public SortedDocValues getSortedDocValues(String field) {
if (Objects.equals(field, fieldToValidate) && dvType != DocValuesType.SORTED) {
throw new IllegalArgumentException(
"SortField "
+ sortField
+ " expected field ["
+ field
+ "] to be SORTED but it is ["
+ dvType
+ "]");
}
return DocValues.emptySorted();
}
@Override
public SortedNumericDocValues getSortedNumericDocValues(String field) {
if (Objects.equals(field, fieldToValidate)
&& dvType != DocValuesType.SORTED_NUMERIC) {
throw new IllegalArgumentException(
"SortField "
+ sortField
+ " expected field ["
+ field
+ "] to be SORTED_NUMERIC but it is ["
+ dvType
+ "]");
}
return DocValues.emptySortedNumeric();
}
@Override
public SortedSetDocValues getSortedSetDocValues(String field) {
if (Objects.equals(field, fieldToValidate) && dvType != DocValuesType.SORTED_SET) {
throw new IllegalArgumentException(
"SortField "
+ sortField
+ " expected field ["
+ field
+ "] to be SORTED_SET but it is ["
+ dvType
+ "]");
}
return DocValues.emptySortedSet();
}
@Override
public FieldInfos getFieldInfos() {
throw new UnsupportedOperationException();
}
},
0);
}
}
/** Called from processDocument to index one field's doc value */
private void indexDocValue(int docID, PerField fp, DocValuesType dvType, IndexableField field)
throws IOException {
if (fp.fieldInfo.getDocValuesType() == DocValuesType.NONE) {
// This is the first time we are seeing this field indexed with doc values, so we
// now record the DV type so that any future attempt to (illegally) change
// the DV type of this field, will throw an IllegalArgExc:
if (indexWriterConfig.getIndexSort() != null) {
final Sort indexSort = indexWriterConfig.getIndexSort();
validateIndexSortDVType(indexSort, fp.fieldInfo.name, dvType);
}
fieldInfos.globalFieldNumbers.setDocValuesType(
fp.fieldInfo.number, fp.fieldInfo.name, dvType);
}
fp.fieldInfo.setDocValuesType(dvType);
switch (dvType) {
case NUMERIC:
if (fp.docValuesWriter == null) {
fp.docValuesWriter = new NumericDocValuesWriter(fp.fieldInfo, bytesUsed);
}
if (field.numericValue() == null) {
throw new IllegalArgumentException(
"field=\"" + fp.fieldInfo.name + "\": null value not allowed");
}
((NumericDocValuesWriter) fp.docValuesWriter)
.addValue(docID, field.numericValue().longValue());
break;
case BINARY:
if (fp.docValuesWriter == null) {
fp.docValuesWriter = new BinaryDocValuesWriter(fp.fieldInfo, bytesUsed);
}
((BinaryDocValuesWriter) fp.docValuesWriter).addValue(docID, field.binaryValue());
break;
case SORTED:
if (fp.docValuesWriter == null) {
fp.docValuesWriter = new SortedDocValuesWriter(fp.fieldInfo, bytesUsed);
}
((SortedDocValuesWriter) fp.docValuesWriter).addValue(docID, field.binaryValue());
break;
case SORTED_NUMERIC:
if (fp.docValuesWriter == null) {
fp.docValuesWriter = new SortedNumericDocValuesWriter(fp.fieldInfo, bytesUsed);
}
((SortedNumericDocValuesWriter) fp.docValuesWriter)
.addValue(docID, field.numericValue().longValue());
break;
case SORTED_SET:
if (fp.docValuesWriter == null) {
fp.docValuesWriter = new SortedSetDocValuesWriter(fp.fieldInfo, bytesUsed);
}
((SortedSetDocValuesWriter) fp.docValuesWriter).addValue(docID, field.binaryValue());
break;
default:
throw new AssertionError("unrecognized DocValues.Type: " + dvType);
}
}
/** Called from processDocument to index one field's vector value */
private void indexVector(int docID, PerField fp, IndexableField field) {
int dimension = field.fieldType().vectorDimension();
VectorValues.SearchStrategy searchStrategy = field.fieldType().vectorSearchStrategy();
// Record dimensions and distance function for this field; this setter will throw IllegalArgExc
// if
// the dimensions or distance function were already set to something different:
if (fp.fieldInfo.getVectorDimension() == 0) {
fieldInfos.globalFieldNumbers.setVectorDimensionsAndSearchStrategy(
fp.fieldInfo.number, fp.fieldInfo.name, dimension, searchStrategy);
}
fp.fieldInfo.setVectorDimensionAndSearchStrategy(dimension, searchStrategy);
if (fp.vectorValuesWriter == null) {
fp.vectorValuesWriter = new VectorValuesWriter(fp.fieldInfo, bytesUsed);
}
fp.vectorValuesWriter.addValue(docID, ((VectorField) field).vectorValue());
}
/** Returns a previously created {@link PerField}, or null if this field name wasn't seen yet. */
private PerField getPerField(String name) {
final int hashPos = name.hashCode() & hashMask;
PerField fp = fieldHash[hashPos];
while (fp != null && !fp.fieldInfo.name.equals(name)) {
fp = fp.next;
}
return fp;
}
/**
* Returns a previously created {@link PerField}, absorbing the type information from {@link
* FieldType}, and creates a new {@link PerField} if this field name wasn't seen yet.
*/
private PerField getOrAddField(String name, IndexableFieldType fieldType, boolean invert) {
// Make sure we have a PerField allocated
final int hashPos = name.hashCode() & hashMask;
PerField fp = fieldHash[hashPos];
while (fp != null && !fp.fieldInfo.name.equals(name)) {
fp = fp.next;
}
if (fp == null) {
// First time we are seeing this field in this segment
FieldInfo fi = fieldInfos.getOrAdd(name);
initIndexOptions(fi, fieldType.indexOptions());
Map<String, String> attributes = fieldType.getAttributes();
if (attributes != null) {
attributes.forEach((k, v) -> fi.putAttribute(k, v));
}
fp =
new PerField(
indexCreatedVersionMajor,
fi,
invert,
indexWriterConfig.getSimilarity(),
indexWriterConfig.getInfoStream(),
indexWriterConfig.getAnalyzer());
fp.next = fieldHash[hashPos];
fieldHash[hashPos] = fp;
totalFieldCount++;
// At most 50% load factor:
if (totalFieldCount >= fieldHash.length / 2) {
rehash();
}
if (totalFieldCount > fields.length) {
PerField[] newFields =
new PerField
[ArrayUtil.oversize(totalFieldCount, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(fields, 0, newFields, 0, fields.length);
fields = newFields;
}
} else if (invert && fp.invertState == null) {
initIndexOptions(fp.fieldInfo, fieldType.indexOptions());
fp.setInvertState();
}
return fp;
}
private void initIndexOptions(FieldInfo info, IndexOptions indexOptions) {
// Messy: must set this here because e.g. FreqProxTermsWriterPerField looks at the initial
// IndexOptions to decide what arrays it must create).
assert info.getIndexOptions() == IndexOptions.NONE;
// This is the first time we are seeing this field indexed, so we now
// record the index options so that any future attempt to (illegally)
// change the index options of this field, will throw an IllegalArgExc:
fieldInfos.globalFieldNumbers.setIndexOptions(info.number, info.name, indexOptions);
info.setIndexOptions(indexOptions);
}
@Override
public long ramBytesUsed() {
return bytesUsed.get()
+ storedFieldsConsumer.accountable.ramBytesUsed()
+ termVectorsWriter.accountable.ramBytesUsed();
}
@Override
public Collection<Accountable> getChildResources() {
return List.of(storedFieldsConsumer.accountable, termVectorsWriter.accountable);
}
/** NOTE: not static: accesses at least docState, termsHash. */
private final class PerField implements Comparable<PerField> {
final int indexCreatedVersionMajor;
final FieldInfo fieldInfo;
final Similarity similarity;
FieldInvertState invertState;
TermsHashPerField termsHashPerField;
// Non-null if this field ever had doc values in this
// segment:
DocValuesWriter<?> docValuesWriter;
// Non-null if this field ever had points in this segment:
PointValuesWriter pointValuesWriter;
// Non-null if this field ever had vector values in this segment:
VectorValuesWriter vectorValuesWriter;
/** We use this to know when a PerField is seen for the first time in the current document. */
long fieldGen = -1;
// Used by the hash table
PerField next;
// Lazy init'd:
NormValuesWriter norms;
// reused
TokenStream tokenStream;
private final InfoStream infoStream;
private final Analyzer analyzer;
PerField(
int indexCreatedVersionMajor,
FieldInfo fieldInfo,
boolean invert,
Similarity similarity,
InfoStream infoStream,
Analyzer analyzer) {
this.indexCreatedVersionMajor = indexCreatedVersionMajor;
this.fieldInfo = fieldInfo;
this.similarity = similarity;
this.infoStream = infoStream;
this.analyzer = analyzer;
if (invert) {
setInvertState();
}
}
void setInvertState() {
invertState =
new FieldInvertState(
indexCreatedVersionMajor, fieldInfo.name, fieldInfo.getIndexOptions());
termsHashPerField = termsHash.addField(invertState, fieldInfo);
if (fieldInfo.omitsNorms() == false) {
assert norms == null;
// Even if no documents actually succeed in setting a norm, we still write norms for this
// segment:
norms = new NormValuesWriter(fieldInfo, bytesUsed);
}
}
@Override
public int compareTo(PerField other) {
return this.fieldInfo.name.compareTo(other.fieldInfo.name);
}
public void finish(int docID) throws IOException {
if (fieldInfo.omitsNorms() == false) {
long normValue;
if (invertState.length == 0) {
// the field exists in this document, but it did not have
// any indexed tokens, so we assign a default value of zero
// to the norm
normValue = 0;
} else {
normValue = similarity.computeNorm(invertState);
if (normValue == 0) {
throw new IllegalStateException(
"Similarity " + similarity + " return 0 for non-empty field");
}
}
norms.addValue(docID, normValue);
}
termsHashPerField.finish();
}
/**
* Inverts one field for one document; first is true if this is the first time we are seeing
* this field name in this document.
*/
public void invert(int docID, IndexableField field, boolean first) throws IOException {
if (first) {
// First time we're seeing this field (indexed) in
// this document:
invertState.reset();
}
IndexableFieldType fieldType = field.fieldType();
IndexOptions indexOptions = fieldType.indexOptions();
fieldInfo.setIndexOptions(indexOptions);
if (fieldType.omitNorms()) {
fieldInfo.setOmitsNorms();
}
final boolean analyzed = fieldType.tokenized() && analyzer != null;
/*
* To assist people in tracking down problems in analysis components, we wish to write the field name to the infostream
* when we fail. We expect some caller to eventually deal with the real exception, so we don't want any 'catch' clauses,
* but rather a finally that takes note of the problem.
*/
boolean succeededInProcessingField = false;
try (TokenStream stream = tokenStream = field.tokenStream(analyzer, tokenStream)) {
// reset the TokenStream to the first token
stream.reset();
invertState.setAttributeSource(stream);
termsHashPerField.start(field, first);
while (stream.incrementToken()) {
// If we hit an exception in stream.next below
// (which is fairly common, e.g. if analyzer
// chokes on a given document), then it's
// non-aborting and (above) this one document
// will be marked as deleted, but still
// consume a docID
int posIncr = invertState.posIncrAttribute.getPositionIncrement();
invertState.position += posIncr;
if (invertState.position < invertState.lastPosition) {
if (posIncr == 0) {
throw new IllegalArgumentException(
"first position increment must be > 0 (got 0) for field '" + field.name() + "'");
} else if (posIncr < 0) {
throw new IllegalArgumentException(
"position increment must be >= 0 (got "
+ posIncr
+ ") for field '"
+ field.name()
+ "'");
} else {
throw new IllegalArgumentException(
"position overflowed Integer.MAX_VALUE (got posIncr="
+ posIncr
+ " lastPosition="
+ invertState.lastPosition
+ " position="
+ invertState.position
+ ") for field '"
+ field.name()
+ "'");
}
} else if (invertState.position > IndexWriter.MAX_POSITION) {
throw new IllegalArgumentException(
"position "
+ invertState.position
+ " is too large for field '"
+ field.name()
+ "': max allowed position is "
+ IndexWriter.MAX_POSITION);
}
invertState.lastPosition = invertState.position;
if (posIncr == 0) {
invertState.numOverlap++;
}
int startOffset = invertState.offset + invertState.offsetAttribute.startOffset();
int endOffset = invertState.offset + invertState.offsetAttribute.endOffset();
if (startOffset < invertState.lastStartOffset || endOffset < startOffset) {
throw new IllegalArgumentException(
"startOffset must be non-negative, and endOffset must be >= startOffset, and offsets must not go backwards "
+ "startOffset="
+ startOffset
+ ",endOffset="
+ endOffset
+ ",lastStartOffset="
+ invertState.lastStartOffset
+ " for field '"
+ field.name()
+ "'");
}
invertState.lastStartOffset = startOffset;
try {
invertState.length =
Math.addExact(invertState.length, invertState.termFreqAttribute.getTermFrequency());
} catch (ArithmeticException ae) {
throw new IllegalArgumentException(
"too many tokens for field \"" + field.name() + "\"");
}
// System.out.println(" term=" + invertState.termAttribute);
// If we hit an exception in here, we abort
// all buffered documents since the last
// flush, on the likelihood that the
// internal state of the terms hash is now
// corrupt and should not be flushed to a
// new segment:
try {
termsHashPerField.add(invertState.termAttribute.getBytesRef(), docID);
} catch (MaxBytesLengthExceededException e) {
byte[] prefix = new byte[30];
BytesRef bigTerm = invertState.termAttribute.getBytesRef();
System.arraycopy(bigTerm.bytes, bigTerm.offset, prefix, 0, 30);
String msg =
"Document contains at least one immense term in field=\""
+ fieldInfo.name
+ "\" (whose UTF8 encoding is longer than the max length "
+ IndexWriter.MAX_TERM_LENGTH
+ "), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '"
+ Arrays.toString(prefix)
+ "...', original message: "
+ e.getMessage();
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", "ERROR: " + msg);
}
// Document will be deleted above:
throw new IllegalArgumentException(msg, e);
} catch (Throwable th) {
onAbortingException(th);
throw th;
}
}
// trigger streams to perform end-of-stream operations
stream.end();
// TODO: maybe add some safety? then again, it's already checked
// when we come back around to the field...
invertState.position += invertState.posIncrAttribute.getPositionIncrement();
invertState.offset += invertState.offsetAttribute.endOffset();
/* if there is an exception coming through, we won't set this to true here:*/
succeededInProcessingField = true;
} finally {
if (!succeededInProcessingField && infoStream.isEnabled("DW")) {
infoStream.message(
"DW", "An exception was thrown while processing field " + fieldInfo.name);
}
}
if (analyzed) {
invertState.position += analyzer.getPositionIncrementGap(fieldInfo.name);
invertState.offset += analyzer.getOffsetGap(fieldInfo.name);
}
}
}
DocIdSetIterator getHasDocValues(String field) {
PerField perField = getPerField(field);
if (perField != null) {
if (perField.docValuesWriter != null) {
if (perField.fieldInfo.getDocValuesType() == DocValuesType.NONE) {
return null;
}
return perField.docValuesWriter.getDocValues();
}
}
return null;
}
private static class IntBlockAllocator extends IntBlockPool.Allocator {
private final Counter bytesUsed;
IntBlockAllocator(Counter bytesUsed) {
super(IntBlockPool.INT_BLOCK_SIZE);
this.bytesUsed = bytesUsed;
}
/* Allocate another int[] from the shared pool */
@Override
public int[] getIntBlock() {
int[] b = new int[IntBlockPool.INT_BLOCK_SIZE];
bytesUsed.addAndGet(IntBlockPool.INT_BLOCK_SIZE * Integer.BYTES);
return b;
}
@Override
public void recycleIntBlocks(int[][] blocks, int offset, int length) {
bytesUsed.addAndGet(-(length * (IntBlockPool.INT_BLOCK_SIZE * Integer.BYTES)));
}
}
}
| 1 | 39,256 | should we set a smaller initial size to make sure that we exercise the growing logic in our tests? | apache-lucene-solr | java |
@@ -230,3 +230,9 @@ def test_sum():
assert str(dt.sum(f[:])) == str(f[:].sum())
DT = dt.Frame(A=range(1, 10))
assert_equals(DT[:, f.A.sum()], DT[:, dt.sum(f.A)])
+
+def test_max():
+ assert str(dt.max(f.A)) == str(f.A.max())
+ assert str(dt.max(f[:])) == str(f[:].max())
+ DT = dt.Frame(A=range(1, 10))
+ assert_equals(DT[:, f.A.max()], DT[:, dt.max(f.A)]) | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Copyright 2019-2020 H2O.ai
#
# 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.
#-------------------------------------------------------------------------------
import pytest
import datatable as dt
from datatable import f
from tests import assert_equals, noop
@pytest.fixture()
def DT():
return dt.Frame([
[2, 7, 0, 0],
[True, False, False, True],
[1, 1, 1, 1],
[0.1, 2, -4, 4.4],
[None, None, None, None],
[0, 0, 0, 0],
["1", "2", "hello", "world"],
],
names=list("ABCDEFG"),
stypes=[dt.int32, dt.bool8, dt.int64, dt.float32, dt.int16,
dt.float64, dt.str32])
#-------------------------------------------------------------------------------
# Plain `f`
#-------------------------------------------------------------------------------
def test_f():
assert str(f) == "Namespace(0)"
assert f.__class__ == type(f)
# Check that missing system atrtibutes raise an AttributeError
# instead of being converted into a column selector expression
with pytest.raises(AttributeError):
f.__name__
#-------------------------------------------------------------------------------
# Stringify
#-------------------------------------------------------------------------------
def test_f_col_selector_unbound():
# Check that unbounded col-selectors can be stringified. The precise
# representation may be modified in the future; however f-expressions
# should not raise exceptions when printed.
# See issues #1024 and #1241
assert str(f.a) == "FExpr<f.a>"
assert str(f.abcdefghijkl) == "FExpr<f.abcdefghijkl>"
assert str(f.abcdefghijklm) == "FExpr<f.abcdefghijklm>"
assert str(f[0]) == "FExpr<f[0]>"
assert str(f[1000]) == "FExpr<f[1000]>"
assert str(f[-1]) == "FExpr<f[-1]>"
assert str(f[-999]) == "FExpr<f[-999]>"
assert str(f[""]) == "FExpr<f['']>"
assert str(f["0"]) == "FExpr<f['0']>"
assert str(f["A+B"]) == "FExpr<f['A+B']>"
assert str(f["_A"]) == "FExpr<f['_A']>"
assert str(f["_54"]) == "FExpr<f['_54']>"
assert str(f._3_) == "FExpr<f._3_>"
assert str(f.a_b_c) == "FExpr<f.a_b_c>"
assert str(f[" y "]) == "FExpr<f[' y ']>"
assert str(f["a b c"]) == "FExpr<f['a b c']>"
assert str(f['"a b c"']) == "FExpr<f['\"a b c\"']>"
def test_f_col_selector_invalid():
with pytest.raises(TypeError) as e:
noop(f[2.5])
assert str(e.value) == ("Column selector should be an integer, string, or "
"slice, or list/tuple, not <class 'float'>")
# Note: at some point we may start supporting all the expressions below:
with pytest.raises(TypeError):
noop(f[lambda: 1])
def test_f_col_selector_list_tuple():
assert str(f[[7, 4]]) == "FExpr<f[[7, 4]]>"
assert str(f[("A", "B", "C")]) == "FExpr<f[['A', 'B', 'C']]>"
def test_f_expressions():
assert str(f.C1 < f.C2) == "FExpr<f.C1 < f.C2>"
assert str(f.C1 > f.C2) == "FExpr<f.C1 > f.C2>"
assert str(f.C1 <= f.C2) == "FExpr<f.C1 <= f.C2>"
assert str(f.C1 >= f.C2) == "FExpr<f.C1 >= f.C2>"
def test_f_columnset_str():
assert str(f[None]) == "FExpr<f[None]>"
assert str(f[:]) == "FExpr<f[:]>"
assert str(f[:7]) == "FExpr<f[:7]>"
assert str(f[::-1]) == "FExpr<f[::-1]>"
assert str(f['Z':'A']) == "FExpr<f['Z':'A']>"
assert str(f[bool]) == "FExpr<f[bool]>"
assert str(f[int]) == "FExpr<f[int]>"
assert str(f[float]) == "FExpr<f[float]>"
assert str(f[str]) == "FExpr<f[str]>"
assert str(f[object]) == "FExpr<f[object]>"
assert str(f[dt.int32]) == "FExpr<f[stype.int32]>"
assert str(f[dt.float64]) == "FExpr<f[stype.float64]>"
assert str(f[dt.ltype.int]) == "FExpr<f[ltype.int]>"
assert str(f[int, float]) == "FExpr<f[[int, float]]>"
assert str(f[dt.int32, dt.float64, dt.str32]) == \
"FExpr<f[[stype.int32, stype.float64, stype.str32]]>"
def test_f_columnset_extend():
assert str(f[:].extend(f.A)) == \
"Expr:setplus(FExpr<f[:]>, FExpr<f.A>; )"
assert str(f[int].extend(f[str])) == \
"Expr:setplus(FExpr<f[int]>, FExpr<f[str]>; )"
assert str(f.A.extend(f['B','C'])) == \
"Expr:setplus(FExpr<f.A>, FExpr<f[['B', 'C']]>; )"
def test_f_columnset_remove():
assert str(f[:].remove(f.A)) == "Expr:setminus(FExpr<f[:]>, FExpr<f.A>; )"
assert str(f[int].remove(f[0])) == "Expr:setminus(FExpr<f[int]>, FExpr<f[0]>; )"
assert str(f.A.remove(f['B','C'])) == \
"Expr:setminus(FExpr<f.A>, FExpr<f[['B', 'C']]>; )"
#-------------------------------------------------------------------------------
# Select individual columns
#-------------------------------------------------------------------------------
def test_f_int(DT):
assert_equals(DT[:, f[3]], DT[:, 3])
assert_equals(DT[:, f[-1]], DT[:, 6])
assert_equals(DT[f[0] > 0, f[-1]], dt.Frame(G=["1", "2"]))
with pytest.raises(ValueError, match="Column index 10 is invalid for a "
"Frame with 7 columns"):
assert DT[:, f[10]]
def test_f_str(DT):
assert_equals(DT[:, "B"], DT[:, 1])
assert_equals(DT[:, f.B], DT[:, 1])
assert_equals(DT[:, f["B"]], DT[:, 1])
for i, name in enumerate(DT.names):
assert_equals(DT[:, f[name]], DT[:, i])
with pytest.raises(KeyError) as e:
noop(DT[:, f["d"]])
assert ("Column d does not exist in the Frame; "
"did you mean D, A or B?" == str(e.value))
#-------------------------------------------------------------------------------
# Select columnsets
#-------------------------------------------------------------------------------
def test_f_columnset(DT):
assert_equals(DT[:, f[:]], DT)
assert_equals(DT[:, f[::-1]], DT[:, ::-1])
assert_equals(DT[:, f[:4]], DT[:, :4])
assert_equals(DT[:, f[3:4]], DT[:, 3:4])
assert_equals(DT[:, f["B":"E"]], DT[:, 1:5])
assert_equals(DT[:, f[bool]], DT[:, 1])
assert_equals(DT[:, f[int]], DT[:, [0, 2, 4]])
assert_equals(DT[:, f[float]], DT[:, [3, 5]])
assert_equals(DT[:, f[str]], DT[:, 6])
assert_equals(DT[:, f[dt.str32]], DT[:, 6])
assert_equals(DT[:, f[dt.str64]], DT[:, []])
assert_equals(DT[:, f[None]], DT[:, []])
def test_f_columnset_stypes(DT):
for st in dt.stype:
assert_equals(DT[:, f[st]],
DT[:, [i for i in range(DT.ncols)
if DT.stypes[i] == st]])
def test_f_columnset_ltypes(DT):
for lt in dt.ltype:
assert_equals(DT[:, f[lt]],
DT[:, [i for i in range(DT.ncols)
if DT.ltypes[i] == lt]])
def test_columnset_sum(DT):
assert_equals(DT[:, f[int].extend(f[float])], DT[:, [int, float]])
assert_equals(DT[:, f[:3].extend(f[-3:])], DT[:, [0, 1, 2, -3, -2, -1]])
assert_equals( DT[:, f['A','B','C'].extend(f['E','F', 'G'])], DT[:, [0, 1, 2, -3, -2, -1]])
assert_equals(DT[:, f.A.extend(f.B)], DT[:, ['A', 'B']])
assert_equals(DT[:, f[:].extend({"extra": f.A + f.C})],
dt.cbind(DT, DT[:, {"extra": f.A + f.C}]))
def test_columnset_diff(DT):
assert_equals(DT[:, f[:].remove(f[3])], DT[:, [0, 1, 2, 4, 5, 6]])
assert_equals(DT[:, f[:].remove(f[2:-2])], DT[:, [0, 1, 5, 6]])
assert_equals(DT[:, f[:5].remove(f[int])], DT[:, [1, 3]])
assert_equals(DT[:, f[:].remove(f[100:])], DT)
assert_equals(DT[:, f[:].remove(f["F":])], DT[:, :"E"])
#-------------------------------------------------------------------------------
# Misc methods
#-------------------------------------------------------------------------------
def test_sum():
assert str(dt.sum(f.A)) == str(f.A.sum())
assert str(dt.sum(f[:])) == str(f[:].sum())
DT = dt.Frame(A=range(1, 10))
assert_equals(DT[:, f.A.sum()], DT[:, dt.sum(f.A)])
| 1 | 12,954 | Let's add a new line at the end of this file, so that the last line becomes a valid line of code. | h2oai-datatable | py |
@@ -3131,7 +3131,7 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
}
bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) {
- name = parser.UnqualifiedName(field->name()->str());
+ name = field->name()->str();
defined_namespace = parser.current_namespace_;
if (!value.type.Deserialize(parser, field->type()))
return false; | 1 | /*
* Copyright 2014 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.
*/
#include <algorithm>
#include <list>
#include <string>
#include <utility>
#include <cmath>
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
// Reflects the version at the compiling time of binary(lib/dll/so).
const char *FLATBUFFERS_VERSION() {
// clang-format off
return
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
// clang-format on
}
const double kPi = 3.14159265358979323846;
const char *const kTypeNames[] = {
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
IDLTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
// clang-format on
nullptr
};
const char kTypeSizes[] = {
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
sizeof(CTYPE),
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
// clang-format on
};
// The enums in the reflection schema should match the ones we use internally.
// Compare the last element to check if these go out of sync.
static_assert(BASE_TYPE_UNION == static_cast<BaseType>(reflection::Union),
"enums don't match");
// Any parsing calls have to be wrapped in this macro, which automates
// handling of recursive error checking a bit. It will check the received
// CheckedError object, and return straight away on error.
#define ECHECK(call) \
{ \
auto ce = (call); \
if (ce.Check()) return ce; \
}
// These two functions are called hundreds of times below, so define a short
// form:
#define NEXT() ECHECK(Next())
#define EXPECT(tok) ECHECK(Expect(tok))
static bool ValidateUTF8(const std::string &str) {
const char *s = &str[0];
const char *const sEnd = s + str.length();
while (s < sEnd) {
if (FromUTF8(&s) < 0) { return false; }
}
return true;
}
// Convert an underscore_based_indentifier in to camelCase.
// Also uppercases the first character if first is true.
std::string MakeCamel(const std::string &in, bool first) {
std::string s;
for (size_t i = 0; i < in.length(); i++) {
if (!i && first)
s += static_cast<char>(toupper(in[0]));
else if (in[i] == '_' && i + 1 < in.length())
s += static_cast<char>(toupper(in[++i]));
else
s += in[i];
}
return s;
}
void DeserializeDoc( std::vector<std::string> &doc,
const Vector<Offset<String>> *documentation) {
if (documentation == nullptr) return;
for (uoffset_t index = 0; index < documentation->size(); index++)
doc.push_back(documentation->Get(index)->str());
}
void Parser::Message(const std::string &msg) {
if (!error_.empty()) error_ += "\n"; // log all warnings and errors
error_ += file_being_parsed_.length() ? AbsolutePath(file_being_parsed_) : "";
// clang-format off
#ifdef _WIN32 // MSVC alike
error_ +=
"(" + NumToString(line_) + ", " + NumToString(CursorPosition()) + ")";
#else // gcc alike
if (file_being_parsed_.length()) error_ += ":";
error_ += NumToString(line_) + ": " + NumToString(CursorPosition());
#endif
// clang-format on
error_ += ": " + msg;
}
void Parser::Warning(const std::string &msg) { Message("warning: " + msg); }
CheckedError Parser::Error(const std::string &msg) {
Message("error: " + msg);
return CheckedError(true);
}
inline CheckedError NoError() { return CheckedError(false); }
CheckedError Parser::RecurseError() {
return Error("maximum parsing recursion of " +
NumToString(FLATBUFFERS_MAX_PARSING_DEPTH) + " reached");
}
template<typename F> CheckedError Parser::Recurse(F f) {
if (recurse_protection_counter >= (FLATBUFFERS_MAX_PARSING_DEPTH))
return RecurseError();
recurse_protection_counter++;
auto ce = f();
recurse_protection_counter--;
return ce;
}
template<typename T> std::string TypeToIntervalString() {
return "[" + NumToString((flatbuffers::numeric_limits<T>::lowest)()) + "; " +
NumToString((flatbuffers::numeric_limits<T>::max)()) + "]";
}
// atot: template version of atoi/atof: convert a string to an instance of T.
template<typename T>
inline CheckedError atot(const char *s, Parser &parser, T *val) {
auto done = StringToNumber(s, val);
if (done) return NoError();
if (0 == *val)
return parser.Error("invalid number: \"" + std::string(s) + "\"");
else
return parser.Error("invalid number: \"" + std::string(s) + "\"" +
", constant does not fit " + TypeToIntervalString<T>());
}
template<>
inline CheckedError atot<Offset<void>>(const char *s, Parser &parser,
Offset<void> *val) {
(void)parser;
*val = Offset<void>(atoi(s));
return NoError();
}
std::string Namespace::GetFullyQualifiedName(const std::string &name,
size_t max_components) const {
// Early exit if we don't have a defined namespace.
if (components.empty() || !max_components) { return name; }
std::string stream_str;
for (size_t i = 0; i < std::min(components.size(), max_components); i++) {
if (i) { stream_str += '.'; }
stream_str += std::string(components[i]);
}
if (name.length()) {
stream_str += '.';
stream_str += name;
}
return stream_str;
}
// Declare tokens we'll use. Single character tokens are represented by their
// ascii character code (e.g. '{'), others above 256.
// clang-format off
#define FLATBUFFERS_GEN_TOKENS(TD) \
TD(Eof, 256, "end of file") \
TD(StringConstant, 257, "string constant") \
TD(IntegerConstant, 258, "integer constant") \
TD(FloatConstant, 259, "float constant") \
TD(Identifier, 260, "identifier")
#ifdef __GNUC__
__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
#endif
enum {
#define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE,
FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
#undef FLATBUFFERS_TOKEN
};
static std::string TokenToString(int t) {
static const char * const tokens[] = {
#define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING,
FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
#undef FLATBUFFERS_TOKEN
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
IDLTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
if (t < 256) { // A single ascii char token.
std::string s;
s.append(1, static_cast<char>(t));
return s;
} else { // Other tokens.
return tokens[t - 256];
}
}
// clang-format on
std::string Parser::TokenToStringId(int t) const {
return t == kTokenIdentifier ? attribute_ : TokenToString(t);
}
// Parses exactly nibbles worth of hex digits into a number, or error.
CheckedError Parser::ParseHexNum(int nibbles, uint64_t *val) {
FLATBUFFERS_ASSERT(nibbles > 0);
for (int i = 0; i < nibbles; i++)
if (!is_xdigit(cursor_[i]))
return Error("escape code must be followed by " + NumToString(nibbles) +
" hex digits");
std::string target(cursor_, cursor_ + nibbles);
*val = StringToUInt(target.c_str(), 16);
cursor_ += nibbles;
return NoError();
}
CheckedError Parser::SkipByteOrderMark() {
if (static_cast<unsigned char>(*cursor_) != 0xef) return NoError();
cursor_++;
if (static_cast<unsigned char>(*cursor_) != 0xbb)
return Error("invalid utf-8 byte order mark");
cursor_++;
if (static_cast<unsigned char>(*cursor_) != 0xbf)
return Error("invalid utf-8 byte order mark");
cursor_++;
return NoError();
}
static inline bool IsIdentifierStart(char c) {
return is_alpha(c) || (c == '_');
}
CheckedError Parser::Next() {
doc_comment_.clear();
bool seen_newline = cursor_ == source_;
attribute_.clear();
attr_is_trivial_ascii_string_ = true;
for (;;) {
char c = *cursor_++;
token_ = c;
switch (c) {
case '\0':
cursor_--;
token_ = kTokenEof;
return NoError();
case ' ':
case '\r':
case '\t': break;
case '\n':
MarkNewLine();
seen_newline = true;
break;
case '{':
case '}':
case '(':
case ')':
case '[':
case ']':
case ',':
case ':':
case ';':
case '=': return NoError();
case '\"':
case '\'': {
int unicode_high_surrogate = -1;
while (*cursor_ != c) {
if (*cursor_ < ' ' && static_cast<signed char>(*cursor_) >= 0)
return Error("illegal character in string constant");
if (*cursor_ == '\\') {
attr_is_trivial_ascii_string_ = false; // has escape sequence
cursor_++;
if (unicode_high_surrogate != -1 && *cursor_ != 'u') {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
switch (*cursor_) {
case 'n':
attribute_ += '\n';
cursor_++;
break;
case 't':
attribute_ += '\t';
cursor_++;
break;
case 'r':
attribute_ += '\r';
cursor_++;
break;
case 'b':
attribute_ += '\b';
cursor_++;
break;
case 'f':
attribute_ += '\f';
cursor_++;
break;
case '\"':
attribute_ += '\"';
cursor_++;
break;
case '\'':
attribute_ += '\'';
cursor_++;
break;
case '\\':
attribute_ += '\\';
cursor_++;
break;
case '/':
attribute_ += '/';
cursor_++;
break;
case 'x': { // Not in the JSON standard
cursor_++;
uint64_t val;
ECHECK(ParseHexNum(2, &val));
attribute_ += static_cast<char>(val);
break;
}
case 'u': {
cursor_++;
uint64_t val;
ECHECK(ParseHexNum(4, &val));
if (val >= 0xD800 && val <= 0xDBFF) {
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (multiple high surrogates)");
} else {
unicode_high_surrogate = static_cast<int>(val);
}
} else if (val >= 0xDC00 && val <= 0xDFFF) {
if (unicode_high_surrogate == -1) {
return Error(
"illegal Unicode sequence (unpaired low surrogate)");
} else {
int code_point = 0x10000 +
((unicode_high_surrogate & 0x03FF) << 10) +
(val & 0x03FF);
ToUTF8(code_point, &attribute_);
unicode_high_surrogate = -1;
}
} else {
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
ToUTF8(static_cast<int>(val), &attribute_);
}
break;
}
default: return Error("unknown escape code in string constant");
}
} else { // printable chars + UTF-8 bytes
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
// reset if non-printable
attr_is_trivial_ascii_string_ &= check_ascii_range(*cursor_, ' ', '~');
attribute_ += *cursor_++;
}
}
if (unicode_high_surrogate != -1) {
return Error("illegal Unicode sequence (unpaired high surrogate)");
}
cursor_++;
if (!attr_is_trivial_ascii_string_ && !opts.allow_non_utf8 &&
!ValidateUTF8(attribute_)) {
return Error("illegal UTF-8 sequence");
}
token_ = kTokenStringConstant;
return NoError();
}
case '/':
if (*cursor_ == '/') {
const char *start = ++cursor_;
while (*cursor_ && *cursor_ != '\n' && *cursor_ != '\r') cursor_++;
if (*start == '/') { // documentation comment
if (!seen_newline)
return Error(
"a documentation comment should be on a line on its own");
doc_comment_.push_back(std::string(start + 1, cursor_));
}
break;
} else if (*cursor_ == '*') {
cursor_++;
// TODO: make nested.
while (*cursor_ != '*' || cursor_[1] != '/') {
if (*cursor_ == '\n') MarkNewLine();
if (!*cursor_) return Error("end of file in comment");
cursor_++;
}
cursor_ += 2;
break;
}
FLATBUFFERS_FALLTHROUGH(); // else fall thru
default:
const auto has_sign = (c == '+') || (c == '-');
// '-'/'+' and following identifier - can be a predefined constant like:
// NAN, INF, PI, etc.
if (IsIdentifierStart(c) || (has_sign && IsIdentifierStart(*cursor_))) {
// Collect all chars of an identifier:
const char *start = cursor_ - 1;
while (IsIdentifierStart(*cursor_) || is_digit(*cursor_)) cursor_++;
attribute_.append(start, cursor_);
token_ = has_sign ? kTokenStringConstant : kTokenIdentifier;
return NoError();
}
auto dot_lvl = (c == '.') ? 0 : 1; // dot_lvl==0 <=> exactly one '.' seen
if (!dot_lvl && !is_digit(*cursor_)) return NoError(); // enum?
// Parser accepts hexadecimal-floating-literal (see C++ 5.13.4).
if (is_digit(c) || has_sign || !dot_lvl) {
const auto start = cursor_ - 1;
auto start_digits = !is_digit(c) ? cursor_ : cursor_ - 1;
if (!is_digit(c) && is_digit(*cursor_)){
start_digits = cursor_; // see digit in cursor_ position
c = *cursor_++;
}
// hex-float can't begind with '.'
auto use_hex = dot_lvl && (c == '0') && is_alpha_char(*cursor_, 'X');
if (use_hex) start_digits = ++cursor_; // '0x' is the prefix, skip it
// Read an integer number or mantisa of float-point number.
do {
if (use_hex) {
while (is_xdigit(*cursor_)) cursor_++;
} else {
while (is_digit(*cursor_)) cursor_++;
}
} while ((*cursor_ == '.') && (++cursor_) && (--dot_lvl >= 0));
// Exponent of float-point number.
if ((dot_lvl >= 0) && (cursor_ > start_digits)) {
// The exponent suffix of hexadecimal float number is mandatory.
if (use_hex && !dot_lvl) start_digits = cursor_;
if ((use_hex && is_alpha_char(*cursor_, 'P')) ||
is_alpha_char(*cursor_, 'E')) {
dot_lvl = 0; // Emulate dot to signal about float-point number.
cursor_++;
if (*cursor_ == '+' || *cursor_ == '-') cursor_++;
start_digits = cursor_; // the exponent-part has to have digits
// Exponent is decimal integer number
while (is_digit(*cursor_)) cursor_++;
if (*cursor_ == '.') {
cursor_++; // If see a dot treat it as part of invalid number.
dot_lvl = -1; // Fall thru to Error().
}
}
}
// Finalize.
if ((dot_lvl >= 0) && (cursor_ > start_digits)) {
attribute_.append(start, cursor_);
token_ = dot_lvl ? kTokenIntegerConstant : kTokenFloatConstant;
return NoError();
} else {
return Error("invalid number: " + std::string(start, cursor_));
}
}
std::string ch;
ch = c;
if (false == check_ascii_range(c, ' ', '~')) ch = "code: " + NumToString(c);
return Error("illegal character: " + ch);
}
}
}
// Check if a given token is next.
bool Parser::Is(int t) const { return t == token_; }
bool Parser::IsIdent(const char *id) const {
return token_ == kTokenIdentifier && attribute_ == id;
}
// Expect a given token to be next, consume it, or error if not present.
CheckedError Parser::Expect(int t) {
if (t != token_) {
return Error("expecting: " + TokenToString(t) +
" instead got: " + TokenToStringId(token_));
}
NEXT();
return NoError();
}
CheckedError Parser::ParseNamespacing(std::string *id, std::string *last) {
while (Is('.')) {
NEXT();
*id += ".";
*id += attribute_;
if (last) *last = attribute_;
EXPECT(kTokenIdentifier);
}
return NoError();
}
EnumDef *Parser::LookupEnum(const std::string &id) {
// Search thru parent namespaces.
for (int components = static_cast<int>(current_namespace_->components.size());
components >= 0; components--) {
auto ed = enums_.Lookup(
current_namespace_->GetFullyQualifiedName(id, components));
if (ed) return ed;
}
return nullptr;
}
StructDef *Parser::LookupStruct(const std::string &id) const {
auto sd = structs_.Lookup(id);
if (sd) sd->refcount++;
return sd;
}
CheckedError Parser::ParseTypeIdent(Type &type) {
std::string id = attribute_;
EXPECT(kTokenIdentifier);
ECHECK(ParseNamespacing(&id, nullptr));
auto enum_def = LookupEnum(id);
if (enum_def) {
type = enum_def->underlying_type;
if (enum_def->is_union) type.base_type = BASE_TYPE_UNION;
} else {
type.base_type = BASE_TYPE_STRUCT;
type.struct_def = LookupCreateStruct(id);
}
return NoError();
}
// Parse any IDL type.
CheckedError Parser::ParseType(Type &type) {
if (token_ == kTokenIdentifier) {
if (IsIdent("bool")) {
type.base_type = BASE_TYPE_BOOL;
NEXT();
} else if (IsIdent("byte") || IsIdent("int8")) {
type.base_type = BASE_TYPE_CHAR;
NEXT();
} else if (IsIdent("ubyte") || IsIdent("uint8")) {
type.base_type = BASE_TYPE_UCHAR;
NEXT();
} else if (IsIdent("short") || IsIdent("int16")) {
type.base_type = BASE_TYPE_SHORT;
NEXT();
} else if (IsIdent("ushort") || IsIdent("uint16")) {
type.base_type = BASE_TYPE_USHORT;
NEXT();
} else if (IsIdent("int") || IsIdent("int32")) {
type.base_type = BASE_TYPE_INT;
NEXT();
} else if (IsIdent("uint") || IsIdent("uint32")) {
type.base_type = BASE_TYPE_UINT;
NEXT();
} else if (IsIdent("long") || IsIdent("int64")) {
type.base_type = BASE_TYPE_LONG;
NEXT();
} else if (IsIdent("ulong") || IsIdent("uint64")) {
type.base_type = BASE_TYPE_ULONG;
NEXT();
} else if (IsIdent("float") || IsIdent("float32")) {
type.base_type = BASE_TYPE_FLOAT;
NEXT();
} else if (IsIdent("double") || IsIdent("float64")) {
type.base_type = BASE_TYPE_DOUBLE;
NEXT();
} else if (IsIdent("string")) {
type.base_type = BASE_TYPE_STRING;
NEXT();
} else {
ECHECK(ParseTypeIdent(type));
}
} else if (token_ == '[') {
NEXT();
Type subtype;
ECHECK(Recurse([&]() { return ParseType(subtype); }));
if (IsSeries(subtype)) {
// We could support this, but it will complicate things, and it's
// easier to work around with a struct around the inner vector.
return Error("nested vector types not supported (wrap in table first)");
}
if (token_ == ':') {
NEXT();
if (token_ != kTokenIntegerConstant) {
return Error("length of fixed-length array must be an integer value");
}
uint16_t fixed_length = 0;
bool check = StringToNumber(attribute_.c_str(), &fixed_length);
if (!check || fixed_length < 1) {
return Error(
"length of fixed-length array must be positive and fit to "
"uint16_t type");
}
// Check if enum arrays are used in C++ without specifying --scoped-enums
if ((opts.lang_to_generate & IDLOptions::kCpp) && !opts.scoped_enums &&
IsEnum(subtype)) {
return Error(
"--scoped-enums must be enabled to use enum arrays in C++\n");
}
type = Type(BASE_TYPE_ARRAY, subtype.struct_def, subtype.enum_def,
fixed_length);
NEXT();
} else {
type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def);
}
type.element = subtype.base_type;
EXPECT(']');
} else {
return Error("illegal type syntax");
}
return NoError();
}
CheckedError Parser::AddField(StructDef &struct_def, const std::string &name,
const Type &type, FieldDef **dest) {
auto &field = *new FieldDef();
field.value.offset =
FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
field.name = name;
field.file = struct_def.file;
field.value.type = type;
if (struct_def.fixed) { // statically compute the field offset
auto size = InlineSize(type);
auto alignment = InlineAlignment(type);
// structs_ need to have a predictable format, so we need to align to
// the largest scalar
struct_def.minalign = std::max(struct_def.minalign, alignment);
struct_def.PadLastField(alignment);
field.value.offset = static_cast<voffset_t>(struct_def.bytesize);
struct_def.bytesize += size;
}
if (struct_def.fields.Add(name, &field))
return Error("field already exists: " + name);
*dest = &field;
return NoError();
}
CheckedError Parser::ParseField(StructDef &struct_def) {
std::string name = attribute_;
if (LookupStruct(name))
return Error("field name can not be the same as table/struct name");
std::vector<std::string> dc = doc_comment_;
EXPECT(kTokenIdentifier);
EXPECT(':');
Type type;
ECHECK(ParseType(type));
if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type) &&
!IsArray(type))
return Error("structs_ may contain only scalar or struct fields");
if (!struct_def.fixed && IsArray(type))
return Error("fixed-length array in table must be wrapped in struct");
if (IsArray(type) && !SupportsAdvancedArrayFeatures()) {
return Error(
"Arrays are not yet supported in all "
"the specified programming languages.");
}
FieldDef *typefield = nullptr;
if (type.base_type == BASE_TYPE_UNION) {
// For union fields, add a second auto-generated field to hold the type,
// with a special suffix.
ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(),
type.enum_def->underlying_type, &typefield));
} else if (type.base_type == BASE_TYPE_VECTOR &&
type.element == BASE_TYPE_UNION) {
// Only cpp, js and ts supports the union vector feature so far.
if (!SupportsAdvancedUnionFeatures()) {
return Error(
"Vectors of unions are not yet supported in all "
"the specified programming languages.");
}
// For vector of union fields, add a second auto-generated vector field to
// hold the types, with a special suffix.
Type union_vector(BASE_TYPE_VECTOR, nullptr, type.enum_def);
union_vector.element = BASE_TYPE_UTYPE;
ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(), union_vector,
&typefield));
}
FieldDef *field;
ECHECK(AddField(struct_def, name, type, &field));
if (token_ == '=') {
NEXT();
ECHECK(ParseSingleValue(&field->name, field->value, true));
if (!IsScalar(type.base_type) ||
(struct_def.fixed && field->value.constant != "0"))
return Error(
"default values currently only supported for scalars in tables");
}
// Append .0 if the value has not it (skip hex and scientific floats).
// This suffix needed for generated C++ code.
if (IsFloat(type.base_type)) {
auto &text = field->value.constant;
FLATBUFFERS_ASSERT(false == text.empty());
auto s = text.c_str();
while(*s == ' ') s++;
if (*s == '-' || *s == '+') s++;
// 1) A float constants (nan, inf, pi, etc) is a kind of identifier.
// 2) A float number needn't ".0" at the end if it has exponent.
if ((false == IsIdentifierStart(*s)) &&
(std::string::npos == field->value.constant.find_first_of(".eEpP"))) {
field->value.constant += ".0";
}
}
if (type.enum_def) {
// The type.base_type can only be scalar, union, array or vector.
// Table, struct or string can't have enum_def.
// Default value of union and vector in NONE, NULL translated to "0".
FLATBUFFERS_ASSERT(IsInteger(type.base_type) ||
(type.base_type == BASE_TYPE_UNION) ||
(type.base_type == BASE_TYPE_VECTOR) ||
(type.base_type == BASE_TYPE_ARRAY));
if (type.base_type == BASE_TYPE_VECTOR) {
// Vector can't use initialization list.
FLATBUFFERS_ASSERT(field->value.constant == "0");
} else {
// All unions should have the NONE ("0") enum value.
auto in_enum = type.enum_def->attributes.Lookup("bit_flags") ||
type.enum_def->FindByValue(field->value.constant);
if (false == in_enum)
return Error("default value of " + field->value.constant +
" for field " + name + " is not part of enum " +
type.enum_def->name);
}
}
field->doc_comment = dc;
ECHECK(ParseMetaData(&field->attributes));
field->deprecated = field->attributes.Lookup("deprecated") != nullptr;
auto hash_name = field->attributes.Lookup("hash");
if (hash_name) {
switch ((type.base_type == BASE_TYPE_VECTOR) ? type.element : type.base_type) {
case BASE_TYPE_SHORT:
case BASE_TYPE_USHORT: {
if (FindHashFunction16(hash_name->constant.c_str()) == nullptr)
return Error("Unknown hashing algorithm for 16 bit types: " +
hash_name->constant);
break;
}
case BASE_TYPE_INT:
case BASE_TYPE_UINT: {
if (FindHashFunction32(hash_name->constant.c_str()) == nullptr)
return Error("Unknown hashing algorithm for 32 bit types: " +
hash_name->constant);
break;
}
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
if (FindHashFunction64(hash_name->constant.c_str()) == nullptr)
return Error("Unknown hashing algorithm for 64 bit types: " +
hash_name->constant);
break;
}
default:
return Error(
"only short, ushort, int, uint, long and ulong data types support hashing.");
}
}
auto cpp_type = field->attributes.Lookup("cpp_type");
if (cpp_type) {
if (!hash_name)
return Error("cpp_type can only be used with a hashed field");
/// forcing cpp_ptr_type to 'naked' if unset
auto cpp_ptr_type = field->attributes.Lookup("cpp_ptr_type");
if (!cpp_ptr_type) {
auto val = new Value();
val->type = cpp_type->type;
val->constant = "naked";
field->attributes.Add("cpp_ptr_type", val);
}
}
if (field->deprecated && struct_def.fixed)
return Error("can't deprecate fields in a struct");
field->required = field->attributes.Lookup("required") != nullptr;
if (field->required &&
(struct_def.fixed || IsScalar(type.base_type)))
return Error("only non-scalar fields in tables may be 'required'");
field->key = field->attributes.Lookup("key") != nullptr;
if (field->key) {
if (struct_def.has_key) return Error("only one field may be set as 'key'");
struct_def.has_key = true;
if (!IsScalar(type.base_type)) {
field->required = true;
if (type.base_type != BASE_TYPE_STRING)
return Error("'key' field must be string or scalar type");
}
}
field->shared = field->attributes.Lookup("shared") != nullptr;
if (field->shared && field->value.type.base_type != BASE_TYPE_STRING)
return Error("shared can only be defined on strings");
auto field_native_custom_alloc =
field->attributes.Lookup("native_custom_alloc");
if (field_native_custom_alloc)
return Error(
"native_custom_alloc can only be used with a table or struct "
"definition");
field->native_inline = field->attributes.Lookup("native_inline") != nullptr;
if (field->native_inline && !IsStruct(field->value.type))
return Error("native_inline can only be defined on structs");
auto nested = field->attributes.Lookup("nested_flatbuffer");
if (nested) {
if (nested->type.base_type != BASE_TYPE_STRING)
return Error(
"nested_flatbuffer attribute must be a string (the root type)");
if (type.base_type != BASE_TYPE_VECTOR || type.element != BASE_TYPE_UCHAR)
return Error(
"nested_flatbuffer attribute may only apply to a vector of ubyte");
// This will cause an error if the root type of the nested flatbuffer
// wasn't defined elsewhere.
field->nested_flatbuffer = LookupCreateStruct(nested->constant);
}
if (field->attributes.Lookup("flexbuffer")) {
field->flexbuffer = true;
uses_flexbuffers_ = true;
if (type.base_type != BASE_TYPE_VECTOR ||
type.element != BASE_TYPE_UCHAR)
return Error("flexbuffer attribute may only apply to a vector of ubyte");
}
if (typefield) {
if (!IsScalar(typefield->value.type.base_type)) {
// this is a union vector field
typefield->required = field->required;
}
// If this field is a union, and it has a manually assigned id,
// the automatically added type field should have an id as well (of N - 1).
auto attr = field->attributes.Lookup("id");
if (attr) {
auto id = atoi(attr->constant.c_str());
auto val = new Value();
val->type = attr->type;
val->constant = NumToString(id - 1);
typefield->attributes.Add("id", val);
}
}
EXPECT(';');
return NoError();
}
CheckedError Parser::ParseString(Value &val) {
auto s = attribute_;
EXPECT(kTokenStringConstant);
val.constant = NumToString(builder_.CreateString(s).o);
return NoError();
}
CheckedError Parser::ParseComma() {
if (!opts.protobuf_ascii_alike) EXPECT(',');
return NoError();
}
CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn,
const StructDef *parent_struct_def,
uoffset_t count,
bool inside_vector) {
switch (val.type.base_type) {
case BASE_TYPE_UNION: {
FLATBUFFERS_ASSERT(field);
std::string constant;
Vector<uint8_t> *vector_of_union_types = nullptr;
// Find corresponding type field we may have already parsed.
for (auto elem = field_stack_.rbegin() + count;
elem != field_stack_.rbegin() + parent_fieldn + count; ++elem) {
auto &type = elem->second->value.type;
if (type.enum_def == val.type.enum_def) {
if (inside_vector) {
if (type.base_type == BASE_TYPE_VECTOR &&
type.element == BASE_TYPE_UTYPE) {
// Vector of union type field.
uoffset_t offset;
ECHECK(atot(elem->first.constant.c_str(), *this, &offset));
vector_of_union_types = reinterpret_cast<Vector<uint8_t> *>(
builder_.GetCurrentBufferPointer() +
builder_.GetSize() - offset);
break;
}
} else {
if (type.base_type == BASE_TYPE_UTYPE) {
// Union type field.
constant = elem->first.constant;
break;
}
}
}
}
if (constant.empty() && !inside_vector) {
// We haven't seen the type field yet. Sadly a lot of JSON writers
// output these in alphabetical order, meaning it comes after this
// value. So we scan past the value to find it, then come back here.
// We currently don't do this for vectors of unions because the
// scanning/serialization logic would get very complicated.
auto type_name = field->name + UnionTypeFieldSuffix();
FLATBUFFERS_ASSERT(parent_struct_def);
auto type_field = parent_struct_def->fields.Lookup(type_name);
FLATBUFFERS_ASSERT(type_field); // Guaranteed by ParseField().
// Remember where we are in the source file, so we can come back here.
auto backup = *static_cast<ParserState *>(this);
ECHECK(SkipAnyJsonValue()); // The table.
ECHECK(ParseComma());
auto next_name = attribute_;
if (Is(kTokenStringConstant)) {
NEXT();
} else {
EXPECT(kTokenIdentifier);
}
if (next_name == type_name) {
EXPECT(':');
Value type_val = type_field->value;
ECHECK(ParseAnyValue(type_val, type_field, 0, nullptr, 0));
constant = type_val.constant;
// Got the information we needed, now rewind:
*static_cast<ParserState *>(this) = backup;
}
}
if (constant.empty() && !vector_of_union_types) {
return Error("missing type field for this union value: " +
field->name);
}
uint8_t enum_idx;
if (vector_of_union_types) {
enum_idx = vector_of_union_types->Get(count);
} else {
ECHECK(atot(constant.c_str(), *this, &enum_idx));
}
auto enum_val = val.type.enum_def->ReverseLookup(enum_idx, true);
if (!enum_val) return Error("illegal type id for: " + field->name);
if (enum_val->union_type.base_type == BASE_TYPE_STRUCT) {
ECHECK(ParseTable(*enum_val->union_type.struct_def, &val.constant,
nullptr));
if (enum_val->union_type.struct_def->fixed) {
// All BASE_TYPE_UNION values are offsets, so turn this into one.
SerializeStruct(*enum_val->union_type.struct_def, val);
builder_.ClearOffsets();
val.constant = NumToString(builder_.GetSize());
}
} else if (enum_val->union_type.base_type == BASE_TYPE_STRING) {
ECHECK(ParseString(val));
} else {
FLATBUFFERS_ASSERT(false);
}
break;
}
case BASE_TYPE_STRUCT:
ECHECK(ParseTable(*val.type.struct_def, &val.constant, nullptr));
break;
case BASE_TYPE_STRING: {
ECHECK(ParseString(val));
break;
}
case BASE_TYPE_VECTOR: {
uoffset_t off;
ECHECK(ParseVector(val.type.VectorType(), &off, field, parent_fieldn));
val.constant = NumToString(off);
break;
}
case BASE_TYPE_ARRAY: {
ECHECK(ParseArray(val));
break;
}
case BASE_TYPE_INT:
case BASE_TYPE_UINT:
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
if (field && field->attributes.Lookup("hash") &&
(token_ == kTokenIdentifier || token_ == kTokenStringConstant)) {
ECHECK(ParseHash(val, field));
} else {
ECHECK(ParseSingleValue(field ? &field->name : nullptr, val, false));
}
break;
}
default:
ECHECK(ParseSingleValue(field ? &field->name : nullptr, val, false));
break;
}
return NoError();
}
void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) {
SerializeStruct(builder_, struct_def, val);
}
void Parser::SerializeStruct(FlatBufferBuilder &builder,
const StructDef &struct_def, const Value &val) {
FLATBUFFERS_ASSERT(val.constant.length() == struct_def.bytesize);
builder.Align(struct_def.minalign);
builder.PushBytes(reinterpret_cast<const uint8_t *>(val.constant.c_str()),
struct_def.bytesize);
builder.AddStructOffset(val.offset, builder.GetSize());
}
template <typename F>
CheckedError Parser::ParseTableDelimiters(size_t &fieldn,
const StructDef *struct_def,
F body) {
// We allow tables both as JSON object{ .. } with field names
// or vector[..] with all fields in order
char terminator = '}';
bool is_nested_vector = struct_def && Is('[');
if (is_nested_vector) {
NEXT();
terminator = ']';
} else {
EXPECT('{');
}
for (;;) {
if ((!opts.strict_json || !fieldn) && Is(terminator)) break;
std::string name;
if (is_nested_vector) {
if (fieldn >= struct_def->fields.vec.size()) {
return Error("too many unnamed fields in nested array");
}
name = struct_def->fields.vec[fieldn]->name;
} else {
name = attribute_;
if (Is(kTokenStringConstant)) {
NEXT();
} else {
EXPECT(opts.strict_json ? kTokenStringConstant : kTokenIdentifier);
}
if (!opts.protobuf_ascii_alike || !(Is('{') || Is('['))) EXPECT(':');
}
ECHECK(body(name, fieldn, struct_def));
if (Is(terminator)) break;
ECHECK(ParseComma());
}
NEXT();
if (is_nested_vector && fieldn != struct_def->fields.vec.size()) {
return Error("wrong number of unnamed fields in table vector");
}
return NoError();
}
CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
uoffset_t *ovalue) {
size_t fieldn_outer = 0;
auto err = ParseTableDelimiters(
fieldn_outer, &struct_def,
[&](const std::string &name, size_t &fieldn,
const StructDef *struct_def_inner) -> CheckedError {
if (name == "$schema") {
ECHECK(Expect(kTokenStringConstant));
return NoError();
}
auto field = struct_def_inner->fields.Lookup(name);
if (!field) {
if (!opts.skip_unexpected_fields_in_json) {
return Error("unknown field: " + name);
} else {
ECHECK(SkipAnyJsonValue());
}
} else {
if (IsIdent("null") && !IsScalar(field->value.type.base_type)) {
ECHECK(Next()); // Ignore this field.
} else {
Value val = field->value;
if (field->flexbuffer) {
flexbuffers::Builder builder(1024,
flexbuffers::BUILDER_FLAG_SHARE_ALL);
ECHECK(ParseFlexBufferValue(&builder));
builder.Finish();
// Force alignment for nested flexbuffer
builder_.ForceVectorAlignment(builder.GetSize(), sizeof(uint8_t),
sizeof(largest_scalar_t));
auto off = builder_.CreateVector(builder.GetBuffer());
val.constant = NumToString(off.o);
} else if (field->nested_flatbuffer) {
ECHECK(
ParseNestedFlatbuffer(val, field, fieldn, struct_def_inner));
} else {
ECHECK(Recurse([&]() {
return ParseAnyValue(val, field, fieldn, struct_def_inner, 0);
}));
}
// Hardcoded insertion-sort with error-check.
// If fields are specified in order, then this loop exits
// immediately.
auto elem = field_stack_.rbegin();
for (; elem != field_stack_.rbegin() + fieldn; ++elem) {
auto existing_field = elem->second;
if (existing_field == field)
return Error("field set more than once: " + field->name);
if (existing_field->value.offset < field->value.offset) break;
}
// Note: elem points to before the insertion point, thus .base()
// points to the correct spot.
field_stack_.insert(elem.base(), std::make_pair(val, field));
fieldn++;
}
}
return NoError();
});
ECHECK(err);
// Check if all required fields are parsed.
for (auto field_it = struct_def.fields.vec.begin();
field_it != struct_def.fields.vec.end(); ++field_it) {
auto required_field = *field_it;
if (!required_field->required) { continue; }
bool found = false;
for (auto pf_it = field_stack_.end() - fieldn_outer;
pf_it != field_stack_.end(); ++pf_it) {
auto parsed_field = pf_it->second;
if (parsed_field == required_field) {
found = true;
break;
}
}
if (!found) {
return Error("required field is missing: " + required_field->name +
" in " + struct_def.name);
}
}
if (struct_def.fixed && fieldn_outer != struct_def.fields.vec.size())
return Error("struct: wrong number of initializers: " + struct_def.name);
auto start = struct_def.fixed ? builder_.StartStruct(struct_def.minalign)
: builder_.StartTable();
for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; size;
size /= 2) {
// Go through elements in reverse, since we're building the data backwards.
for (auto it = field_stack_.rbegin();
it != field_stack_.rbegin() + fieldn_outer; ++it) {
auto &field_value = it->first;
auto field = it->second;
if (!struct_def.sortbysize ||
size == SizeOf(field_value.type.base_type)) {
switch (field_value.type.base_type) {
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \
if (struct_def.fixed) { \
CTYPE val; \
ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
builder_.PushElement(val); \
} else { \
CTYPE val, valdef; \
ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
ECHECK(atot(field->value.constant.c_str(), *this, &valdef)); \
builder_.AddElement(field_value.offset, val, valdef); \
} \
break;
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \
if (IsStruct(field->value.type)) { \
SerializeStruct(*field->value.type.struct_def, field_value); \
} else { \
CTYPE val; \
ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
builder_.AddOffset(field_value.offset, val); \
} \
break;
FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
case BASE_TYPE_ARRAY:
builder_.Pad(field->padding);
builder_.PushBytes(
reinterpret_cast<const uint8_t*>(field_value.constant.c_str()),
InlineSize(field_value.type));
break;
// clang-format on
}
}
}
}
for (size_t i = 0; i < fieldn_outer; i++) field_stack_.pop_back();
if (struct_def.fixed) {
builder_.ClearOffsets();
builder_.EndStruct();
FLATBUFFERS_ASSERT(value);
// Temporarily store this struct in the value string, since it is to
// be serialized in-place elsewhere.
value->assign(
reinterpret_cast<const char *>(builder_.GetCurrentBufferPointer()),
struct_def.bytesize);
builder_.PopBytes(struct_def.bytesize);
FLATBUFFERS_ASSERT(!ovalue);
} else {
auto val = builder_.EndTable(start);
if (ovalue) *ovalue = val;
if (value) *value = NumToString(val);
}
return NoError();
}
template <typename F>
CheckedError Parser::ParseVectorDelimiters(uoffset_t &count, F body) {
EXPECT('[');
for (;;) {
if ((!opts.strict_json || !count) && Is(']')) break;
ECHECK(body(count));
count++;
if (Is(']')) break;
ECHECK(ParseComma());
}
NEXT();
return NoError();
}
CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue,
FieldDef *field, size_t fieldn) {
uoffset_t count = 0;
auto err = ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
Value val;
val.type = type;
ECHECK(Recurse([&]() {
return ParseAnyValue(val, field, fieldn, nullptr, count, true);
}));
field_stack_.push_back(std::make_pair(val, nullptr));
return NoError();
});
ECHECK(err);
builder_.StartVector(count * InlineSize(type) / InlineAlignment(type),
InlineAlignment(type));
for (uoffset_t i = 0; i < count; i++) {
// start at the back, since we're building the data backwards.
auto &val = field_stack_.back().first;
switch (val.type.base_type) {
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
case BASE_TYPE_ ## ENUM: \
if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
else { \
CTYPE elem; \
ECHECK(atot(val.constant.c_str(), *this, &elem)); \
builder_.PushElement(elem); \
} \
break;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
// clang-format on
}
field_stack_.pop_back();
}
builder_.ClearOffsets();
*ovalue = builder_.EndVector(count);
return NoError();
}
CheckedError Parser::ParseArray(Value &array) {
std::vector<Value> stack;
FlatBufferBuilder builder;
const auto &type = array.type.VectorType();
auto length = array.type.fixed_length;
uoffset_t count = 0;
auto err = ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
vector_emplace_back(&stack, Value());
auto &val = stack.back();
val.type = type;
if (IsStruct(type)) {
ECHECK(ParseTable(*val.type.struct_def, &val.constant, nullptr));
} else {
ECHECK(ParseSingleValue(nullptr, val, false));
}
return NoError();
});
ECHECK(err);
if (length != count) return Error("Fixed-length array size is incorrect.");
for (auto it = stack.rbegin(); it != stack.rend(); ++it) {
auto &val = *it;
// clang-format off
switch (val.type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
case BASE_TYPE_ ## ENUM: \
if (IsStruct(val.type)) { \
SerializeStruct(builder, *val.type.struct_def, val); \
} else { \
CTYPE elem; \
ECHECK(atot(val.constant.c_str(), *this, &elem)); \
builder.PushElement(elem); \
} \
break;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
default: FLATBUFFERS_ASSERT(0);
}
// clang-format on
}
array.constant.assign(
reinterpret_cast<const char *>(builder.GetCurrentBufferPointer()),
InlineSize(array.type));
return NoError();
}
CheckedError Parser::ParseNestedFlatbuffer(Value &val, FieldDef *field,
size_t fieldn,
const StructDef *parent_struct_def) {
if (token_ == '[') { // backwards compat for 'legacy' ubyte buffers
ECHECK(ParseAnyValue(val, field, fieldn, parent_struct_def, 0));
} else {
auto cursor_at_value_begin = cursor_;
ECHECK(SkipAnyJsonValue());
std::string substring(cursor_at_value_begin - 1, cursor_ - 1);
// Create and initialize new parser
Parser nested_parser;
FLATBUFFERS_ASSERT(field->nested_flatbuffer);
nested_parser.root_struct_def_ = field->nested_flatbuffer;
nested_parser.enums_ = enums_;
nested_parser.opts = opts;
nested_parser.uses_flexbuffers_ = uses_flexbuffers_;
// Parse JSON substring into new flatbuffer builder using nested_parser
bool ok = nested_parser.Parse(substring.c_str(), nullptr, nullptr);
// Clean nested_parser to avoid deleting the elements in
// the SymbolTables on destruction
nested_parser.enums_.dict.clear();
nested_parser.enums_.vec.clear();
if (!ok) {
ECHECK(Error(nested_parser.error_));
}
// Force alignment for nested flatbuffer
builder_.ForceVectorAlignment(nested_parser.builder_.GetSize(), sizeof(uint8_t),
nested_parser.builder_.GetBufferMinAlignment());
auto off = builder_.CreateVector(nested_parser.builder_.GetBufferPointer(),
nested_parser.builder_.GetSize());
val.constant = NumToString(off.o);
}
return NoError();
}
CheckedError Parser::ParseMetaData(SymbolTable<Value> *attributes) {
if (Is('(')) {
NEXT();
for (;;) {
auto name = attribute_;
if (false == (Is(kTokenIdentifier) || Is(kTokenStringConstant)))
return Error("attribute name must be either identifier or string: " +
name);
if (known_attributes_.find(name) == known_attributes_.end())
return Error("user define attributes must be declared before use: " +
name);
NEXT();
auto e = new Value();
attributes->Add(name, e);
if (Is(':')) {
NEXT();
ECHECK(ParseSingleValue(&name, *e, true));
}
if (Is(')')) {
NEXT();
break;
}
EXPECT(',');
}
}
return NoError();
}
CheckedError Parser::TryTypedValue(const std::string *name, int dtoken,
bool check, Value &e, BaseType req,
bool *destmatch) {
bool match = dtoken == token_;
if (match) {
FLATBUFFERS_ASSERT(*destmatch == false);
*destmatch = true;
e.constant = attribute_;
// Check token match
if (!check) {
if (e.type.base_type == BASE_TYPE_NONE) {
e.type.base_type = req;
} else {
return Error(
std::string("type mismatch: expecting: ") +
kTypeNames[e.type.base_type] + ", found: " + kTypeNames[req] +
", name: " + (name ? *name : "") + ", value: " + e.constant);
}
}
// The exponent suffix of hexadecimal float-point number is mandatory.
// A hex-integer constant is forbidden as an initializer of float number.
if ((kTokenFloatConstant != dtoken) && IsFloat(e.type.base_type)) {
const auto &s = e.constant;
const auto k = s.find_first_of("0123456789.");
if ((std::string::npos != k) && (s.length() > (k + 1)) &&
(s[k] == '0' && is_alpha_char(s[k + 1], 'X')) &&
(std::string::npos == s.find_first_of("pP", k + 2))) {
return Error(
"invalid number, the exponent suffix of hexadecimal "
"floating-point literals is mandatory: \"" +
s + "\"");
}
}
NEXT();
}
return NoError();
}
CheckedError Parser::ParseEnumFromString(const Type &type,
std::string *result) {
const auto base_type =
type.enum_def ? type.enum_def->underlying_type.base_type : type.base_type;
if (!IsInteger(base_type)) return Error("not a valid value for this field");
uint64_t u64 = 0;
for (size_t pos = 0; pos != std::string::npos;) {
const auto delim = attribute_.find_first_of(' ', pos);
const auto last = (std::string::npos == delim);
auto word = attribute_.substr(pos, !last ? delim - pos : std::string::npos);
pos = !last ? delim + 1 : std::string::npos;
const EnumVal *ev = nullptr;
if (type.enum_def) {
ev = type.enum_def->Lookup(word);
} else {
auto dot = word.find_first_of('.');
if (std::string::npos == dot)
return Error("enum values need to be qualified by an enum type");
auto enum_def_str = word.substr(0, dot);
const auto enum_def = LookupEnum(enum_def_str);
if (!enum_def) return Error("unknown enum: " + enum_def_str);
auto enum_val_str = word.substr(dot + 1);
ev = enum_def->Lookup(enum_val_str);
}
if (!ev) return Error("unknown enum value: " + word);
u64 |= ev->GetAsUInt64();
}
*result = IsUnsigned(base_type) ? NumToString(u64)
: NumToString(static_cast<int64_t>(u64));
return NoError();
}
CheckedError Parser::ParseHash(Value &e, FieldDef *field) {
FLATBUFFERS_ASSERT(field);
Value *hash_name = field->attributes.Lookup("hash");
switch (e.type.base_type) {
case BASE_TYPE_SHORT: {
auto hash = FindHashFunction16(hash_name->constant.c_str());
int16_t hashed_value = static_cast<int16_t>(hash(attribute_.c_str()));
e.constant = NumToString(hashed_value);
break;
}
case BASE_TYPE_USHORT: {
auto hash = FindHashFunction16(hash_name->constant.c_str());
uint16_t hashed_value = hash(attribute_.c_str());
e.constant = NumToString(hashed_value);
break;
}
case BASE_TYPE_INT: {
auto hash = FindHashFunction32(hash_name->constant.c_str());
int32_t hashed_value = static_cast<int32_t>(hash(attribute_.c_str()));
e.constant = NumToString(hashed_value);
break;
}
case BASE_TYPE_UINT: {
auto hash = FindHashFunction32(hash_name->constant.c_str());
uint32_t hashed_value = hash(attribute_.c_str());
e.constant = NumToString(hashed_value);
break;
}
case BASE_TYPE_LONG: {
auto hash = FindHashFunction64(hash_name->constant.c_str());
int64_t hashed_value = static_cast<int64_t>(hash(attribute_.c_str()));
e.constant = NumToString(hashed_value);
break;
}
case BASE_TYPE_ULONG: {
auto hash = FindHashFunction64(hash_name->constant.c_str());
uint64_t hashed_value = hash(attribute_.c_str());
e.constant = NumToString(hashed_value);
break;
}
default: FLATBUFFERS_ASSERT(0);
}
NEXT();
return NoError();
}
CheckedError Parser::TokenError() {
return Error("cannot parse value starting with: " + TokenToStringId(token_));
}
// Re-pack helper (ParseSingleValue) to normalize defaults of scalars.
template<typename T> inline void SingleValueRepack(Value &e, T val) {
// Remove leading zeros.
if (IsInteger(e.type.base_type)) { e.constant = NumToString(val); }
}
#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
// Normilaze defaults NaN to unsigned quiet-NaN(0).
static inline void SingleValueRepack(Value& e, float val) {
if (val != val) e.constant = "nan";
}
static inline void SingleValueRepack(Value& e, double val) {
if (val != val) e.constant = "nan";
}
#endif
CheckedError Parser::ParseSingleValue(const std::string *name, Value &e,
bool check_now) {
// First see if this could be a conversion function:
if (token_ == kTokenIdentifier && *cursor_ == '(') {
// todo: Extract processing of conversion functions to ParseFunction.
const auto functionname = attribute_;
if (!IsFloat(e.type.base_type)) {
return Error(functionname + ": type of argument mismatch, expecting: " +
kTypeNames[BASE_TYPE_DOUBLE] +
", found: " + kTypeNames[e.type.base_type] +
", name: " + (name ? *name : "") + ", value: " + e.constant);
}
NEXT();
EXPECT('(');
ECHECK(Recurse([&]() { return ParseSingleValue(name, e, false); }));
EXPECT(')');
// calculate with double precision
double x, y = 0.0;
ECHECK(atot(e.constant.c_str(), *this, &x));
auto func_match = false;
// clang-format off
#define FLATBUFFERS_FN_DOUBLE(name, op) \
if (!func_match && functionname == name) { y = op; func_match = true; }
FLATBUFFERS_FN_DOUBLE("deg", x / kPi * 180);
FLATBUFFERS_FN_DOUBLE("rad", x * kPi / 180);
FLATBUFFERS_FN_DOUBLE("sin", sin(x));
FLATBUFFERS_FN_DOUBLE("cos", cos(x));
FLATBUFFERS_FN_DOUBLE("tan", tan(x));
FLATBUFFERS_FN_DOUBLE("asin", asin(x));
FLATBUFFERS_FN_DOUBLE("acos", acos(x));
FLATBUFFERS_FN_DOUBLE("atan", atan(x));
// TODO(wvo): add more useful conversion functions here.
#undef FLATBUFFERS_FN_DOUBLE
// clang-format on
if (true != func_match) {
return Error(std::string("Unknown conversion function: ") + functionname +
", field name: " + (name ? *name : "") +
", value: " + e.constant);
}
e.constant = NumToString(y);
return NoError();
}
auto match = false;
const auto in_type = e.type.base_type;
// clang-format off
#define IF_ECHECK_(force, dtoken, check, req) \
if (!match && ((check) || IsConstTrue(force))) \
ECHECK(TryTypedValue(name, dtoken, check, e, req, &match))
#define TRY_ECHECK(dtoken, check, req) IF_ECHECK_(false, dtoken, check, req)
#define FORCE_ECHECK(dtoken, check, req) IF_ECHECK_(true, dtoken, check, req)
// clang-format on
if (token_ == kTokenStringConstant || token_ == kTokenIdentifier) {
const auto kTokenStringOrIdent = token_;
// The string type is a most probable type, check it first.
TRY_ECHECK(kTokenStringConstant, in_type == BASE_TYPE_STRING,
BASE_TYPE_STRING);
// avoid escaped and non-ascii in the string
if (!match && (token_ == kTokenStringConstant) && IsScalar(in_type) &&
!attr_is_trivial_ascii_string_) {
return Error(
std::string("type mismatch or invalid value, an initializer of "
"non-string field must be trivial ASCII string: type: ") +
kTypeNames[in_type] + ", name: " + (name ? *name : "") +
", value: " + attribute_);
}
// A boolean as true/false. Boolean as Integer check below.
if (!match && IsBool(in_type)) {
auto is_true = attribute_ == "true";
if (is_true || attribute_ == "false") {
attribute_ = is_true ? "1" : "0";
// accepts both kTokenStringConstant and kTokenIdentifier
TRY_ECHECK(kTokenStringOrIdent, IsBool(in_type), BASE_TYPE_BOOL);
}
}
// Check if this could be a string/identifier enum value.
// Enum can have only true integer base type.
if (!match && IsInteger(in_type) && !IsBool(in_type) &&
IsIdentifierStart(*attribute_.c_str())) {
ECHECK(ParseEnumFromString(e.type, &e.constant));
NEXT();
match = true;
}
// Parse a float/integer number from the string.
if (!match) check_now = true; // Re-pack if parsed from string literal.
if (!match && (token_ == kTokenStringConstant) && IsScalar(in_type)) {
// remove trailing whitespaces from attribute_
auto last = attribute_.find_last_not_of(' ');
if (std::string::npos != last) // has non-whitespace
attribute_.resize(last + 1);
}
// Float numbers or nan, inf, pi, etc.
TRY_ECHECK(kTokenStringOrIdent, IsFloat(in_type), BASE_TYPE_FLOAT);
// An integer constant in string.
TRY_ECHECK(kTokenStringOrIdent, IsInteger(in_type), BASE_TYPE_INT);
// Unknown tokens will be interpreted as string type.
FORCE_ECHECK(kTokenStringConstant, in_type == BASE_TYPE_STRING,
BASE_TYPE_STRING);
} else {
// Try a float number.
TRY_ECHECK(kTokenFloatConstant, IsFloat(in_type), BASE_TYPE_FLOAT);
// Integer token can init any scalar (integer of float).
FORCE_ECHECK(kTokenIntegerConstant, IsScalar(in_type), BASE_TYPE_INT);
}
#undef FORCE_ECHECK
#undef TRY_ECHECK
#undef IF_ECHECK_
if (!match) return TokenError();
const auto match_type = e.type.base_type; // may differ from in_type
// The check_now flag must be true when parse a fbs-schema.
// This flag forces to check default scalar values or metadata of field.
// For JSON parser the flag should be false.
// If it is set for JSON each value will be checked twice (see ParseTable).
if (check_now && IsScalar(match_type)) {
// clang-format off
switch (match_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
case BASE_TYPE_ ## ENUM: {\
CTYPE val; \
ECHECK(atot(e.constant.c_str(), *this, &val)); \
SingleValueRepack(e, val); \
break; }
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
default: break;
}
// clang-format on
}
return NoError();
}
StructDef *Parser::LookupCreateStruct(const std::string &name,
bool create_if_new, bool definition) {
std::string qualified_name = current_namespace_->GetFullyQualifiedName(name);
// See if it exists pre-declared by an unqualified use.
auto struct_def = LookupStruct(name);
if (struct_def && struct_def->predecl) {
if (definition) {
// Make sure it has the current namespace, and is registered under its
// qualified name.
struct_def->defined_namespace = current_namespace_;
structs_.Move(name, qualified_name);
}
return struct_def;
}
// See if it exists pre-declared by an qualified use.
struct_def = LookupStruct(qualified_name);
if (struct_def && struct_def->predecl) {
if (definition) {
// Make sure it has the current namespace.
struct_def->defined_namespace = current_namespace_;
}
return struct_def;
}
if (!definition) {
// Search thru parent namespaces.
for (size_t components = current_namespace_->components.size();
components && !struct_def; components--) {
struct_def = LookupStruct(
current_namespace_->GetFullyQualifiedName(name, components - 1));
}
}
if (!struct_def && create_if_new) {
struct_def = new StructDef();
if (definition) {
structs_.Add(qualified_name, struct_def);
struct_def->name = name;
struct_def->defined_namespace = current_namespace_;
} else {
// Not a definition.
// Rather than failing, we create a "pre declared" StructDef, due to
// circular references, and check for errors at the end of parsing.
// It is defined in the current namespace, as the best guess what the
// final namespace will be.
structs_.Add(name, struct_def);
struct_def->name = name;
struct_def->defined_namespace = current_namespace_;
struct_def->original_location.reset(
new std::string(file_being_parsed_ + ":" + NumToString(line_)));
}
}
return struct_def;
}
const EnumVal *EnumDef::MinValue() const {
return vals.vec.empty() ? nullptr : vals.vec.front();
}
const EnumVal *EnumDef::MaxValue() const {
return vals.vec.empty() ? nullptr : vals.vec.back();
}
template<typename T> static uint64_t EnumDistanceImpl(T e1, T e2) {
if (e1 < e2) { std::swap(e1, e2); } // use std for scalars
// Signed overflow may occur, use unsigned calculation.
// The unsigned overflow is well-defined by C++ standard (modulo 2^n).
return static_cast<uint64_t>(e1) - static_cast<uint64_t>(e2);
}
uint64_t EnumDef::Distance(const EnumVal *v1, const EnumVal *v2) const {
return IsUInt64() ? EnumDistanceImpl(v1->GetAsUInt64(), v2->GetAsUInt64())
: EnumDistanceImpl(v1->GetAsInt64(), v2->GetAsInt64());
}
std::string EnumDef::AllFlags() const {
FLATBUFFERS_ASSERT(attributes.Lookup("bit_flags"));
uint64_t u64 = 0;
for (auto it = Vals().begin(); it != Vals().end(); ++it) {
u64 |= (*it)->GetAsUInt64();
}
return IsUInt64() ? NumToString(u64) : NumToString(static_cast<int64_t>(u64));
}
EnumVal *EnumDef::ReverseLookup(int64_t enum_idx,
bool skip_union_default) const {
auto skip_first = static_cast<int>(is_union && skip_union_default);
for (auto it = Vals().begin() + skip_first; it != Vals().end(); ++it) {
if ((*it)->GetAsInt64() == enum_idx) { return *it; }
}
return nullptr;
}
EnumVal *EnumDef::FindByValue(const std::string &constant) const {
int64_t i64;
auto done = false;
if (IsUInt64()) {
uint64_t u64; // avoid reinterpret_cast of pointers
done = StringToNumber(constant.c_str(), &u64);
i64 = static_cast<int64_t>(u64);
} else {
done = StringToNumber(constant.c_str(), &i64);
}
FLATBUFFERS_ASSERT(done);
if (!done) return nullptr;
return ReverseLookup(i64, false);
}
void EnumDef::SortByValue() {
auto &v = vals.vec;
if (IsUInt64())
std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
return e1->GetAsUInt64() < e2->GetAsUInt64();
});
else
std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
return e1->GetAsInt64() < e2->GetAsInt64();
});
}
void EnumDef::RemoveDuplicates() {
// This method depends form SymbolTable implementation!
// 1) vals.vec - owner (raw pointer)
// 2) vals.dict - access map
auto first = vals.vec.begin();
auto last = vals.vec.end();
if (first == last) return;
auto result = first;
while (++first != last) {
if ((*result)->value != (*first)->value) {
*(++result) = *first;
} else {
auto ev = *first;
for (auto it = vals.dict.begin(); it != vals.dict.end(); ++it) {
if (it->second == ev) it->second = *result; // reassign
}
delete ev; // delete enum value
*first = nullptr;
}
}
vals.vec.erase(++result, last);
}
template<typename T> void EnumDef::ChangeEnumValue(EnumVal *ev, T new_value) {
ev->value = static_cast<int64_t>(new_value);
}
namespace EnumHelper {
template<BaseType E> struct EnumValType { typedef int64_t type; };
template<> struct EnumValType<BASE_TYPE_ULONG> { typedef uint64_t type; };
} // namespace EnumHelper
struct EnumValBuilder {
EnumVal *CreateEnumerator(const std::string &ev_name) {
FLATBUFFERS_ASSERT(!temp);
auto first = enum_def.vals.vec.empty();
user_value = first;
temp = new EnumVal(ev_name, first ? 0 : enum_def.vals.vec.back()->value);
return temp;
}
EnumVal *CreateEnumerator(const std::string &ev_name, int64_t val) {
FLATBUFFERS_ASSERT(!temp);
user_value = true;
temp = new EnumVal(ev_name, val);
return temp;
}
FLATBUFFERS_CHECKED_ERROR AcceptEnumerator(const std::string &name) {
FLATBUFFERS_ASSERT(temp);
ECHECK(ValidateValue(&temp->value, false == user_value));
FLATBUFFERS_ASSERT((temp->union_type.enum_def == nullptr) ||
(temp->union_type.enum_def == &enum_def));
auto not_unique = enum_def.vals.Add(name, temp);
temp = nullptr;
if (not_unique) return parser.Error("enum value already exists: " + name);
return NoError();
}
FLATBUFFERS_CHECKED_ERROR AcceptEnumerator() {
return AcceptEnumerator(temp->name);
}
FLATBUFFERS_CHECKED_ERROR AssignEnumeratorValue(const std::string &value) {
user_value = true;
auto fit = false;
auto ascending = false;
if (enum_def.IsUInt64()) {
uint64_t u64;
fit = StringToNumber(value.c_str(), &u64);
ascending = u64 > temp->GetAsUInt64();
temp->value = static_cast<int64_t>(u64); // well-defined since C++20.
} else {
int64_t i64;
fit = StringToNumber(value.c_str(), &i64);
ascending = i64 > temp->GetAsInt64();
temp->value = i64;
}
if (!fit) return parser.Error("enum value does not fit, \"" + value + "\"");
if (!ascending && strict_ascending && !enum_def.vals.vec.empty())
return parser.Error("enum values must be specified in ascending order");
return NoError();
}
template<BaseType E, typename CTYPE>
inline FLATBUFFERS_CHECKED_ERROR ValidateImpl(int64_t *ev, int m) {
typedef typename EnumHelper::EnumValType<E>::type T; // int64_t or uint64_t
static_assert(sizeof(T) == sizeof(int64_t), "invalid EnumValType");
const auto v = static_cast<T>(*ev);
auto up = static_cast<T>((flatbuffers::numeric_limits<CTYPE>::max)());
auto dn = static_cast<T>((flatbuffers::numeric_limits<CTYPE>::lowest)());
if (v < dn || v > (up - m)) {
return parser.Error("enum value does not fit, \"" + NumToString(v) +
(m ? " + 1\"" : "\"") + " out of " +
TypeToIntervalString<CTYPE>());
}
*ev = static_cast<int64_t>(v + m); // well-defined since C++20.
return NoError();
}
FLATBUFFERS_CHECKED_ERROR ValidateValue(int64_t *ev, bool next) {
// clang-format off
switch (enum_def.underlying_type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, \
PTYPE, RTYPE, KTYPE) \
case BASE_TYPE_##ENUM: { \
if (!IsInteger(BASE_TYPE_##ENUM)) break; \
return ValidateImpl<BASE_TYPE_##ENUM, CTYPE>(ev, next ? 1 : 0); \
}
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
default: break;
}
// clang-format on
return parser.Error("fatal: invalid enum underlying type");
}
EnumValBuilder(Parser &_parser, EnumDef &_enum_def, bool strict_order = true)
: parser(_parser),
enum_def(_enum_def),
temp(nullptr),
strict_ascending(strict_order),
user_value(false) {}
~EnumValBuilder() { delete temp; }
Parser &parser;
EnumDef &enum_def;
EnumVal *temp;
const bool strict_ascending;
bool user_value;
};
CheckedError Parser::ParseEnum(const bool is_union, EnumDef **dest) {
std::vector<std::string> enum_comment = doc_comment_;
NEXT();
std::string enum_name = attribute_;
EXPECT(kTokenIdentifier);
EnumDef *enum_def;
ECHECK(StartEnum(enum_name, is_union, &enum_def));
enum_def->doc_comment = enum_comment;
if (!is_union && !opts.proto_mode) {
// Give specialized error message, since this type spec used to
// be optional in the first FlatBuffers release.
if (!Is(':')) {
return Error(
"must specify the underlying integer type for this"
" enum (e.g. \': short\', which was the default).");
} else {
NEXT();
}
// Specify the integer type underlying this enum.
ECHECK(ParseType(enum_def->underlying_type));
if (!IsInteger(enum_def->underlying_type.base_type) ||
IsBool(enum_def->underlying_type.base_type))
return Error("underlying enum type must be integral");
// Make this type refer back to the enum it was derived from.
enum_def->underlying_type.enum_def = enum_def;
}
ECHECK(ParseMetaData(&enum_def->attributes));
const auto underlying_type = enum_def->underlying_type.base_type;
if (enum_def->attributes.Lookup("bit_flags") &&
!IsUnsigned(underlying_type)) {
// todo: Convert to the Error in the future?
Warning("underlying type of bit_flags enum must be unsigned");
}
// Protobuf allows them to be specified in any order, so sort afterwards.
const auto strict_ascending = (false == opts.proto_mode);
EnumValBuilder evb(*this, *enum_def, strict_ascending);
EXPECT('{');
// A lot of code generatos expect that an enum is not-empty.
if ((is_union || Is('}')) && !opts.proto_mode) {
evb.CreateEnumerator("NONE");
ECHECK(evb.AcceptEnumerator());
}
std::set<std::pair<BaseType, StructDef *>> union_types;
while (!Is('}')) {
if (opts.proto_mode && attribute_ == "option") {
ECHECK(ParseProtoOption());
} else {
auto &ev = *evb.CreateEnumerator(attribute_);
auto full_name = ev.name;
ev.doc_comment = doc_comment_;
EXPECT(kTokenIdentifier);
if (is_union) {
ECHECK(ParseNamespacing(&full_name, &ev.name));
if (opts.union_value_namespacing) {
// Since we can't namespace the actual enum identifiers, turn
// namespace parts into part of the identifier.
ev.name = full_name;
std::replace(ev.name.begin(), ev.name.end(), '.', '_');
}
if (Is(':')) {
NEXT();
ECHECK(ParseType(ev.union_type));
if (ev.union_type.base_type != BASE_TYPE_STRUCT &&
ev.union_type.base_type != BASE_TYPE_STRING)
return Error("union value type may only be table/struct/string");
} else {
ev.union_type = Type(BASE_TYPE_STRUCT, LookupCreateStruct(full_name));
}
if (!enum_def->uses_multiple_type_instances) {
auto ins = union_types.insert(std::make_pair(
ev.union_type.base_type, ev.union_type.struct_def));
enum_def->uses_multiple_type_instances = (false == ins.second);
}
}
if (Is('=')) {
NEXT();
ECHECK(evb.AssignEnumeratorValue(attribute_));
EXPECT(kTokenIntegerConstant);
} else if (false == strict_ascending) {
// The opts.proto_mode flag is active.
return Error("Protobuf mode doesn't allow implicit enum values.");
}
ECHECK(evb.AcceptEnumerator());
if (opts.proto_mode && Is('[')) {
NEXT();
// ignore attributes on enums.
while (token_ != ']') NEXT();
NEXT();
}
}
if (!Is(opts.proto_mode ? ';' : ',')) break;
NEXT();
}
EXPECT('}');
// At this point, the enum can be empty if input is invalid proto-file.
if (!enum_def->size())
return Error("incomplete enum declaration, values not found");
if (enum_def->attributes.Lookup("bit_flags")) {
const auto base_width = static_cast<uint64_t>(8 * SizeOf(underlying_type));
for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end();
++it) {
auto ev = *it;
const auto u = ev->GetAsUInt64();
// Stop manipulations with the sign.
if (!IsUnsigned(underlying_type) && u == (base_width - 1))
return Error("underlying type of bit_flags enum must be unsigned");
if (u >= base_width)
return Error("bit flag out of range of underlying integral type");
enum_def->ChangeEnumValue(ev, 1ULL << u);
}
}
if (false == strict_ascending)
enum_def->SortByValue(); // Must be sorted to use MinValue/MaxValue.
if (dest) *dest = enum_def;
types_.Add(current_namespace_->GetFullyQualifiedName(enum_def->name),
new Type(BASE_TYPE_UNION, nullptr, enum_def));
return NoError();
}
CheckedError Parser::StartStruct(const std::string &name, StructDef **dest) {
auto &struct_def = *LookupCreateStruct(name, true, true);
if (!struct_def.predecl) return Error("datatype already exists: " + name);
struct_def.predecl = false;
struct_def.name = name;
struct_def.file = file_being_parsed_;
// Move this struct to the back of the vector just in case it was predeclared,
// to preserve declaration order.
*std::remove(structs_.vec.begin(), structs_.vec.end(), &struct_def) =
&struct_def;
*dest = &struct_def;
return NoError();
}
CheckedError Parser::CheckClash(std::vector<FieldDef *> &fields,
StructDef *struct_def, const char *suffix,
BaseType basetype) {
auto len = strlen(suffix);
for (auto it = fields.begin(); it != fields.end(); ++it) {
auto &fname = (*it)->name;
if (fname.length() > len &&
fname.compare(fname.length() - len, len, suffix) == 0 &&
(*it)->value.type.base_type != BASE_TYPE_UTYPE) {
auto field =
struct_def->fields.Lookup(fname.substr(0, fname.length() - len));
if (field && field->value.type.base_type == basetype)
return Error("Field " + fname +
" would clash with generated functions for field " +
field->name);
}
}
return NoError();
}
bool Parser::SupportsAdvancedUnionFeatures() const {
return opts.lang_to_generate != 0 &&
(opts.lang_to_generate & ~(IDLOptions::kCpp | IDLOptions::kJs |
IDLOptions::kTs | IDLOptions::kPhp |
IDLOptions::kJava | IDLOptions::kCSharp |
IDLOptions::kKotlin |
IDLOptions::kBinary)) == 0;
}
bool Parser::SupportsAdvancedArrayFeatures() const {
return (opts.lang_to_generate &
~(IDLOptions::kCpp | IDLOptions::kPython | IDLOptions::kJava |
IDLOptions::kCSharp | IDLOptions::kJsonSchema | IDLOptions::kJson |
IDLOptions::kBinary)) == 0;
}
Namespace *Parser::UniqueNamespace(Namespace *ns) {
for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
if (ns->components == (*it)->components) {
delete ns;
return *it;
}
}
namespaces_.push_back(ns);
return ns;
}
std::string Parser::UnqualifiedName(const std::string &full_qualified_name) {
Namespace *ns = new Namespace();
std::size_t current, previous = 0;
current = full_qualified_name.find('.');
while (current != std::string::npos) {
ns->components.push_back(
full_qualified_name.substr(previous, current - previous));
previous = current + 1;
current = full_qualified_name.find('.', previous);
}
current_namespace_ = UniqueNamespace(ns);
return full_qualified_name.substr(previous, current - previous);
}
static bool compareFieldDefs(const FieldDef *a, const FieldDef *b) {
auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str());
auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str());
return a_id < b_id;
}
CheckedError Parser::ParseDecl() {
std::vector<std::string> dc = doc_comment_;
bool fixed = IsIdent("struct");
if (!fixed && !IsIdent("table")) return Error("declaration expected");
NEXT();
std::string name = attribute_;
EXPECT(kTokenIdentifier);
StructDef *struct_def;
ECHECK(StartStruct(name, &struct_def));
struct_def->doc_comment = dc;
struct_def->fixed = fixed;
ECHECK(ParseMetaData(&struct_def->attributes));
struct_def->sortbysize =
struct_def->attributes.Lookup("original_order") == nullptr && !fixed;
EXPECT('{');
while (token_ != '}') ECHECK(ParseField(*struct_def));
auto force_align = struct_def->attributes.Lookup("force_align");
if (fixed) {
if (force_align) {
auto align = static_cast<size_t>(atoi(force_align->constant.c_str()));
if (force_align->type.base_type != BASE_TYPE_INT ||
align < struct_def->minalign || align > FLATBUFFERS_MAX_ALIGNMENT ||
align & (align - 1))
return Error(
"force_align must be a power of two integer ranging from the"
"struct\'s natural alignment to " +
NumToString(FLATBUFFERS_MAX_ALIGNMENT));
struct_def->minalign = align;
}
if (!struct_def->bytesize) return Error("size 0 structs not allowed");
}
struct_def->PadLastField(struct_def->minalign);
// Check if this is a table that has manual id assignments
auto &fields = struct_def->fields.vec;
if (!fixed && fields.size()) {
size_t num_id_fields = 0;
for (auto it = fields.begin(); it != fields.end(); ++it) {
if ((*it)->attributes.Lookup("id")) num_id_fields++;
}
// If any fields have ids..
if (num_id_fields) {
// Then all fields must have them.
if (num_id_fields != fields.size())
return Error(
"either all fields or no fields must have an 'id' attribute");
// Simply sort by id, then the fields are the same as if no ids had
// been specified.
std::sort(fields.begin(), fields.end(), compareFieldDefs);
// Verify we have a contiguous set, and reassign vtable offsets.
for (int i = 0; i < static_cast<int>(fields.size()); i++) {
if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str()))
return Error("field id\'s must be consecutive from 0, id " +
NumToString(i) + " missing or set twice");
fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i));
}
}
}
ECHECK(
CheckClash(fields, struct_def, UnionTypeFieldSuffix(), BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, "Type", BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, "_length", BASE_TYPE_VECTOR));
ECHECK(CheckClash(fields, struct_def, "Length", BASE_TYPE_VECTOR));
ECHECK(CheckClash(fields, struct_def, "_byte_vector", BASE_TYPE_STRING));
ECHECK(CheckClash(fields, struct_def, "ByteVector", BASE_TYPE_STRING));
EXPECT('}');
types_.Add(current_namespace_->GetFullyQualifiedName(struct_def->name),
new Type(BASE_TYPE_STRUCT, struct_def, nullptr));
return NoError();
}
CheckedError Parser::ParseService() {
std::vector<std::string> service_comment = doc_comment_;
NEXT();
auto service_name = attribute_;
EXPECT(kTokenIdentifier);
auto &service_def = *new ServiceDef();
service_def.name = service_name;
service_def.file = file_being_parsed_;
service_def.doc_comment = service_comment;
service_def.defined_namespace = current_namespace_;
if (services_.Add(current_namespace_->GetFullyQualifiedName(service_name),
&service_def))
return Error("service already exists: " + service_name);
ECHECK(ParseMetaData(&service_def.attributes));
EXPECT('{');
do {
std::vector<std::string> doc_comment = doc_comment_;
auto rpc_name = attribute_;
EXPECT(kTokenIdentifier);
EXPECT('(');
Type reqtype, resptype;
ECHECK(ParseTypeIdent(reqtype));
EXPECT(')');
EXPECT(':');
ECHECK(ParseTypeIdent(resptype));
if (reqtype.base_type != BASE_TYPE_STRUCT || reqtype.struct_def->fixed ||
resptype.base_type != BASE_TYPE_STRUCT || resptype.struct_def->fixed)
return Error("rpc request and response types must be tables");
auto &rpc = *new RPCCall();
rpc.name = rpc_name;
rpc.request = reqtype.struct_def;
rpc.response = resptype.struct_def;
rpc.doc_comment = doc_comment;
if (service_def.calls.Add(rpc_name, &rpc))
return Error("rpc already exists: " + rpc_name);
ECHECK(ParseMetaData(&rpc.attributes));
EXPECT(';');
} while (token_ != '}');
NEXT();
return NoError();
}
bool Parser::SetRootType(const char *name) {
root_struct_def_ = LookupStruct(name);
if (!root_struct_def_)
root_struct_def_ =
LookupStruct(current_namespace_->GetFullyQualifiedName(name));
return root_struct_def_ != nullptr;
}
void Parser::MarkGenerated() {
// This function marks all existing definitions as having already
// been generated, which signals no code for included files should be
// generated.
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
(*it)->generated = true;
}
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
if (!(*it)->predecl) { (*it)->generated = true; }
}
for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
(*it)->generated = true;
}
}
CheckedError Parser::ParseNamespace() {
NEXT();
auto ns = new Namespace();
namespaces_.push_back(ns); // Store it here to not leak upon error.
if (token_ != ';') {
for (;;) {
ns->components.push_back(attribute_);
EXPECT(kTokenIdentifier);
if (Is('.')) NEXT() else break;
}
}
namespaces_.pop_back();
current_namespace_ = UniqueNamespace(ns);
EXPECT(';');
return NoError();
}
// Best effort parsing of .proto declarations, with the aim to turn them
// in the closest corresponding FlatBuffer equivalent.
// We parse everything as identifiers instead of keywords, since we don't
// want protobuf keywords to become invalid identifiers in FlatBuffers.
CheckedError Parser::ParseProtoDecl() {
bool isextend = IsIdent("extend");
if (IsIdent("package")) {
// These are identical in syntax to FlatBuffer's namespace decl.
ECHECK(ParseNamespace());
} else if (IsIdent("message") || isextend) {
std::vector<std::string> struct_comment = doc_comment_;
NEXT();
StructDef *struct_def = nullptr;
Namespace *parent_namespace = nullptr;
if (isextend) {
if (Is('.')) NEXT(); // qualified names may start with a . ?
auto id = attribute_;
EXPECT(kTokenIdentifier);
ECHECK(ParseNamespacing(&id, nullptr));
struct_def = LookupCreateStruct(id, false);
if (!struct_def)
return Error("cannot extend unknown message type: " + id);
} else {
std::string name = attribute_;
EXPECT(kTokenIdentifier);
ECHECK(StartStruct(name, &struct_def));
// Since message definitions can be nested, we create a new namespace.
auto ns = new Namespace();
// Copy of current namespace.
*ns = *current_namespace_;
// But with current message name.
ns->components.push_back(name);
ns->from_table++;
parent_namespace = current_namespace_;
current_namespace_ = UniqueNamespace(ns);
}
struct_def->doc_comment = struct_comment;
ECHECK(ParseProtoFields(struct_def, isextend, false));
if (!isextend) { current_namespace_ = parent_namespace; }
if (Is(';')) NEXT();
} else if (IsIdent("enum")) {
// These are almost the same, just with different terminator:
EnumDef *enum_def;
ECHECK(ParseEnum(false, &enum_def));
if (Is(';')) NEXT();
// Temp: remove any duplicates, as .fbs files can't handle them.
enum_def->RemoveDuplicates();
} else if (IsIdent("syntax")) { // Skip these.
NEXT();
EXPECT('=');
EXPECT(kTokenStringConstant);
EXPECT(';');
} else if (IsIdent("option")) { // Skip these.
ECHECK(ParseProtoOption());
EXPECT(';');
} else if (IsIdent("service")) { // Skip these.
NEXT();
EXPECT(kTokenIdentifier);
ECHECK(ParseProtoCurliesOrIdent());
} else {
return Error("don\'t know how to parse .proto declaration starting with " +
TokenToStringId(token_));
}
return NoError();
}
CheckedError Parser::StartEnum(const std::string &enum_name, bool is_union,
EnumDef **dest) {
auto &enum_def = *new EnumDef();
enum_def.name = enum_name;
enum_def.file = file_being_parsed_;
enum_def.doc_comment = doc_comment_;
enum_def.is_union = is_union;
enum_def.defined_namespace = current_namespace_;
if (enums_.Add(current_namespace_->GetFullyQualifiedName(enum_name),
&enum_def))
return Error("enum already exists: " + enum_name);
enum_def.underlying_type.base_type = is_union ? BASE_TYPE_UTYPE
: BASE_TYPE_INT;
enum_def.underlying_type.enum_def = &enum_def;
if (dest) *dest = &enum_def;
return NoError();
}
CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend,
bool inside_oneof) {
EXPECT('{');
while (token_ != '}') {
if (IsIdent("message") || IsIdent("extend") || IsIdent("enum")) {
// Nested declarations.
ECHECK(ParseProtoDecl());
} else if (IsIdent("extensions")) { // Skip these.
NEXT();
EXPECT(kTokenIntegerConstant);
if (Is(kTokenIdentifier)) {
NEXT(); // to
NEXT(); // num
}
EXPECT(';');
} else if (IsIdent("option")) { // Skip these.
ECHECK(ParseProtoOption());
EXPECT(';');
} else if (IsIdent("reserved")) { // Skip these.
NEXT();
while (!Is(';')) { NEXT(); } // A variety of formats, just skip.
NEXT();
} else {
std::vector<std::string> field_comment = doc_comment_;
// Parse the qualifier.
bool required = false;
bool repeated = false;
bool oneof = false;
if (!inside_oneof) {
if (IsIdent("optional")) {
// This is the default.
NEXT();
} else if (IsIdent("required")) {
required = true;
NEXT();
} else if (IsIdent("repeated")) {
repeated = true;
NEXT();
} else if (IsIdent("oneof")) {
oneof = true;
NEXT();
} else {
// can't error, proto3 allows decls without any of the above.
}
}
StructDef *anonymous_struct = nullptr;
EnumDef *oneof_union = nullptr;
Type type;
if (IsIdent("group") || oneof) {
if (!oneof) NEXT();
if (oneof && opts.proto_oneof_union) {
auto name = MakeCamel(attribute_, true) + "Union";
ECHECK(StartEnum(name, true, &oneof_union));
type = Type(BASE_TYPE_UNION, nullptr, oneof_union);
} else {
auto name = "Anonymous" + NumToString(anonymous_counter++);
ECHECK(StartStruct(name, &anonymous_struct));
type = Type(BASE_TYPE_STRUCT, anonymous_struct);
}
} else {
ECHECK(ParseTypeFromProtoType(&type));
}
// Repeated elements get mapped to a vector.
if (repeated) {
type.element = type.base_type;
type.base_type = BASE_TYPE_VECTOR;
if (type.element == BASE_TYPE_VECTOR) {
// We have a vector or vectors, which FlatBuffers doesn't support.
// For now make it a vector of string (since the source is likely
// "repeated bytes").
// TODO(wvo): A better solution would be to wrap this in a table.
type.element = BASE_TYPE_STRING;
}
}
std::string name = attribute_;
EXPECT(kTokenIdentifier);
if (!oneof) {
// Parse the field id. Since we're just translating schemas, not
// any kind of binary compatibility, we can safely ignore these, and
// assign our own.
EXPECT('=');
EXPECT(kTokenIntegerConstant);
}
FieldDef *field = nullptr;
if (isextend) {
// We allow a field to be re-defined when extending.
// TODO: are there situations where that is problematic?
field = struct_def->fields.Lookup(name);
}
if (!field) ECHECK(AddField(*struct_def, name, type, &field));
field->doc_comment = field_comment;
if (!IsScalar(type.base_type)) field->required = required;
// See if there's a default specified.
if (Is('[')) {
NEXT();
for (;;) {
auto key = attribute_;
ECHECK(ParseProtoKey());
EXPECT('=');
auto val = attribute_;
ECHECK(ParseProtoCurliesOrIdent());
if (key == "default") {
// Temp: skip non-numeric defaults (enums).
auto numeric = strpbrk(val.c_str(), "0123456789-+.");
if (IsScalar(type.base_type) && numeric == val.c_str())
field->value.constant = val;
} else if (key == "deprecated") {
field->deprecated = val == "true";
}
if (!Is(',')) break;
NEXT();
}
EXPECT(']');
}
if (anonymous_struct) {
ECHECK(ParseProtoFields(anonymous_struct, false, oneof));
if (Is(';')) NEXT();
} else if (oneof_union) {
// Parse into a temporary StructDef, then transfer fields into an
// EnumDef describing the oneof as a union.
StructDef oneof_struct;
ECHECK(ParseProtoFields(&oneof_struct, false, oneof));
if (Is(';')) NEXT();
for (auto field_it = oneof_struct.fields.vec.begin();
field_it != oneof_struct.fields.vec.end(); ++field_it) {
const auto &oneof_field = **field_it;
const auto &oneof_type = oneof_field.value.type;
if (oneof_type.base_type != BASE_TYPE_STRUCT ||
!oneof_type.struct_def || oneof_type.struct_def->fixed)
return Error("oneof '" + name +
"' cannot be mapped to a union because member '" +
oneof_field.name + "' is not a table type.");
EnumValBuilder evb(*this, *oneof_union);
auto ev = evb.CreateEnumerator(oneof_type.struct_def->name);
ev->union_type = oneof_type;
ev->doc_comment = oneof_field.doc_comment;
ECHECK(evb.AcceptEnumerator(oneof_field.name));
}
} else {
EXPECT(';');
}
}
}
NEXT();
return NoError();
}
CheckedError Parser::ParseProtoKey() {
if (token_ == '(') {
NEXT();
// Skip "(a.b)" style custom attributes.
while (token_ == '.' || token_ == kTokenIdentifier) NEXT();
EXPECT(')');
while (Is('.')) {
NEXT();
EXPECT(kTokenIdentifier);
}
} else {
EXPECT(kTokenIdentifier);
}
return NoError();
}
CheckedError Parser::ParseProtoCurliesOrIdent() {
if (Is('{')) {
NEXT();
for (int nesting = 1; nesting;) {
if (token_ == '{')
nesting++;
else if (token_ == '}')
nesting--;
NEXT();
}
} else {
NEXT(); // Any single token.
}
return NoError();
}
CheckedError Parser::ParseProtoOption() {
NEXT();
ECHECK(ParseProtoKey());
EXPECT('=');
ECHECK(ParseProtoCurliesOrIdent());
return NoError();
}
// Parse a protobuf type, and map it to the corresponding FlatBuffer one.
CheckedError Parser::ParseTypeFromProtoType(Type *type) {
struct type_lookup {
const char *proto_type;
BaseType fb_type, element;
};
static type_lookup lookup[] = {
{ "float", BASE_TYPE_FLOAT, BASE_TYPE_NONE },
{ "double", BASE_TYPE_DOUBLE, BASE_TYPE_NONE },
{ "int32", BASE_TYPE_INT, BASE_TYPE_NONE },
{ "int64", BASE_TYPE_LONG, BASE_TYPE_NONE },
{ "uint32", BASE_TYPE_UINT, BASE_TYPE_NONE },
{ "uint64", BASE_TYPE_ULONG, BASE_TYPE_NONE },
{ "sint32", BASE_TYPE_INT, BASE_TYPE_NONE },
{ "sint64", BASE_TYPE_LONG, BASE_TYPE_NONE },
{ "fixed32", BASE_TYPE_UINT, BASE_TYPE_NONE },
{ "fixed64", BASE_TYPE_ULONG, BASE_TYPE_NONE },
{ "sfixed32", BASE_TYPE_INT, BASE_TYPE_NONE },
{ "sfixed64", BASE_TYPE_LONG, BASE_TYPE_NONE },
{ "bool", BASE_TYPE_BOOL, BASE_TYPE_NONE },
{ "string", BASE_TYPE_STRING, BASE_TYPE_NONE },
{ "bytes", BASE_TYPE_VECTOR, BASE_TYPE_UCHAR },
{ nullptr, BASE_TYPE_NONE, BASE_TYPE_NONE }
};
for (auto tl = lookup; tl->proto_type; tl++) {
if (attribute_ == tl->proto_type) {
type->base_type = tl->fb_type;
type->element = tl->element;
NEXT();
return NoError();
}
}
if (Is('.')) NEXT(); // qualified names may start with a . ?
ECHECK(ParseTypeIdent(*type));
return NoError();
}
CheckedError Parser::SkipAnyJsonValue() {
switch (token_) {
case '{': {
size_t fieldn_outer = 0;
return ParseTableDelimiters(
fieldn_outer, nullptr,
[&](const std::string &, size_t &fieldn,
const StructDef *) -> CheckedError {
ECHECK(Recurse([&]() { return SkipAnyJsonValue(); }));
fieldn++;
return NoError();
});
}
case '[': {
uoffset_t count = 0;
return ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
return Recurse([&]() { return SkipAnyJsonValue(); });
});
}
case kTokenStringConstant:
case kTokenIntegerConstant:
case kTokenFloatConstant: NEXT(); break;
default:
if (IsIdent("true") || IsIdent("false") || IsIdent("null")) {
NEXT();
} else
return TokenError();
}
return NoError();
}
CheckedError Parser::ParseFlexBufferValue(flexbuffers::Builder *builder) {
switch (token_) {
case '{': {
auto start = builder->StartMap();
size_t fieldn_outer = 0;
auto err =
ParseTableDelimiters(fieldn_outer, nullptr,
[&](const std::string &name, size_t &fieldn,
const StructDef *) -> CheckedError {
builder->Key(name);
ECHECK(ParseFlexBufferValue(builder));
fieldn++;
return NoError();
});
ECHECK(err);
builder->EndMap(start);
break;
}
case '[': {
auto start = builder->StartVector();
uoffset_t count = 0;
ECHECK(ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
return ParseFlexBufferValue(builder);
}));
builder->EndVector(start, false, false);
break;
}
case kTokenStringConstant:
builder->String(attribute_);
EXPECT(kTokenStringConstant);
break;
case kTokenIntegerConstant:
builder->Int(StringToInt(attribute_.c_str()));
EXPECT(kTokenIntegerConstant);
break;
case kTokenFloatConstant:
builder->Double(strtod(attribute_.c_str(), nullptr));
EXPECT(kTokenFloatConstant);
break;
default:
if (IsIdent("true")) {
builder->Bool(true);
NEXT();
} else if (IsIdent("false")) {
builder->Bool(false);
NEXT();
} else if (IsIdent("null")) {
builder->Null();
NEXT();
} else
return TokenError();
}
return NoError();
}
bool Parser::ParseFlexBuffer(const char *source, const char *source_filename,
flexbuffers::Builder *builder) {
auto ok = !StartParseFile(source, source_filename).Check() &&
!ParseFlexBufferValue(builder).Check();
if (ok) builder->Finish();
return ok;
}
bool Parser::Parse(const char *source, const char **include_paths,
const char *source_filename) {
FLATBUFFERS_ASSERT(0 == recurse_protection_counter);
auto r = !ParseRoot(source, include_paths, source_filename).Check();
FLATBUFFERS_ASSERT(0 == recurse_protection_counter);
return r;
}
CheckedError Parser::StartParseFile(const char *source,
const char *source_filename) {
file_being_parsed_ = source_filename ? source_filename : "";
source_ = source;
ResetState(source_);
error_.clear();
ECHECK(SkipByteOrderMark());
NEXT();
if (Is(kTokenEof)) return Error("input file is empty");
return NoError();
}
CheckedError Parser::ParseRoot(const char *source, const char **include_paths,
const char *source_filename) {
ECHECK(DoParse(source, include_paths, source_filename, nullptr));
// Check that all types were defined.
for (auto it = structs_.vec.begin(); it != structs_.vec.end();) {
auto &struct_def = **it;
if (struct_def.predecl) {
if (opts.proto_mode) {
// Protos allow enums to be used before declaration, so check if that
// is the case here.
EnumDef *enum_def = nullptr;
for (size_t components =
struct_def.defined_namespace->components.size() + 1;
components && !enum_def; components--) {
auto qualified_name =
struct_def.defined_namespace->GetFullyQualifiedName(
struct_def.name, components - 1);
enum_def = LookupEnum(qualified_name);
}
if (enum_def) {
// This is pretty slow, but a simple solution for now.
auto initial_count = struct_def.refcount;
for (auto struct_it = structs_.vec.begin();
struct_it != structs_.vec.end(); ++struct_it) {
auto &sd = **struct_it;
for (auto field_it = sd.fields.vec.begin();
field_it != sd.fields.vec.end(); ++field_it) {
auto &field = **field_it;
if (field.value.type.struct_def == &struct_def) {
field.value.type.struct_def = nullptr;
field.value.type.enum_def = enum_def;
auto &bt = field.value.type.base_type == BASE_TYPE_VECTOR
? field.value.type.element
: field.value.type.base_type;
FLATBUFFERS_ASSERT(bt == BASE_TYPE_STRUCT);
bt = enum_def->underlying_type.base_type;
struct_def.refcount--;
enum_def->refcount++;
}
}
}
if (struct_def.refcount)
return Error("internal: " + NumToString(struct_def.refcount) + "/" +
NumToString(initial_count) +
" use(s) of pre-declaration enum not accounted for: " +
enum_def->name);
structs_.dict.erase(structs_.dict.find(struct_def.name));
it = structs_.vec.erase(it);
delete &struct_def;
continue; // Skip error.
}
}
auto err = "type referenced but not defined (check namespace): " +
struct_def.name;
if (struct_def.original_location)
err += ", originally at: " + *struct_def.original_location;
return Error(err);
}
++it;
}
// This check has to happen here and not earlier, because only now do we
// know for sure what the type of these are.
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto &enum_def = **it;
if (enum_def.is_union) {
for (auto val_it = enum_def.Vals().begin();
val_it != enum_def.Vals().end(); ++val_it) {
auto &val = **val_it;
if (!SupportsAdvancedUnionFeatures() && val.union_type.struct_def &&
val.union_type.struct_def->fixed)
return Error(
"only tables can be union elements in the generated language: " +
val.name);
}
}
}
return NoError();
}
CheckedError Parser::DoParse(const char *source, const char **include_paths,
const char *source_filename,
const char *include_filename) {
if (source_filename) {
if (included_files_.find(source_filename) == included_files_.end()) {
included_files_[source_filename] =
include_filename ? include_filename : "";
files_included_per_file_[source_filename] = std::set<std::string>();
} else {
return NoError();
}
}
if (!include_paths) {
static const char *current_directory[] = { "", nullptr };
include_paths = current_directory;
}
field_stack_.clear();
builder_.Clear();
// Start with a blank namespace just in case this file doesn't have one.
current_namespace_ = empty_namespace_;
ECHECK(StartParseFile(source, source_filename));
// Includes must come before type declarations:
for (;;) {
// Parse pre-include proto statements if any:
if (opts.proto_mode && (attribute_ == "option" || attribute_ == "syntax" ||
attribute_ == "package")) {
ECHECK(ParseProtoDecl());
} else if (IsIdent("native_include")) {
NEXT();
vector_emplace_back(&native_included_files_, attribute_);
EXPECT(kTokenStringConstant);
EXPECT(';');
} else if (IsIdent("include") || (opts.proto_mode && IsIdent("import"))) {
NEXT();
if (opts.proto_mode && attribute_ == "public") NEXT();
auto name = flatbuffers::PosixPath(attribute_.c_str());
EXPECT(kTokenStringConstant);
// Look for the file in include_paths.
std::string filepath;
for (auto paths = include_paths; paths && *paths; paths++) {
filepath = flatbuffers::ConCatPathFileName(*paths, name);
if (FileExists(filepath.c_str())) break;
}
if (filepath.empty())
return Error("unable to locate include file: " + name);
if (source_filename)
files_included_per_file_[source_filename].insert(filepath);
if (included_files_.find(filepath) == included_files_.end()) {
// We found an include file that we have not parsed yet.
// Load it and parse it.
std::string contents;
if (!LoadFile(filepath.c_str(), true, &contents))
return Error("unable to load include file: " + name);
ECHECK(DoParse(contents.c_str(), include_paths, filepath.c_str(),
name.c_str()));
// We generally do not want to output code for any included files:
if (!opts.generate_all) MarkGenerated();
// Reset these just in case the included file had them, and the
// parent doesn't.
root_struct_def_ = nullptr;
file_identifier_.clear();
file_extension_.clear();
// This is the easiest way to continue this file after an include:
// instead of saving and restoring all the state, we simply start the
// file anew. This will cause it to encounter the same include
// statement again, but this time it will skip it, because it was
// entered into included_files_.
// This is recursive, but only go as deep as the number of include
// statements.
if (source_filename) {
included_files_.erase(source_filename);
}
return DoParse(source, include_paths, source_filename,
include_filename);
}
EXPECT(';');
} else {
break;
}
}
// Now parse all other kinds of declarations:
while (token_ != kTokenEof) {
if (opts.proto_mode) {
ECHECK(ParseProtoDecl());
} else if (IsIdent("namespace")) {
ECHECK(ParseNamespace());
} else if (token_ == '{') {
if (!root_struct_def_)
return Error("no root type set to parse json with");
if (builder_.GetSize()) {
return Error("cannot have more than one json object in a file");
}
uoffset_t toff;
ECHECK(ParseTable(*root_struct_def_, nullptr, &toff));
if (opts.size_prefixed) {
builder_.FinishSizePrefixed(Offset<Table>(toff), file_identifier_.length()
? file_identifier_.c_str()
: nullptr);
} else {
builder_.Finish(Offset<Table>(toff), file_identifier_.length()
? file_identifier_.c_str()
: nullptr);
}
// Check that JSON file doesn't contain more objects or IDL directives.
// Comments after JSON are allowed.
EXPECT(kTokenEof);
} else if (IsIdent("enum")) {
ECHECK(ParseEnum(false, nullptr));
} else if (IsIdent("union")) {
ECHECK(ParseEnum(true, nullptr));
} else if (IsIdent("root_type")) {
NEXT();
auto root_type = attribute_;
EXPECT(kTokenIdentifier);
ECHECK(ParseNamespacing(&root_type, nullptr));
if (opts.root_type.empty()) {
if (!SetRootType(root_type.c_str()))
return Error("unknown root type: " + root_type);
if (root_struct_def_->fixed)
return Error("root type must be a table");
}
EXPECT(';');
} else if (IsIdent("file_identifier")) {
NEXT();
file_identifier_ = attribute_;
EXPECT(kTokenStringConstant);
if (file_identifier_.length() != FlatBufferBuilder::kFileIdentifierLength)
return Error("file_identifier must be exactly " +
NumToString(FlatBufferBuilder::kFileIdentifierLength) +
" characters");
EXPECT(';');
} else if (IsIdent("file_extension")) {
NEXT();
file_extension_ = attribute_;
EXPECT(kTokenStringConstant);
EXPECT(';');
} else if (IsIdent("include")) {
return Error("includes must come before declarations");
} else if (IsIdent("attribute")) {
NEXT();
auto name = attribute_;
if (Is(kTokenIdentifier)) {
NEXT();
} else {
EXPECT(kTokenStringConstant);
}
EXPECT(';');
known_attributes_[name] = false;
} else if (IsIdent("rpc_service")) {
ECHECK(ParseService());
} else {
ECHECK(ParseDecl());
}
}
return NoError();
}
std::set<std::string> Parser::GetIncludedFilesRecursive(
const std::string &file_name) const {
std::set<std::string> included_files;
std::list<std::string> to_process;
if (file_name.empty()) return included_files;
to_process.push_back(file_name);
while (!to_process.empty()) {
std::string current = to_process.front();
to_process.pop_front();
included_files.insert(current);
// Workaround the lack of const accessor in C++98 maps.
auto &new_files =
(*const_cast<std::map<std::string, std::set<std::string>> *>(
&files_included_per_file_))[current];
for (auto it = new_files.begin(); it != new_files.end(); ++it) {
if (included_files.find(*it) == included_files.end())
to_process.push_back(*it);
}
}
return included_files;
}
// Schema serialization functionality:
template<typename T> bool compareName(const T *a, const T *b) {
return a->defined_namespace->GetFullyQualifiedName(a->name) <
b->defined_namespace->GetFullyQualifiedName(b->name);
}
template<typename T> void AssignIndices(const std::vector<T *> &defvec) {
// Pre-sort these vectors, such that we can set the correct indices for them.
auto vec = defvec;
std::sort(vec.begin(), vec.end(), compareName<T>);
for (int i = 0; i < static_cast<int>(vec.size()); i++) vec[i]->index = i;
}
void Parser::Serialize() {
builder_.Clear();
AssignIndices(structs_.vec);
AssignIndices(enums_.vec);
std::vector<Offset<reflection::Object>> object_offsets;
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
object_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
}
std::vector<Offset<reflection::Enum>> enum_offsets;
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
enum_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
}
std::vector<Offset<reflection::Service>> service_offsets;
for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
service_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
}
auto objs__ = builder_.CreateVectorOfSortedTables(&object_offsets);
auto enum__ = builder_.CreateVectorOfSortedTables(&enum_offsets);
auto fiid__ = builder_.CreateString(file_identifier_);
auto fext__ = builder_.CreateString(file_extension_);
auto serv__ = builder_.CreateVectorOfSortedTables(&service_offsets);
auto schema_offset =
reflection::CreateSchema(builder_, objs__, enum__, fiid__, fext__,
(root_struct_def_ ? root_struct_def_->serialized_location : 0),
serv__);
if (opts.size_prefixed) {
builder_.FinishSizePrefixed(schema_offset, reflection::SchemaIdentifier());
} else {
builder_.Finish(schema_offset, reflection::SchemaIdentifier());
}
}
static Namespace *GetNamespace(
const std::string &qualified_name, std::vector<Namespace *> &namespaces,
std::map<std::string, Namespace *> &namespaces_index) {
size_t dot = qualified_name.find_last_of('.');
std::string namespace_name = (dot != std::string::npos)
? std::string(qualified_name.c_str(), dot)
: "";
Namespace *&ns = namespaces_index[namespace_name];
if (!ns) {
ns = new Namespace();
namespaces.push_back(ns);
size_t pos = 0;
for (;;) {
dot = qualified_name.find('.', pos);
if (dot == std::string::npos) { break; }
ns->components.push_back(qualified_name.substr(pos, dot - pos));
pos = dot + 1;
}
}
return ns;
}
Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<Offset<reflection::Field>> field_offsets;
for (auto it = fields.vec.begin(); it != fields.vec.end(); ++it) {
field_offsets.push_back((*it)->Serialize(
builder, static_cast<uint16_t>(it - fields.vec.begin()), parser));
}
auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
auto name__ = builder->CreateString(qualified_name);
auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateObject(*builder, name__, flds__, fixed,
static_cast<int>(minalign),
static_cast<int>(bytesize),
attr__, docs__);
}
bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) {
if (!DeserializeAttributes(parser, object->attributes()))
return false;
DeserializeDoc(doc_comment, object->documentation());
name = parser.UnqualifiedName(object->name()->str());
predecl = false;
sortbysize = attributes.Lookup("original_order") == nullptr && !fixed;
const auto& of = *(object->fields());
auto indexes = std::vector<uoffset_t>(of.size());
for (uoffset_t i = 0; i < of.size(); i++) indexes[of.Get(i)->id()] = i;
size_t tmp_struct_size = 0;
for (size_t i = 0; i < indexes.size(); i++) {
auto field = of.Get(indexes[i]);
auto field_def = new FieldDef();
if (!field_def->Deserialize(parser, field) ||
fields.Add(field_def->name, field_def)) {
delete field_def;
return false;
}
if (fixed) {
// Recompute padding since that's currently not serialized.
auto size = InlineSize(field_def->value.type);
auto next_field =
i + 1 < indexes.size()
? of.Get(indexes[i+1])
: nullptr;
tmp_struct_size += size;
field_def->padding =
next_field ? (next_field->offset() - field_def->value.offset) - size
: PaddingBytes(tmp_struct_size, minalign);
tmp_struct_size += field_def->padding;
}
}
FLATBUFFERS_ASSERT(static_cast<int>(tmp_struct_size) == object->bytesize());
return true;
}
Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
uint16_t id,
const Parser &parser) const {
auto name__ = builder->CreateString(name);
auto type__ = value.type.Serialize(builder);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateField(*builder, name__, type__, id, value.offset,
// Is uint64>max(int64) tested?
IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0,
// result may be platform-dependent if underlying is float (not double)
IsFloat(value.type.base_type) ? strtod(value.constant.c_str(), nullptr)
: 0.0,
deprecated, required, key, attr__, docs__);
// TODO: value.constant is almost always "0", we could save quite a bit of
// space by sharing it. Same for common values of value.type.
}
bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) {
name = parser.UnqualifiedName(field->name()->str());
defined_namespace = parser.current_namespace_;
if (!value.type.Deserialize(parser, field->type()))
return false;
value.offset = field->offset();
if (IsInteger(value.type.base_type)) {
value.constant = NumToString(field->default_integer());
} else if (IsFloat(value.type.base_type)) {
value.constant = FloatToString(field->default_real(), 16);
size_t last_zero = value.constant.find_last_not_of('0');
if (last_zero != std::string::npos && last_zero != 0) {
value.constant.erase(last_zero, std::string::npos);
}
}
deprecated = field->deprecated();
required = field->required();
key = field->key();
if (!DeserializeAttributes(parser, field->attributes()))
return false;
// TODO: this should probably be handled by a separate attribute
if (attributes.Lookup("flexbuffer")) {
flexbuffer = true;
parser.uses_flexbuffers_ = true;
if (value.type.base_type != BASE_TYPE_VECTOR ||
value.type.element != BASE_TYPE_UCHAR)
return false;
}
DeserializeDoc(doc_comment, field->documentation());
return true;
}
Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
auto name__ = builder->CreateString(name);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateRPCCall(*builder, name__,
request->serialized_location,
response->serialized_location,
attr__, docs__);
}
bool RPCCall::Deserialize(Parser &parser, const reflection::RPCCall *call) {
name = call->name()->str();
if (!DeserializeAttributes(parser, call->attributes()))
return false;
DeserializeDoc(doc_comment, call->documentation());
request = parser.structs_.Lookup(call->request()->name()->str());
response = parser.structs_.Lookup(call->response()->name()->str());
if (!request || !response) { return false; }
return true;
}
Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<Offset<reflection::RPCCall>> servicecall_offsets;
for (auto it = calls.vec.begin(); it != calls.vec.end(); ++it) {
servicecall_offsets.push_back((*it)->Serialize(builder, parser));
}
auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
auto name__ = builder->CreateString(qualified_name);
auto call__ = builder->CreateVector(servicecall_offsets);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateService(*builder, name__, call__, attr__, docs__);
}
bool ServiceDef::Deserialize(Parser &parser,
const reflection::Service *service) {
name = parser.UnqualifiedName(service->name()->str());
if (service->calls()) {
for (uoffset_t i = 0; i < service->calls()->size(); ++i) {
auto call = new RPCCall();
if (!call->Deserialize(parser, service->calls()->Get(i)) ||
calls.Add(call->name, call)) {
delete call;
return false;
}
}
}
if (!DeserializeAttributes(parser, service->attributes()))
return false;
DeserializeDoc(doc_comment, service->documentation());
return true;
}
Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<Offset<reflection::EnumVal>> enumval_offsets;
for (auto it = vals.vec.begin(); it != vals.vec.end(); ++it) {
enumval_offsets.push_back((*it)->Serialize(builder, parser));
}
auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
auto name__ = builder->CreateString(qualified_name);
auto vals__ = builder->CreateVector(enumval_offsets);
auto type__ = underlying_type.Serialize(builder);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateEnum(*builder, name__, vals__, is_union, type__,
attr__, docs__);
}
bool EnumDef::Deserialize(Parser &parser, const reflection::Enum *_enum) {
name = parser.UnqualifiedName(_enum->name()->str());
for (uoffset_t i = 0; i < _enum->values()->size(); ++i) {
auto val = new EnumVal();
if (!val->Deserialize(parser, _enum->values()->Get(i)) ||
vals.Add(val->name, val)) {
delete val;
return false;
}
}
is_union = _enum->is_union();
if (!underlying_type.Deserialize(parser, _enum->underlying_type())) {
return false;
}
if (!DeserializeAttributes(parser, _enum->attributes()))
return false;
DeserializeDoc(doc_comment, _enum->documentation());
return true;
}
Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
auto name__ = builder->CreateString(name);
auto type__ = union_type.Serialize(builder);
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateEnumVal(*builder, name__, value,
union_type.struct_def ? union_type.struct_def->serialized_location : 0,
type__, docs__);
}
bool EnumVal::Deserialize(const Parser &parser,
const reflection::EnumVal *val) {
name = val->name()->str();
value = val->value();
if (!union_type.Deserialize(parser, val->union_type()))
return false;
DeserializeDoc(doc_comment, val->documentation());
return true;
}
Offset<reflection::Type> Type::Serialize(FlatBufferBuilder *builder) const {
return reflection::CreateType(
*builder, static_cast<reflection::BaseType>(base_type),
static_cast<reflection::BaseType>(element),
struct_def ? struct_def->index : (enum_def ? enum_def->index : -1),
fixed_length);
}
bool Type::Deserialize(const Parser &parser, const reflection::Type *type) {
if (type == nullptr) return true;
base_type = static_cast<BaseType>(type->base_type());
element = static_cast<BaseType>(type->element());
fixed_length = type->fixed_length();
if (type->index() >= 0) {
bool is_series = type->base_type() == reflection::Vector ||
type->base_type() == reflection::Array;
if (type->base_type() == reflection::Obj ||
(is_series &&
type->element() == reflection::Obj)) {
if (static_cast<size_t>(type->index()) < parser.structs_.vec.size()) {
struct_def = parser.structs_.vec[type->index()];
struct_def->refcount++;
} else {
return false;
}
} else {
if (static_cast<size_t>(type->index()) < parser.enums_.vec.size()) {
enum_def = parser.enums_.vec[type->index()];
} else {
return false;
}
}
}
return true;
}
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
Definition::SerializeAttributes(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<flatbuffers::Offset<reflection::KeyValue>> attrs;
for (auto kv = attributes.dict.begin(); kv != attributes.dict.end(); ++kv) {
auto it = parser.known_attributes_.find(kv->first);
FLATBUFFERS_ASSERT(it != parser.known_attributes_.end());
if (parser.opts.binary_schema_builtins || !it->second) {
auto key = builder->CreateString(kv->first);
auto val = builder->CreateString(kv->second->constant);
attrs.push_back(reflection::CreateKeyValue(*builder, key, val));
}
}
if (attrs.size()) {
return builder->CreateVectorOfSortedTables(&attrs);
} else {
return 0;
}
}
bool Definition::DeserializeAttributes(
Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs) {
if (attrs == nullptr)
return true;
for (uoffset_t i = 0; i < attrs->size(); ++i) {
auto kv = attrs->Get(i);
auto value = new Value();
if (kv->value()) { value->constant = kv->value()->str(); }
if (attributes.Add(kv->key()->str(), value)) {
delete value;
return false;
}
parser.known_attributes_[kv->key()->str()];
}
return true;
}
/************************************************************************/
/* DESERIALIZATION */
/************************************************************************/
bool Parser::Deserialize(const uint8_t *buf, const size_t size) {
flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(buf), size);
bool size_prefixed = false;
if(!reflection::SchemaBufferHasIdentifier(buf)) {
if (!flatbuffers::BufferHasIdentifier(buf, reflection::SchemaIdentifier(),
true))
return false;
else
size_prefixed = true;
}
auto verify_fn = size_prefixed ? &reflection::VerifySizePrefixedSchemaBuffer
: &reflection::VerifySchemaBuffer;
if (!verify_fn(verifier)) {
return false;
}
auto schema = size_prefixed ? reflection::GetSizePrefixedSchema(buf)
: reflection::GetSchema(buf);
return Deserialize(schema);
}
bool Parser::Deserialize(const reflection::Schema *schema) {
file_identifier_ = schema->file_ident() ? schema->file_ident()->str() : "";
file_extension_ = schema->file_ext() ? schema->file_ext()->str() : "";
std::map<std::string, Namespace *> namespaces_index;
// Create defs without deserializing so references from fields to structs and
// enums can be resolved.
for (auto it = schema->objects()->begin(); it != schema->objects()->end();
++it) {
auto struct_def = new StructDef();
struct_def->bytesize = it->bytesize();
struct_def->fixed = it->is_struct();
struct_def->minalign = it->minalign();
if (structs_.Add(it->name()->str(), struct_def)) {
delete struct_def;
return false;
}
auto type = new Type(BASE_TYPE_STRUCT, struct_def, nullptr);
if (types_.Add(it->name()->str(), type)) {
delete type;
return false;
}
}
for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) {
auto enum_def = new EnumDef();
if (enums_.Add(it->name()->str(), enum_def)) {
delete enum_def;
return false;
}
auto type = new Type(BASE_TYPE_UNION, nullptr, enum_def);
if (types_.Add(it->name()->str(), type)) {
delete type;
return false;
}
}
// Now fields can refer to structs and enums by index.
for (auto it = schema->objects()->begin(); it != schema->objects()->end();
++it) {
std::string qualified_name = it->name()->str();
auto struct_def = structs_.Lookup(qualified_name);
struct_def->defined_namespace =
GetNamespace(qualified_name, namespaces_, namespaces_index);
if (!struct_def->Deserialize(*this, * it)) { return false; }
if (schema->root_table() == *it) { root_struct_def_ = struct_def; }
}
for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) {
std::string qualified_name = it->name()->str();
auto enum_def = enums_.Lookup(qualified_name);
enum_def->defined_namespace =
GetNamespace(qualified_name, namespaces_, namespaces_index);
if (!enum_def->Deserialize(*this, *it)) { return false; }
}
if (schema->services()) {
for (auto it = schema->services()->begin(); it != schema->services()->end();
++it) {
std::string qualified_name = it->name()->str();
auto service_def = new ServiceDef();
service_def->defined_namespace =
GetNamespace(qualified_name, namespaces_, namespaces_index);
if (!service_def->Deserialize(*this, *it) ||
services_.Add(qualified_name, service_def)) {
delete service_def;
return false;
}
}
}
return true;
}
std::string Parser::ConformTo(const Parser &base) {
for (auto sit = structs_.vec.begin(); sit != structs_.vec.end(); ++sit) {
auto &struct_def = **sit;
auto qualified_name =
struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name);
auto struct_def_base = base.LookupStruct(qualified_name);
if (!struct_def_base) continue;
for (auto fit = struct_def.fields.vec.begin();
fit != struct_def.fields.vec.end(); ++fit) {
auto &field = **fit;
auto field_base = struct_def_base->fields.Lookup(field.name);
if (field_base) {
if (field.value.offset != field_base->value.offset)
return "offsets differ for field: " + field.name;
if (field.value.constant != field_base->value.constant)
return "defaults differ for field: " + field.name;
if (!EqualByName(field.value.type, field_base->value.type))
return "types differ for field: " + field.name;
} else {
// Doesn't have to exist, deleting fields is fine.
// But we should check if there is a field that has the same offset
// but is incompatible (in the case of field renaming).
for (auto fbit = struct_def_base->fields.vec.begin();
fbit != struct_def_base->fields.vec.end(); ++fbit) {
field_base = *fbit;
if (field.value.offset == field_base->value.offset) {
if (!EqualByName(field.value.type, field_base->value.type))
return "field renamed to different type: " + field.name;
break;
}
}
}
}
}
for (auto eit = enums_.vec.begin(); eit != enums_.vec.end(); ++eit) {
auto &enum_def = **eit;
auto qualified_name =
enum_def.defined_namespace->GetFullyQualifiedName(enum_def.name);
auto enum_def_base = base.enums_.Lookup(qualified_name);
if (!enum_def_base) continue;
for (auto evit = enum_def.Vals().begin(); evit != enum_def.Vals().end();
++evit) {
auto &enum_val = **evit;
auto enum_val_base = enum_def_base->Lookup(enum_val.name);
if (enum_val_base) {
if (enum_val != *enum_val_base)
return "values differ for enum: " + enum_val.name;
}
}
}
return "";
}
} // namespace flatbuffers
| 1 | 16,274 | Why was this removed? | google-flatbuffers | java |
@@ -20,5 +20,12 @@ namespace Microsoft.CodeAnalysis.Sarif.SarifValidator
HelpText = "Path of the SARIF file to validate",
Required = true)]
public string InstanceFilePath { get; set; }
+
+ [Option(
+ 'l',
+ "log-file-path",
+ HelpText = "Path to SARIF log file containing the results of the validation",
+ Default = "sarif.log")]
+ public string LogFilePath { get; set; }
}
} | 1 | // Copyright (c) Microsoft. All rights reserved. Licensed under the MIT
// license. See LICENSE file in the project root for full license information.
using CommandLine;
namespace Microsoft.CodeAnalysis.Sarif.SarifValidator
{
internal class Options
{
[Option(
's',
"schema-file-path",
HelpText = "Path of the SARIF JSON schema file",
Default = "Sarif.schema.json")]
public string SchemaFilePath { get; set; }
[Option(
'i',
"instance-file-path",
HelpText = "Path of the SARIF file to validate",
Required = true)]
public string InstanceFilePath { get; set; }
}
}
| 1 | 10,099 | I would prefer that this tool follow the driver framework conventions, which use OutputFilePath as an argument, take a look at AnalyzeCommandBase. You can propose changes to that if you'd like, but binskim, sqlskim, this tool should all conform (in the interests of building an eco-system with consistent command-line interface) | microsoft-sarif-sdk | .cs |
@@ -308,6 +308,18 @@ public final class Queue<T> extends AbstractQueue<T, Queue<T>> implements Linear
return io.vavr.collection.Collections.fill(n, s, empty(), Queue::of);
}
+ /**
+ * Returns a Queue containing {@code n} times the given {@code element}
+ *
+ * @param <T> Component type of the Queue
+ * @param n The number of elements in the Queue
+ * @param element The element
+ * @return An Queue of size {@code n}, where each element is the given {@code element}.
+ */
+ public static <T> Queue<T> fill(int n, T element) {
+ return io.vavr.collection.Collections.fillObject(n, element, empty(), Queue::of);
+ }
+
public static Queue<Character> range(char from, char toExclusive) {
return ofAll(Iterator.range(from, toExclusive));
} | 1 | /* __ __ __ __ __ ___
* \ \ / / \ \ / / __/
* \ \/ / /\ \ \/ / /
* \____/__/ \__\____/__/
*
* Copyright 2014-2018 Vavr, http://vavr.io
*
* 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 io.vavr.collection;
import io.vavr.*;
import io.vavr.control.Option;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;
import static io.vavr.collection.JavaConverters.ChangePolicy.IMMUTABLE;
import static io.vavr.collection.JavaConverters.ChangePolicy.MUTABLE;
/**
* An immutable {@code Queue} stores elements allowing a first-in-first-out (FIFO) retrieval.
* <p>
* Queue API:
*
* <ul>
* <li>{@link #dequeue()}</li>
* <li>{@link #dequeueOption()}</li>
* <li>{@link #enqueue(Object)}</li>
* <li>{@link #enqueue(Object[])}</li>
* <li>{@link #enqueueAll(Iterable)}</li>
* <li>{@link #peek()}</li>
* <li>{@link #peekOption()}</li>
* </ul>
*
* A Queue internally consists of a front List containing the front elements of the Queue in the correct order and a
* rear List containing the rear elements of the Queue in reverse order.
* <p>
* When the front list is empty, front and rear are swapped and rear is reversed. This implies the following queue
* invariant: {@code front.isEmpty() => rear.isEmpty()}.
* <p>
* See Okasaki, Chris: <em>Purely Functional Data Structures</em> (p. 42 ff.). Cambridge, 2003.
*
* @param <T> Component type of the Queue
* @author Daniel Dietrich
*/
public final class Queue<T> extends AbstractQueue<T, Queue<T>> implements LinearSeq<T> {
private static final long serialVersionUID = 1L;
private static final Queue<?> EMPTY = new Queue<>(io.vavr.collection.List.empty(), io.vavr.collection.List.empty());
private final io.vavr.collection.List<T> front;
private final io.vavr.collection.List<T> rear;
/**
* Creates a Queue consisting of a front List and a rear List.
* <p>
* For a {@code Queue(front, rear)} the following invariant holds: {@code Queue is empty <=> front is empty}.
* In other words: If the Queue is not empty, the front List contains at least one element.
*
* @param front A List of front elements, in correct order.
* @param rear A List of rear elements, in reverse order.
*/
private Queue(io.vavr.collection.List<T> front, io.vavr.collection.List<T> rear) {
final boolean frontIsEmpty = front.isEmpty();
this.front = frontIsEmpty ? rear.reverse() : front;
this.rear = frontIsEmpty ? front : rear;
}
/**
* Returns a {@link java.util.stream.Collector} which may be used in conjunction with
* {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link Queue}
* .
*
* @param <T> Component type of the Queue.
* @return A io.vavr.collection.Queue Collector.
*/
public static <T> Collector<T, ArrayList<T>, Queue<T>> collector() {
final Supplier<ArrayList<T>> supplier = ArrayList::new;
final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
left.addAll(right);
return left;
};
final Function<ArrayList<T>, Queue<T>> finisher = Queue::ofAll;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns the empty Queue.
*
* @param <T> Component type
* @return The empty Queue.
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> empty() {
return (Queue<T>) EMPTY;
}
/**
* Narrows a widened {@code Queue<? extends T>} to {@code Queue<T>}
* by performing a type-safe cast. This is eligible because immutable/read-only
* collections are covariant.
*
* @param queue An {@code Queue}.
* @param <T> Component type of the {@code Queue}.
* @return the given {@code queue} instance as narrowed type {@code Queue<T>}.
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> narrow(Queue<? extends T> queue) {
return (Queue<T>) queue;
}
/**
* Returns a singleton {@code Queue}, i.e. a {@code Queue} of one element.
*
* @param element An element.
* @param <T> The component type
* @return A new Queue instance containing the given element
*/
public static <T> Queue<T> of(T element) {
return ofAll(io.vavr.collection.List.of(element));
}
/**
* Creates a Queue of the given elements.
*
* @param <T> Component type of the Queue.
* @param elements Zero or more elements.
* @return A queue containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("varargs")
@SafeVarargs
public static <T> Queue<T> of(T... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.of(elements));
}
/**
* Creates a Queue of the given elements.
*
* @param <T> Component type of the Queue.
* @param elements An Iterable of elements.
* @return A queue containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> ofAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (elements instanceof Queue) {
return (Queue<T>) elements;
} else if (!elements.iterator().hasNext()) {
return empty();
} else if (elements instanceof io.vavr.collection.List) {
return new Queue<>((io.vavr.collection.List<T>) elements, io.vavr.collection.List.empty());
} else {
return new Queue<>(io.vavr.collection.List.ofAll(elements), io.vavr.collection.List.empty());
}
}
/**
* Creates a Queue that contains the elements of the given {@link java.util.stream.Stream}.
*
* @param javaStream A {@link java.util.stream.Stream}
* @param <T> Component type of the Stream.
* @return A Queue containing the given elements in the same order.
*/
public static <T> Queue<T> ofAll(java.util.stream.Stream<? extends T> javaStream) {
Objects.requireNonNull(javaStream, "javaStream is null");
return new Queue<>(io.vavr.collection.List.ofAll(javaStream), io.vavr.collection.List.empty());
}
/**
* Creates a Queue from boolean values.
*
* @param elements boolean values
* @return A new Queue of Boolean values
* @throws NullPointerException if elements is null
*/
public static Queue<Boolean> ofAll(boolean... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from byte values.
*
* @param elements byte values
* @return A new Queue of Byte values
* @throws NullPointerException if elements is null
*/
public static Queue<Byte> ofAll(byte... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from char values.
*
* @param elements char values
* @return A new Queue of Character values
* @throws NullPointerException if elements is null
*/
public static Queue<Character> ofAll(char... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from double values.
*
* @param elements double values
* @return A new Queue of Double values
* @throws NullPointerException if elements is null
*/
public static Queue<Double> ofAll(double... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from float values.
*
* @param elements float values
* @return A new Queue of Float values
* @throws NullPointerException if elements is null
*/
public static Queue<Float> ofAll(float... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from int values.
*
* @param elements int values
* @return A new Queue of Integer values
* @throws NullPointerException if elements is null
*/
public static Queue<Integer> ofAll(int... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from long values.
*
* @param elements long values
* @return A new Queue of Long values
* @throws NullPointerException if elements is null
*/
public static Queue<Long> ofAll(long... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Creates a Queue from short values.
*
* @param elements short values
* @return A new Queue of Short values
* @throws NullPointerException if elements is null
*/
public static Queue<Short> ofAll(short... elements) {
Objects.requireNonNull(elements, "elements is null");
return ofAll(io.vavr.collection.List.ofAll(elements));
}
/**
* Returns a Queue containing {@code n} values of a given Function {@code f}
* over a range of integer values from 0 to {@code n - 1}.
*
* @param <T> Component type of the Queue
* @param n The number of elements in the Queue
* @param f The Function computing element values
* @return A Queue consisting of elements {@code f(0),f(1), ..., f(n - 1)}
* @throws NullPointerException if {@code f} is null
*/
public static <T> Queue<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
Objects.requireNonNull(f, "f is null");
return io.vavr.collection.Collections.tabulate(n, f, empty(), Queue::of);
}
/**
* Returns a Queue containing {@code n} values supplied by a given Supplier {@code s}.
*
* @param <T> Component type of the Queue
* @param n The number of elements in the Queue
* @param s The Supplier computing element values
* @return An Queue of size {@code n}, where each element contains the result supplied by {@code s}.
* @throws NullPointerException if {@code s} is null
*/
public static <T> Queue<T> fill(int n, Supplier<? extends T> s) {
Objects.requireNonNull(s, "s is null");
return io.vavr.collection.Collections.fill(n, s, empty(), Queue::of);
}
public static Queue<Character> range(char from, char toExclusive) {
return ofAll(Iterator.range(from, toExclusive));
}
public static Queue<Character> rangeBy(char from, char toExclusive, int step) {
return ofAll(Iterator.rangeBy(from, toExclusive, step));
}
@GwtIncompatible
public static Queue<Double> rangeBy(double from, double toExclusive, double step) {
return ofAll(Iterator.rangeBy(from, toExclusive, step));
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.range(0, 0) // = Queue()
* Queue.range(2, 0) // = Queue()
* Queue.range(-2, 2) // = Queue(-2, -1, 0, 1)
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @return a range of int values as specified or {@code Nil} if {@code from >= toExclusive}
*/
public static Queue<Integer> range(int from, int toExclusive) {
return ofAll(Iterator.range(from, toExclusive));
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.rangeBy(1, 3, 1) // = Queue(1, 2)
* Queue.rangeBy(1, 4, 2) // = Queue(1, 3)
* Queue.rangeBy(4, 1, -2) // = Queue(4, 2)
* Queue.rangeBy(4, 1, 2) // = Queue()
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @param step the step
* @return a range of long values as specified or {@code Nil} if<br>
* {@code from >= toInclusive} and {@code step > 0} or<br>
* {@code from <= toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
public static Queue<Integer> rangeBy(int from, int toExclusive, int step) {
return ofAll(Iterator.rangeBy(from, toExclusive, step));
}
/**
* Creates a Queue of long numbers starting from {@code from}, extending to {@code toExclusive - 1}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.range(0L, 0L) // = Queue()
* Queue.range(2L, 0L) // = Queue()
* Queue.range(-2L, 2L) // = Queue(-2L, -1L, 0L, 1L)
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @return a range of long values as specified or {@code Nil} if {@code from >= toExclusive}
*/
public static Queue<Long> range(long from, long toExclusive) {
return ofAll(Iterator.range(from, toExclusive));
}
/**
* Creates a Queue of long numbers starting from {@code from}, extending to {@code toExclusive - 1},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.rangeBy(1L, 3L, 1L) // = Queue(1L, 2L)
* Queue.rangeBy(1L, 4L, 2L) // = Queue(1L, 3L)
* Queue.rangeBy(4L, 1L, -2L) // = Queue(4L, 2L)
* Queue.rangeBy(4L, 1L, 2L) // = Queue()
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @param step the step
* @return a range of long values as specified or {@code Nil} if<br>
* {@code from >= toInclusive} and {@code step > 0} or<br>
* {@code from <= toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
public static Queue<Long> rangeBy(long from, long toExclusive, long step) {
return ofAll(Iterator.rangeBy(from, toExclusive, step));
}
public static Queue<Character> rangeClosed(char from, char toInclusive) {
return ofAll(Iterator.rangeClosed(from, toInclusive));
}
public static Queue<Character> rangeClosedBy(char from, char toInclusive, int step) {
return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
}
@GwtIncompatible
public static Queue<Double> rangeClosedBy(double from, double toInclusive, double step) {
return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.rangeClosed(0, 0) // = Queue(0)
* Queue.rangeClosed(2, 0) // = Queue()
* Queue.rangeClosed(-2, 2) // = Queue(-2, -1, 0, 1, 2)
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @return a range of int values as specified or {@code Nil} if {@code from > toInclusive}
*/
public static Queue<Integer> rangeClosed(int from, int toInclusive) {
return ofAll(Iterator.rangeClosed(from, toInclusive));
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.rangeClosedBy(1, 3, 1) // = Queue(1, 2, 3)
* Queue.rangeClosedBy(1, 4, 2) // = Queue(1, 3)
* Queue.rangeClosedBy(4, 1, -2) // = Queue(4, 2)
* Queue.rangeClosedBy(4, 1, 2) // = Queue()
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @param step the step
* @return a range of int values as specified or {@code Nil} if<br>
* {@code from > toInclusive} and {@code step > 0} or<br>
* {@code from < toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
public static Queue<Integer> rangeClosedBy(int from, int toInclusive, int step) {
return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
}
/**
* Creates a Queue of long numbers starting from {@code from}, extending to {@code toInclusive}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.rangeClosed(0L, 0L) // = Queue(0L)
* Queue.rangeClosed(2L, 0L) // = Queue()
* Queue.rangeClosed(-2L, 2L) // = Queue(-2L, -1L, 0L, 1L, 2L)
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @return a range of long values as specified or {@code Nil} if {@code from > toInclusive}
*/
public static Queue<Long> rangeClosed(long from, long toInclusive) {
return ofAll(Iterator.rangeClosed(from, toInclusive));
}
/**
* Transposes the rows and columns of a {@link Queue} matrix.
*
* @param <T> matrix element type
* @param matrix to be transposed.
* @return a transposed {@link Queue} matrix.
* @throws IllegalArgumentException if the row lengths of {@code matrix} differ.
*
* <p>
* ex: {@code
* Queue.transpose(Queue(Queue(1,2,3), Queue(4,5,6))) → Queue(Queue(1,4), Queue(2,5), Queue(3,6))
* }
*/
public static <T> Queue<Queue<T>> transpose(Queue<Queue<T>> matrix) {
return io.vavr.collection.Collections.transpose(matrix, Queue::ofAll, Queue::of);
}
/**
* Creates a Queue of long numbers starting from {@code from}, extending to {@code toInclusive},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Queue.rangeClosedBy(1L, 3L, 1L) // = Queue(1L, 2L, 3L)
* Queue.rangeClosedBy(1L, 4L, 2L) // = Queue(1L, 3L)
* Queue.rangeClosedBy(4L, 1L, -2L) // = Queue(4L, 2L)
* Queue.rangeClosedBy(4L, 1L, 2L) // = Queue()
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @param step the step
* @return a range of int values as specified or {@code Nil} if<br>
* {@code from > toInclusive} and {@code step > 0} or<br>
* {@code from < toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
public static Queue<Long> rangeClosedBy(long from, long toInclusive, long step) {
return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
}
/**
* Creates a Queue from a seed value and a function.
* The function takes the seed at first.
* The function should return {@code None} when it's
* done generating the Queue, otherwise {@code Some} {@code Tuple}
* of the element for the next call and the value to add to the
* resulting Queue.
* <p>
* Example:
* <pre>
* <code>
* Queue.unfoldRight(10, x -> x == 0
* ? Option.none()
* : Option.of(new Tuple2<>(x, x-1)));
* // Queue(10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
* </code>
* </pre>
*
* @param <T> type of seeds
* @param <U> type of unfolded values
* @param seed the start value for the iteration
* @param f the function to get the next step of the iteration
* @return a Queue with the values built up by the iteration
* @throws NullPointerException if {@code f} is null
*/
public static <T, U> Queue<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) {
return Iterator.unfoldRight(seed, f).toQueue();
}
/**
* Creates a Queue from a seed value and a function.
* The function takes the seed at first.
* The function should return {@code None} when it's
* done generating the Queue, otherwise {@code Some} {@code Tuple}
* of the value to add to the resulting Queue and
* the element for the next call.
* <p>
* Example:
* <pre>
* <code>
* Queue.unfoldLeft(10, x -> x == 0
* ? Option.none()
* : Option.of(new Tuple2<>(x-1, x)));
* // Queue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
* </code>
* </pre>
*
* @param <T> type of seeds
* @param <U> type of unfolded values
* @param seed the start value for the iteration
* @param f the function to get the next step of the iteration
* @return a Queue with the values built up by the iteration
* @throws NullPointerException if {@code f} is null
*/
public static <T, U> Queue<U> unfoldLeft(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends U>>> f) {
return Iterator.unfoldLeft(seed, f).toQueue();
}
/**
* Creates a Queue from a seed value and a function.
* The function takes the seed at first.
* The function should return {@code None} when it's
* done generating the Queue, otherwise {@code Some} {@code Tuple}
* of the value to add to the resulting Queue and
* the element for the next call.
* <p>
* Example:
* <pre>
* <code>
* Queue.unfold(10, x -> x == 0
* ? Option.none()
* : Option.of(new Tuple2<>(x-1, x)));
* // Queue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
* </code>
* </pre>
*
* @param <T> type of seeds and unfolded values
* @param seed the start value for the iteration
* @param f the function to get the next step of the iteration
* @return a Queue with the values built up by the iteration
* @throws NullPointerException if {@code f} is null
*/
public static <T> Queue<T> unfold(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends T>>> f) {
return Iterator.unfold(seed, f).toQueue();
}
/**
* Enqueues a new element.
*
* @param element The new element
* @return a new {@code Queue} instance, containing the new element
*/
@Override
public Queue<T> enqueue(T element) {
return new Queue<>(front, rear.prepend(element));
}
/**
* Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is
* the first which will be retrieved.
*
* @param elements An Iterable of elements, may be empty
* @return a new {@code Queue} instance, containing the new elements
* @throws NullPointerException if elements is null
*/
@SuppressWarnings("unchecked")
public Queue<T> enqueueAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (isEmpty() && elements instanceof Queue) {
return (Queue<T>) elements;
} else {
return io.vavr.collection.List.ofAll(elements).foldLeft(this, Queue::enqueue);
}
}
// -- Adjusted return types of Seq methods
@Override
public Queue<T> append(T element) {
return enqueue(element);
}
@Override
public Queue<T> appendAll(Iterable<? extends T> elements) {
return enqueueAll(elements);
}
@GwtIncompatible
@Override
public java.util.List<T> asJava() {
return JavaConverters.asJava(this, IMMUTABLE);
}
@GwtIncompatible
@Override
public Queue<T> asJava(Consumer<? super java.util.List<T>> action) {
return Collections.asJava(this, action, IMMUTABLE);
}
@GwtIncompatible
@Override
public java.util.List<T> asJavaMutable() {
return JavaConverters.asJava(this, MUTABLE);
}
@GwtIncompatible
@Override
public Queue<T> asJavaMutable(Consumer<? super java.util.List<T>> action) {
return Collections.asJava(this, action, MUTABLE);
}
@Override
public <R> Queue<R> collect(PartialFunction<? super T, ? extends R> partialFunction) {
return ofAll(iterator().<R> collect(partialFunction));
}
@Override
public Queue<Queue<T>> combinations() {
return ofAll(toList().combinations().map(Queue::ofAll));
}
@Override
public Queue<Queue<T>> combinations(int k) {
return ofAll(toList().combinations(k).map(Queue::ofAll));
}
@Override
public Iterator<Queue<T>> crossProduct(int power) {
return io.vavr.collection.Collections.crossProduct(empty(), this, power);
}
@Override
public Queue<T> distinct() {
return ofAll(toList().distinct());
}
@Override
public Queue<T> distinctBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
return ofAll(toList().distinctBy(comparator));
}
@Override
public <U> Queue<T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor is null");
return ofAll(toList().distinctBy(keyExtractor));
}
@Override
public Queue<T> drop(int n) {
if (n <= 0) {
return this;
}
if (n >= length()) {
return empty();
}
return new Queue<>(front.drop(n), rear.dropRight(n - front.length()));
}
@Override
public Queue<T> dropWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final List<T> dropped = toList().dropWhile(predicate);
return ofAll(dropped.length() == length() ? this : dropped);
}
@Override
public Queue<T> dropRight(int n) {
if (n <= 0) {
return this;
}
if (n >= length()) {
return empty();
}
return new Queue<>(front.dropRight(n - rear.length()), rear.drop(n));
}
@Override
public Queue<T> dropRightUntil(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return reverse().dropUntil(predicate).reverse();
}
@Override
public Queue<T> dropRightWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return dropRightUntil(predicate.negate());
}
@Override
public Queue<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final io.vavr.collection.List<T> filtered = toList().filter(predicate);
if (filtered.isEmpty()) {
return empty();
} else if (filtered.length() == length()) {
return this;
} else {
return ofAll(filtered);
}
}
@Override
public <U> Queue<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
if (isEmpty()) {
return empty();
} else {
return new Queue<>(front.flatMap(mapper), rear.flatMap(mapper));
}
}
@Override
public T get(int index) {
if (isEmpty()) {
throw new IndexOutOfBoundsException("get(" + index + ") on empty Queue");
}
if (index < 0) {
throw new IndexOutOfBoundsException("get(" + index + ")");
}
final int length = front.length();
if (index < length) {
return front.get(index);
} else {
final int rearIndex = index - length;
final int rearLength = rear.length();
if (rearIndex < rearLength) {
final int reverseRearIndex = rearLength - rearIndex - 1;
return rear.get(reverseRearIndex);
} else {
throw new IndexOutOfBoundsException("get(" + index + ") on Queue of length " + length());
}
}
}
@Override
public <C> Map<C, Queue<T>> groupBy(Function<? super T, ? extends C> classifier) {
return io.vavr.collection.Collections.groupBy(this, classifier, Queue::ofAll);
}
@Override
public Iterator<Queue<T>> grouped(int size) {
return sliding(size, size);
}
@Override
public boolean hasDefiniteSize() {
return true;
}
@Override
public T head() {
if (isEmpty()) {
throw new NoSuchElementException("head of empty " + stringPrefix());
} else {
return front.head();
}
}
@Override
public int indexOf(T element, int from) {
final int frontIndex = front.indexOf(element, from);
if (frontIndex != -1) {
return frontIndex;
} else {
// we need to reverse because we search the first occurrence
final int rearIndex = rear.reverse().indexOf(element, from - front.length());
return (rearIndex == -1) ? -1 : rearIndex + front.length();
}
}
@Override
public Queue<T> init() {
if (isEmpty()) {
throw new UnsupportedOperationException("init of empty " + stringPrefix());
} else if (rear.isEmpty()) {
return new Queue<>(front.init(), rear);
} else {
return new Queue<>(front, rear.tail());
}
}
@Override
public Queue<T> insert(int index, T element) {
if (index < 0) {
throw new IndexOutOfBoundsException("insert(" + index + ", element)");
}
final int length = front.length();
if (index <= length) {
return new Queue<>(front.insert(index, element), rear);
} else {
final int rearIndex = index - length;
final int rearLength = rear.length();
if (rearIndex <= rearLength) {
final int reverseRearIndex = rearLength - rearIndex;
return new Queue<>(front, rear.insert(reverseRearIndex, element));
} else {
throw new IndexOutOfBoundsException("insert(" + index + ", element) on Queue of length " + length());
}
}
}
@SuppressWarnings("unchecked")
@Override
public Queue<T> insertAll(int index, Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (index < 0) {
throw new IndexOutOfBoundsException("insertAll(" + index + ", elements)");
}
final int length = front.length();
if (index <= length) {
if (isEmpty() && elements instanceof Queue) {
return (Queue<T>) elements;
} else {
final io.vavr.collection.List<T> newFront = front.insertAll(index, elements);
return (newFront == front) ? this : new Queue<>(newFront, rear);
}
} else {
final int rearIndex = index - length;
final int rearLength = rear.length();
if (rearIndex <= rearLength) {
final int reverseRearIndex = rearLength - rearIndex;
final io.vavr.collection.List<T> newRear = rear.insertAll(reverseRearIndex, io.vavr.collection.List.ofAll(elements).reverse());
return (newRear == rear) ? this : new Queue<>(front, newRear);
} else {
throw new IndexOutOfBoundsException("insertAll(" + index + ", elements) on Queue of length " + length());
}
}
}
@Override
public Queue<T> intersperse(T element) {
if (isEmpty()) {
return this;
} else if (rear.isEmpty()) {
return new Queue<>(front.intersperse(element), rear);
} else {
return new Queue<>(front.intersperse(element), rear.intersperse(element).append(element));
}
}
/**
* A {@code Queue} is computed synchronously.
*
* @return false
*/
@Override
public boolean isAsync() {
return false;
}
@Override
public boolean isEmpty() {
return front.isEmpty();
}
/**
* A {@code Queue} is computed eagerly.
*
* @return false
*/
@Override
public boolean isLazy() {
return false;
}
@Override
public boolean isTraversableAgain() {
return true;
}
@Override
public T last() {
return rear.isEmpty() ? front.last() : rear.head();
}
@Override
public int lastIndexOf(T element, int end) {
return toList().lastIndexOf(element, end);
}
@Override
public int length() {
return front.length() + rear.length();
}
@Override
public <U> Queue<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return new Queue<>(front.map(mapper), rear.map(mapper));
}
@Override
public Queue<T> orElse(Iterable<? extends T> other) {
return isEmpty() ? ofAll(other) : this;
}
@Override
public Queue<T> orElse(Supplier<? extends Iterable<? extends T>> supplier) {
return isEmpty() ? ofAll(supplier.get()) : this;
}
@Override
public Queue<T> padTo(int length, T element) {
final int actualLength = length();
if (length <= actualLength) {
return this;
} else {
return ofAll(toList().padTo(length, element));
}
}
@Override
public Queue<T> leftPadTo(int length, T element) {
final int actualLength = length();
if (length <= actualLength) {
return this;
} else {
return ofAll(toList().leftPadTo(length, element));
}
}
@Override
public Queue<T> patch(int from, Iterable<? extends T> that, int replaced) {
from = from < 0 ? 0 : from;
replaced = replaced < 0 ? 0 : replaced;
Queue<T> result = take(from).appendAll(that);
from += replaced;
result = result.appendAll(drop(from));
return result;
}
@Override
public Tuple2<Queue<T>, Queue<T>> partition(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return toList().partition(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public Queue<Queue<T>> permutations() {
return ofAll(toList().permutations().map(io.vavr.collection.List::toQueue));
}
@Override
public Queue<T> prepend(T element) {
return new Queue<>(front.prepend(element), rear);
}
@SuppressWarnings("unchecked")
@Override
public Queue<T> prependAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (isEmpty() && elements instanceof Queue) {
return (Queue<T>) elements;
} else {
final io.vavr.collection.List<T> newFront = front.prependAll(elements);
return (newFront == front) ? this : new Queue<>(newFront, rear);
}
}
@Override
public Queue<T> remove(T element) {
final io.vavr.collection.List<T> removed = toList().remove(element);
return ofAll(removed.length() == length() ? this : removed);
}
@Override
public Queue<T> removeFirst(Predicate<T> predicate) {
final io.vavr.collection.List<T> removed = toList().removeFirst(predicate);
return ofAll(removed.length() == length() ? this : removed);
}
@Override
public Queue<T> removeLast(Predicate<T> predicate) {
final io.vavr.collection.List<T> removed = toList().removeLast(predicate);
return ofAll(removed.length() == length() ? this : removed);
}
@Override
public Queue<T> removeAt(int index) {
return ofAll(toList().removeAt(index));
}
@Override
public Queue<T> removeAll(T element) {
return io.vavr.collection.Collections.removeAll(this, element);
}
@Override
public Queue<T> replace(T currentElement, T newElement) {
final io.vavr.collection.List<T> newFront = front.replace(currentElement, newElement);
final io.vavr.collection.List<T> newRear = rear.replace(currentElement, newElement);
return newFront.size() + newRear.size() == 0 ? empty()
: newFront == front && newRear == rear ? this
: new Queue<>(newFront, newRear);
}
@Override
public Queue<T> replaceAll(T currentElement, T newElement) {
final io.vavr.collection.List<T> newFront = front.replaceAll(currentElement, newElement);
final io.vavr.collection.List<T> newRear = rear.replaceAll(currentElement, newElement);
return newFront.size() + newRear.size() == 0 ? empty()
: newFront == front && newRear == rear ? this
: new Queue<>(newFront, newRear);
}
@Override
public Queue<T> reverse() {
return isEmpty() ? this : ofAll(toList().reverse());
}
@Override
public Queue<T> rotateLeft(int n) {
return Collections.rotateLeft(this, n);
}
@Override
public Queue<T> rotateRight(int n) {
return Collections.rotateRight(this, n);
}
@Override
public Queue<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) {
return scanLeft(zero, operation);
}
@Override
public <U> Queue<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) {
return io.vavr.collection.Collections.scanLeft(this, zero, operation, Iterator::toQueue);
}
@Override
public <U> Queue<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
return io.vavr.collection.Collections.scanRight(this, zero, operation, Iterator::toQueue);
}
@Override
public Queue<T> shuffle() {
return io.vavr.collection.Collections.shuffle(this, Queue::ofAll);
}
@Override
public Queue<T> slice(int beginIndex, int endIndex) {
return ofAll(toList().slice(beginIndex, endIndex));
}
@Override
public Iterator<Queue<T>> slideBy(Function<? super T, ?> classifier) {
return iterator().slideBy(classifier).map(Queue::ofAll);
}
@Override
public Iterator<Queue<T>> sliding(int size) {
return sliding(size, 1);
}
@Override
public Iterator<Queue<T>> sliding(int size, int step) {
return iterator().sliding(size, step).map(Queue::ofAll);
}
@Override
public Queue<T> sorted() {
return ofAll(toList().sorted());
}
@Override
public Queue<T> sorted(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
return ofAll(toList().sorted(comparator));
}
@Override
public <U extends Comparable<? super U>> Queue<T> sortBy(Function<? super T, ? extends U> mapper) {
return sortBy(U::compareTo, mapper);
}
@Override
public <U> Queue<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) {
return Collections.sortBy(this, comparator, mapper, collector());
}
@Override
public Tuple2<Queue<T>, Queue<T>> span(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return toList().span(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public Tuple2<Queue<T>, Queue<T>> splitAt(int n) {
return toList().splitAt(n).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public Tuple2<Queue<T>, Queue<T>> splitAt(Predicate<? super T> predicate) {
return toList().splitAt(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public Tuple2<Queue<T>, Queue<T>> splitAtInclusive(Predicate<? super T> predicate) {
return toList().splitAtInclusive(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public boolean startsWith(Iterable<? extends T> that, int offset) {
return toList().startsWith(that, offset);
}
@Override
public Queue<T> subSequence(int beginIndex) {
if (beginIndex < 0 || beginIndex > length()) {
throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ")");
} else {
return drop(beginIndex);
}
}
@Override
public Queue<T> subSequence(int beginIndex, int endIndex) {
Collections.subSequenceRangeCheck(beginIndex, endIndex, length());
if (beginIndex == endIndex) {
return empty();
} else if (beginIndex == 0 && endIndex == length()) {
return this;
} else {
return ofAll(toList().subSequence(beginIndex, endIndex));
}
}
@Override
public Queue<T> tail() {
if (isEmpty()) {
throw new UnsupportedOperationException("tail of empty " + stringPrefix());
} else {
return new Queue<>(front.tail(), rear);
}
}
@Override
public Queue<T> take(int n) {
if (n <= 0) {
return empty();
}
if (n >= length()) {
return this;
}
final int frontLength = front.length();
if (n < frontLength) {
return new Queue<>(front.take(n), io.vavr.collection.List.empty());
} else if (n == frontLength) {
return new Queue<>(front, io.vavr.collection.List.empty());
} else {
return new Queue<>(front, rear.takeRight(n - frontLength));
}
}
@Override
public Queue<T> takeUntil(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final io.vavr.collection.List<T> taken = toList().takeUntil(predicate);
return taken.length() == length() ? this : ofAll(taken);
}
@Override
public Queue<T> takeRight(int n) {
if (n <= 0) {
return empty();
}
if (n >= length()) {
return this;
}
final int rearLength = rear.length();
if (n < rearLength) {
return new Queue<>(rear.take(n).reverse(), io.vavr.collection.List.empty());
} else if (n == rearLength) {
return new Queue<>(rear.reverse(), io.vavr.collection.List.empty());
} else {
return new Queue<>(front.takeRight(n - rearLength), rear);
}
}
@Override
public Queue<T> takeRightUntil(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final io.vavr.collection.List<T> taken = toList().takeRightUntil(predicate);
return taken.length() == length() ? this : ofAll(taken);
}
@Override
public Queue<T> takeRightWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return takeRightUntil(predicate.negate());
}
/**
* Transforms this {@code Queue}.
*
* @param f A transformation
* @param <U> Type of transformation result
* @return An instance of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
public <U> U transform(Function<? super Queue<T>, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return f.apply(this);
}
@Override
public <T1, T2> Tuple2<Queue<T1>, Queue<T2>> unzip(
Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return toList().unzip(unzipper).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public <T1, T2, T3> Tuple3<Queue<T1>, Queue<T2>, Queue<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return toList().unzip3(unzipper).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
}
@Override
public Queue<T> update(int index, T element) {
return ofAll(toList().update(index, element));
}
@Override
public Queue<T> update(int index, Function<? super T, ? extends T> updater) {
Objects.requireNonNull(updater, "updater is null");
return update(index, updater.apply(get(index)));
}
@Override
public <U> Queue<Tuple2<T, U>> zip(Iterable<? extends U> that) {
return zipWith(that, Tuple::of);
}
@SuppressWarnings("unchecked")
@Override
public <U, R> Queue<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) {
Objects.requireNonNull(that, "that is null");
Objects.requireNonNull(mapper, "mapper is null");
return ofAll(toList().zipWith(that, mapper));
}
@Override
public <U> Queue<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) {
Objects.requireNonNull(that, "that is null");
return ofAll(toList().zipAll(that, thisElem, thatElem));
}
@Override
public Queue<Tuple2<T, Integer>> zipWithIndex() {
return zipWithIndex(Tuple::of);
}
@Override
public <U> Queue<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return ofAll(toList().zipWithIndex(mapper));
}
private Object readResolve() {
return isEmpty() ? EMPTY : this;
}
@Override
public String stringPrefix() {
return "Queue";
}
@Override
public boolean equals(Object o) {
return io.vavr.collection.Collections.equals(this, o);
}
@Override
public int hashCode() {
return io.vavr.collection.Collections.hashOrdered(this);
}
}
| 1 | 12,931 | (...), where each element ~are~ **is the** given {@code element}. | vavr-io-vavr | java |
@@ -57,7 +57,7 @@ namespace Examples.AspNetCore
switch (exporter)
{
case "jaeger":
- services.AddOpenTelemetryTracerProvider((builder) => builder
+ services.AddOpenTelemetryTracing((builder) => builder
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddJaegerExporter(jaegerOptions => | 1 | // <copyright file="Startup.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.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using OpenTelemetry.Trace;
namespace Examples.AspNetCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
c.IncludeXmlComments(xmlPath);
}
});
// Switch between Zipkin/Jaeger by setting UseExporter in appsettings.json.
var exporter = this.Configuration.GetValue<string>("UseExporter").ToLowerInvariant();
switch (exporter)
{
case "jaeger":
services.AddOpenTelemetryTracerProvider((builder) => builder
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddJaegerExporter(jaegerOptions =>
{
jaegerOptions.ServiceName = this.Configuration.GetValue<string>("Jaeger:ServiceName");
jaegerOptions.AgentHost = this.Configuration.GetValue<string>("Jaeger:Host");
jaegerOptions.AgentPort = this.Configuration.GetValue<int>("Jaeger:Port");
}));
break;
case "zipkin":
services.AddOpenTelemetryTracerProvider((builder) => builder
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddZipkinExporter(zipkinOptions =>
{
zipkinOptions.ServiceName = this.Configuration.GetValue<string>("Zipkin:ServiceName");
zipkinOptions.Endpoint = new Uri(this.Configuration.GetValue<string>("Zipkin:Endpoint"));
}));
break;
default:
services.AddOpenTelemetryTracerProvider((builder) => builder
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddConsoleExporter());
break;
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 1 | 16,912 | What if `AddOpenTelemetryTracing` is called multiple times? | open-telemetry-opentelemetry-dotnet | .cs |
@@ -16,9 +16,10 @@ FileBasedWalIterator::FileBasedWalIterator(
std::shared_ptr<FileBasedWal> wal,
LogID startId,
LogID lastId)
- : wal_(std::move(wal))
+ : wal_(wal)
, currId_(startId) {
- if (lastId >= 0) {
+ holder_ = std::make_unique<folly::RWSpinLock::ReadHolder>(wal_->rollbackLock_);
+ if (lastId >= 0 && lastId <= wal_->lastLogId()) {
lastId_ = lastId;
} else {
lastId_ = wal_->lastLogId(); | 1 | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "base/Base.h"
#include "kvstore/wal/FileBasedWalIterator.h"
#include "kvstore/wal/FileBasedWal.h"
#include "kvstore/wal/WalFileInfo.h"
namespace nebula {
namespace wal {
FileBasedWalIterator::FileBasedWalIterator(
std::shared_ptr<FileBasedWal> wal,
LogID startId,
LogID lastId)
: wal_(std::move(wal))
, currId_(startId) {
if (lastId >= 0) {
lastId_ = lastId;
} else {
lastId_ = wal_->lastLogId();
}
if (currId_ > lastId_) {
LOG(ERROR) << wal_->idStr_ << "The log " << currId_
<< " is out of range, the lastLogId is " << lastId_;
return;
}
if (startId < wal_->firstLogId()) {
LOG(ERROR) << wal_->idStr_ << "The given log id " << startId
<< " is out of the range, the wal firstLogId is " << wal_->firstLogId();
currId_ = lastId_ + 1;
return;
} else {
// Pick all buffers that match the range [currId_, lastId_]
wal_->accessAllBuffers([this] (BufferPtr buffer) {
if (buffer->empty()) {
// Skip th empty one.
return true;
}
if (lastId_ >= buffer->firstLogId()) {
buffers_.push_front(buffer);
firstIdInBuffer_ = buffer->firstLogId();
}
if (firstIdInBuffer_ <= currId_) {
// Go no futher
currIdx_ = currId_ - firstIdInBuffer_;
currTerm_ = buffers_.front()->getTerm(currIdx_);
nextFirstId_ = getFirstIdInNextBuffer();
return false;
} else {
return true;
}
});
}
if (firstIdInBuffer_ > currId_) {
// We need to read from the WAL files
wal_->accessAllWalInfo([this] (WalFileInfoPtr info) {
if (info->firstId() >= firstIdInBuffer_) {
// Skip this file
return true;
}
int fd = open(info->path(), O_RDONLY);
if (fd < 0) {
LOG(ERROR) << "Failed to open wal file \""
<< info->path()
<< "\" (" << errno << "): "
<< strerror(errno);
currId_ = lastId_ + 1;
return false;
}
fds_.push_front(fd);
idRanges_.push_front(std::make_pair(info->firstId(), info->lastId()));
if (info->firstId() <= currId_) {
// Go no further
return false;
} else {
return true;
}
});
if (idRanges_.empty() || idRanges_.front().first > currId_) {
LOG(ERROR) << "LogID " << currId_
<< " is out of the wal files range";
currId_ = lastId_ + 1;
return;
}
nextFirstId_ = getFirstIdInNextFile();
CHECK_LE(currId_, idRanges_.front().second);
}
if (!idRanges_.empty()) {
// Find the correct position in the first WAL file
currPos_ = 0;
while (true) {
LogID logId;
// Read the logID
int fd = fds_.front();
CHECK_EQ(pread(fd,
reinterpret_cast<char*>(&logId),
sizeof(LogID),
currPos_),
static_cast<ssize_t>(sizeof(LogID)));
// Read the termID
CHECK_EQ(pread(fd,
reinterpret_cast<char*>(&currTerm_),
sizeof(TermID),
currPos_ + sizeof(LogID)),
static_cast<ssize_t>(sizeof(TermID)));
// Read the log length
CHECK_EQ(pread(fd,
reinterpret_cast<char*>(&currMsgLen_),
sizeof(int32_t),
currPos_ + sizeof(LogID) + sizeof(TermID)),
static_cast<ssize_t>(sizeof(int32_t)));
if (logId == currId_) {
break;
}
currPos_ += sizeof(LogID)
+ sizeof(TermID)
+ sizeof(int32_t) * 2
+ currMsgLen_
+ sizeof(ClusterID);
}
}
}
FileBasedWalIterator::~FileBasedWalIterator() {
for (auto& fd : fds_) {
close(fd);
}
}
LogIterator& FileBasedWalIterator::operator++() {
++currId_;
if (currId_ < firstIdInBuffer_) {
// Still in the WAL file
if (currId_ >= nextFirstId_) {
// Need to roll over to next file
VLOG(2) << "Current ID is " << currId_
<< ", and the first ID in the next file is "
<< nextFirstId_
<< ", so need to move to the next file";
// Close the current file
CHECK_EQ(close(fds_.front()), 0);
fds_.pop_front();
idRanges_.pop_front();
if (idRanges_.empty()) {
// Reached the end of wal files, only happens
// when there is no buffer to read
CHECK_EQ(std::numeric_limits<LogID>::max(),
firstIdInBuffer_);
currId_ = lastId_ + 1;
return *this;
}
nextFirstId_ = getFirstIdInNextFile();
CHECK_EQ(currId_, idRanges_.front().first);
currPos_ = 0;
} else {
// Move to the next log
currPos_ += sizeof(LogID)
+ sizeof(TermID)
+ sizeof(int32_t) * 2
+ currMsgLen_
+ sizeof(ClusterID);
}
if (idRanges_.front().second <= 0) {
// empty file
currId_ = lastId_ + 1;
return *this;
} else {
LogID logId;
int fd = fds_.front();
// Read the logID
CHECK_EQ(pread(fd,
reinterpret_cast<char*>(&logId),
sizeof(LogID),
currPos_),
static_cast<ssize_t>(sizeof(LogID))) << "currPos = " << currPos_;
CHECK_EQ(currId_, logId);
// Read the termID
CHECK_EQ(pread(fd,
reinterpret_cast<char*>(&currTerm_),
sizeof(TermID),
currPos_ + sizeof(LogID)),
static_cast<ssize_t>(sizeof(TermID)));
// Read the log length
CHECK_EQ(pread(fd,
reinterpret_cast<char*>(&currMsgLen_),
sizeof(int32_t),
currPos_ + sizeof(TermID) + sizeof(LogID)),
static_cast<ssize_t>(sizeof(int32_t)));
}
} else if (currId_ <= lastId_) {
// Need to adjust nextFirstId_, in case we just start
// reading buffers
if (currId_ == firstIdInBuffer_) {
nextFirstId_ = getFirstIdInNextBuffer();
CHECK_LT(firstIdInBuffer_, nextFirstId_);
currIdx_ = -1;
}
// Read from buffer
if (currId_ >= nextFirstId_) {
// Roll over to next buffer
if (buffers_.size() == 1) {
LOG(FATAL) << wal_->idStr_
<< ", currId_ " << currId_
<< ", nextFirstId_ " << nextFirstId_
<< ", firstIdInBuffer_ " << firstIdInBuffer_
<< ", lastId_ " << lastId_
<< ", firstLogId in buffer " << buffers_.front()->firstLogId()
<< ", lastLogId in buffer " << buffers_.front()->lastLogId()
<< ", numLogs in buffer " << buffers_.front()->size();
}
buffers_.pop_front();
CHECK(!buffers_.empty());
CHECK_EQ(currId_, buffers_.front()->firstLogId());
nextFirstId_ = getFirstIdInNextBuffer();
currIdx_ = 0;
} else {
++currIdx_;
}
currTerm_ = buffers_.front()->getTerm(currIdx_);
}
return *this;
}
bool FileBasedWalIterator::valid() const {
return currId_ <= lastId_;
}
LogID FileBasedWalIterator::logId() const {
return currId_;
}
TermID FileBasedWalIterator::logTerm() const {
return currTerm_;
}
ClusterID FileBasedWalIterator::logSource() const {
if (currId_ >= firstIdInBuffer_) {
// Retrieve from the buffer
DCHECK(!buffers_.empty());
return buffers_.front()->getCluster(currIdx_);
} else {
// Retrieve from the file
DCHECK(!fds_.empty());
ClusterID cluster = 0;
CHECK_EQ(pread(fds_.front(),
&(cluster),
sizeof(ClusterID),
currPos_
+ sizeof(LogID)
+ sizeof(TermID)
+ sizeof(int32_t)),
static_cast<ssize_t>(sizeof(ClusterID)))
<< "Failed to read. Curr position is " << currPos_
<< ", expected read length is " << sizeof(ClusterID)
<< " (errno: " << errno << "): " << strerror(errno);
return cluster;
}
}
folly::StringPiece FileBasedWalIterator::logMsg() const {
if (currId_ >= firstIdInBuffer_) {
// Retrieve from the buffer
DCHECK(!buffers_.empty());
return buffers_.front()->getLog(currIdx_);
} else {
// Retrieve from the file
DCHECK(!fds_.empty());
currLog_.resize(currMsgLen_);
CHECK_EQ(pread(fds_.front(),
&(currLog_[0]),
currMsgLen_,
currPos_
+ sizeof(LogID)
+ sizeof(TermID)
+ sizeof(int32_t)
+ sizeof(ClusterID)),
static_cast<ssize_t>(currMsgLen_))
<< "Failed to read. Curr position is " << currPos_
<< ", expected read length is " << currMsgLen_
<< " (errno: " << errno << "): " << strerror(errno);
return currLog_;
}
}
LogID FileBasedWalIterator::getFirstIdInNextBuffer() const {
auto it = buffers_.begin();
++it;
if (it == buffers_.end()) {
return buffers_.front()->lastLogId() + 1;
} else {
return (*it)->firstLogId();
}
}
LogID FileBasedWalIterator::getFirstIdInNextFile() const {
auto it = idRanges_.begin();
++it;
if (it == idRanges_.end()) {
return idRanges_.front().second + 1;
} else {
return it->first;
}
}
} // namespace wal
} // namespace nebula
| 1 | 24,614 | Why is the condition of "lastId <= wal _-> lastLogId() " added here? | vesoft-inc-nebula | cpp |
@@ -13,3 +13,9 @@
// limitations under the License.
package model
+
+import "path"
+
+func MakeEnvironmentURL(baseURL, environmentID string) string {
+ return path.Join(baseURL, "settings", "environment")
+} | 1 | // Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package model
| 1 | 17,638 | `environmentID` is unused in MakeEnvironmentURL | pipe-cd-pipe | go |
@@ -1700,10 +1700,14 @@ public class LFMainActivity extends SharedMediaActivity {
}
}
- private void checkNoSearchResults(String result){
- textView.setText(getString(R.string.null_search_result) + " " + '"' + result + '"' );
- textView.setTextColor(getTextColor());
- textView.setVisibility(View.VISIBLE);
+ private void checkNoSearchResults(String result,int length){
+ if (length>0) {
+ textView.setText(getString(R.string.null_search_result) + " " + '"' + result + '"');
+ textView.setTextColor(getTextColor());
+ textView.setVisibility(View.VISIBLE);
+ }
+ else
+ textView.setVisibility(View.INVISIBLE);
}
//region MENU | 1 | package org.fossasia.phimpme.gallery.activities;
import android.animation.Animator;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.bumptech.glide.gifencoder.AnimatedGifEncoder;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.view.IconicsImageView;
import org.fossasia.phimpme.R;
import org.fossasia.phimpme.base.SharedMediaActivity;
import org.fossasia.phimpme.data.local.FavouriteImagesModel;
import org.fossasia.phimpme.data.local.ImageDescModel;
import org.fossasia.phimpme.data.local.TrashBinRealmModel;
import org.fossasia.phimpme.data.local.UploadHistoryRealmModel;
import org.fossasia.phimpme.gallery.SelectAlbumBottomSheet;
import org.fossasia.phimpme.gallery.adapters.AlbumsAdapter;
import org.fossasia.phimpme.gallery.adapters.MediaAdapter;
import org.fossasia.phimpme.gallery.data.Album;
import org.fossasia.phimpme.gallery.data.CustomAlbumsHelper;
import org.fossasia.phimpme.gallery.data.HandlingAlbums;
import org.fossasia.phimpme.gallery.data.Media;
import org.fossasia.phimpme.gallery.data.base.ImageFileFilter;
import org.fossasia.phimpme.gallery.data.base.MediaComparators;
import org.fossasia.phimpme.gallery.data.base.SortingMode;
import org.fossasia.phimpme.gallery.data.base.SortingOrder;
import org.fossasia.phimpme.gallery.data.providers.MediaStoreProvider;
import org.fossasia.phimpme.gallery.data.providers.StorageProvider;
import org.fossasia.phimpme.gallery.util.Affix;
import org.fossasia.phimpme.gallery.util.AlertDialogsHelper;
import org.fossasia.phimpme.gallery.util.ContentHelper;
import org.fossasia.phimpme.gallery.util.Measure;
import org.fossasia.phimpme.gallery.util.PreferenceUtil;
import org.fossasia.phimpme.gallery.util.SecurityHelper;
import org.fossasia.phimpme.gallery.util.StringUtils;
import org.fossasia.phimpme.gallery.views.CustomScrollBarRecyclerView;
import org.fossasia.phimpme.gallery.views.GridSpacingItemDecoration;
import org.fossasia.phimpme.trashbin.TrashBinActivity;
import org.fossasia.phimpme.uploadhistory.UploadHistory;
import org.fossasia.phimpme.utilities.ActivitySwitchHelper;
import org.fossasia.phimpme.utilities.Constants;
import org.fossasia.phimpme.utilities.NotificationHandler;
import org.fossasia.phimpme.utilities.SnackBarHandler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import static org.fossasia.phimpme.gallery.data.base.SortingMode.DATE;
import static org.fossasia.phimpme.gallery.data.base.SortingMode.NAME;
import static org.fossasia.phimpme.gallery.data.base.SortingMode.NUMERIC;
import static org.fossasia.phimpme.gallery.data.base.SortingMode.SIZE;
import static org.fossasia.phimpme.gallery.util.ThemeHelper.LIGHT_THEME;
import static org.fossasia.phimpme.utilities.ActivitySwitchHelper.context;
public class LFMainActivity extends SharedMediaActivity {
private static String TAG = "AlbumsAct";
private LFMainActivity activityContext;
private int REQUEST_CODE_SD_CARD_PERMISSIONS = 42;
private static final int BUFFER = 80000;
private boolean about = false, settings = false, uploadHistory = false, favourites = false, trashbin = false;
private CustomAlbumsHelper customAlbumsHelper = CustomAlbumsHelper.getInstance(LFMainActivity.this);
private PreferenceUtil SP;
private SecurityHelper securityObj;
private AlbumsAdapter albumsAdapter;
private GridSpacingItemDecoration rvAlbumsDecoration;
private SwipeRefreshLayout.OnRefreshListener refreshListener;
private MediaAdapter mediaAdapter;
private GridSpacingItemDecoration rvMediaDecoration;
private SelectAlbumBottomSheet bottomSheetDialogFragment;
private BottomNavigationView navigationView;
private boolean hidden = false, pickMode = false, editMode = false, albumsMode = true, firstLaunch = true, localFolder = true, hidenav = false;
//to handle pinch gesture
private ScaleGestureDetector mScaleGestureDetector;
//To handle all photos/Album conditions
public boolean all_photos = false;
private boolean checkForReveal = true;
final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
public static ArrayList<Media> listAll;
public int size;
public int pos;
ArrayList<String> path;
private ArrayList<Media> media;
private ArrayList<Media> selectedMedias = new ArrayList<>();
private ArrayList<Media> selectedAlbumMedia = new ArrayList<>();
public boolean visible;
private ArrayList<Album> albList;
//To handle favourite collection
private Realm realm;
private ArrayList<Media> favouriteslist;
public boolean fav_photos = false;
private IconicsImageView favicon;
private CustomScrollBarRecyclerView rvAlbums;
private CustomScrollBarRecyclerView rvMedia;
// To handle back pressed
boolean doubleBackToExitPressedOnce = false;
private boolean fromOnClick = false;
// Binding various views with Butterknife
private SearchView searchView;
@BindView(R.id.toolbar)
protected Toolbar toolbar;
@BindView(R.id.swipeRefreshLayout)
protected SwipeRefreshLayout swipeRefreshLayout;
@BindView(R.id.drawer_layout)
protected DrawerLayout mDrawerLayout;
@BindView(R.id.fab_scroll_up)
protected FloatingActionButton fabScrollUp;
@BindView(R.id.Drawer_Setting_Item)
protected TextView drawerSettingText;
@BindView(R.id.Drawer_About_Item)
protected TextView drawerAboutText;
@BindView(R.id.Drawer_share_Item)
protected TextView drawerShareText;
@BindView(R.id.Drawer_rate_Item)
protected TextView drawerRateText;
@BindView(R.id.Drawer_Upload_Item)
protected TextView drawerUploadText;
@BindView(R.id.Drawer_TrashBin_Item)
protected TextView drawerTrashText;
@BindView(R.id.Drawer_Setting_Icon)
protected IconicsImageView drawerSettingIcon;
@BindView(R.id.Drawer_About_Icon)
protected IconicsImageView drawerAboutIcon;
@BindView(R.id.Drawer_share_Icon)
protected IconicsImageView drawerShareIcon;
@BindView(R.id.Drawer_rate_Icon)
protected IconicsImageView drawerRateIcon;
@BindView(R.id.Drawer_Upload_Icon)
protected IconicsImageView drawerUploadIcon;
@BindView(R.id.Drawer_trashbin_Icon)
protected IconicsImageView drawerTrashIcon;
@BindView(R.id.drawer_scrollbar)
protected ScrollView scrollView;
@BindView(R.id.appbar_toolbar)
protected View toolbari;
@BindView(R.id.nothing_to_show)
protected TextView nothingToShow;
@BindView(R.id.no_search_results)
protected TextView textView;
@BindView(R.id.Drawer_Default_Icon)
protected IconicsImageView defaultIcon;
@BindView(R.id.Drawer_hidden_Icon)
protected IconicsImageView hiddenIcon;
@BindView(R.id.Drawer_Default_Item)
protected TextView defaultText;
@BindView(R.id.Drawer_hidden_Item)
protected TextView hiddenText;
@BindView(R.id.star_image_view)
protected ImageView starImageView;
@BindView(R.id.no_fav_msg)
protected TextView noFavMsg;
/*
editMode- When true, user can select items by clicking on them one by one
*/
/**
* Handles long clicks on photos.
* If first long click on photo (editMode = false), go into selection mode and set editMode = true.
* If not first long click, means that already in selection mode- s0 select all photos upto chosen one.
*/
private View.OnLongClickListener photosOnLongClickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (checkForReveal) {
enterReveal();
checkForReveal = false;
}
Media m = (Media) v.findViewById(R.id.photo_path).getTag();
//If first long press, turn on selection mode
hideNavigationBar();
hidenav = true;
if (!all_photos && !fav_photos) {
appBarOverlay();
if (!editMode) {
mediaAdapter.notifyItemChanged(getAlbum().toggleSelectPhoto(m));
editMode = true;
} else getAlbum().selectAllPhotosUpTo(getAlbum().getIndex(m), mediaAdapter);
invalidateOptionsMenu();
} else if (all_photos && !fav_photos) {
if (!editMode) {
mediaAdapter.notifyItemChanged(toggleSelectPhoto(m));
editMode = true;
}
} else if (fav_photos && !all_photos) {
if (!editMode) {
mediaAdapter.notifyItemChanged(toggleSelectPhoto(m));
editMode = true;
} else {
selectAllPhotosUpToFav(getImagePosition(m.getPath()));
}
} else selectAllPhotosUpTo(getImagePosition(m.getPath()), mediaAdapter);
return true;
}
};
/**
* Helper method for making reveal animation for toolbar when any item is selected by long click.
*/
private void enterReveal() {
// get the center for the clipping circle
int cx = toolbari.getMeasuredWidth() / 2;
int cy = toolbari.getMeasuredHeight() / 2;
// get the final radius for the clipping circle
int finalRadius = Math.max(toolbari.getWidth(), toolbari.getHeight()) / 2;
// create the animator for this view
Animator anim =
ViewAnimationUtils.createCircularReveal(toolbari, cx, cy, 5, finalRadius);
anim.start();
}
/**
* Helper method for making reveal animation for toolbar when back is presses in edit mode.
*/
private void exitReveal() {
// get the center for the clipping circle
int cx = toolbari.getMeasuredWidth() / 2;
int cy = toolbari.getMeasuredHeight() / 2;
// get the final radius for the clipping circle
int finalRadius = Math.max(toolbari.getWidth(), toolbari.getHeight()) / 2;
// create the animator for this view
Animator anim =
ViewAnimationUtils.createCircularReveal(toolbari, cx, cy, finalRadius, 5);
anim.start();
}
private int toggleSelectPhoto(Media m) {
if (m != null) {
m.setSelected(!m.isSelected());
if (m.isSelected())
selectedMedias.add(m);
else
selectedMedias.remove(m);
}
if (selectedMedias.size() == 0) {
getNavigationBar();
editMode = false;
toolbar.setTitle(getString(R.string.all));
} else {
if (!fav_photos) {
toolbar.setTitle(selectedMedias.size() + "/" + size);
} else if (fav_photos) {
toolbar.setTitle(selectedMedias.size() + "/" + favouriteslist.size());
}
}
invalidateOptionsMenu();
return getImagePosition(m.getPath());
}
public void clearSelectedPhotos() {
for (Media m : selectedMedias)
m.setSelected(false);
if (selectedMedias != null)
selectedMedias.clear();
if (localFolder) toolbar.setTitle(getString(R.string.local_folder));
else toolbar.setTitle(getString(R.string.hidden_folder));
}
public void selectAllPhotos() {
if (all_photos && !fav_photos) {
for (Media m : listAll) {
m.setSelected(true);
selectedMedias.add(m);
}
toolbar.setTitle(selectedMedias.size() + "/" + size);
} else if (!all_photos && fav_photos) {
for (Media m : favouriteslist) {
m.setSelected(true);
if (m.isSelected())
selectedMedias.add(m);
}
toolbar.setTitle(selectedMedias.size() + "/" + favouriteslist.size());
}
}
public void selectAllPhotosUpTo(int targetIndex, MediaAdapter adapter) {
int indexRightBeforeOrAfter = -1;
int indexNow;
for (Media sm : selectedMedias) {
indexNow = getImagePosition(sm.getPath());
if (indexRightBeforeOrAfter == -1) indexRightBeforeOrAfter = indexNow;
if (indexNow > targetIndex) break;
indexRightBeforeOrAfter = indexNow;
}
if (indexRightBeforeOrAfter != -1) {
for (int index = Math.min(targetIndex, indexRightBeforeOrAfter); index <= Math.max(targetIndex, indexRightBeforeOrAfter); index++) {
if (listAll.get(index) != null && !listAll.get(index).isSelected()) {
listAll.get(index).setSelected(true);
selectedMedias.add(listAll.get(index));
adapter.notifyItemChanged(index);
}
}
}
toolbar.setTitle(selectedMedias.size() + "/" + size);
}
public void selectAllPhotosUpToFav(int targetIndex) {
int indexRightBeforeOrAfter = -1;
int indexNow;
for (Media sm : selectedMedias) {
indexNow = getImagePosition(sm.getPath());
if (indexRightBeforeOrAfter == -1) indexRightBeforeOrAfter = indexNow;
if (indexNow > targetIndex) break;
indexRightBeforeOrAfter = indexNow;
}
ArrayList<Media> favlist = mediaAdapter.getList();
if (indexRightBeforeOrAfter != -1) {
for (int index = Math.min(targetIndex, indexRightBeforeOrAfter); index <= Math.max(targetIndex, indexRightBeforeOrAfter); index++) {
if (favlist.get(index) != null && !favlist.get(index).isSelected()) {
favlist.get(index).setSelected(true);
selectedMedias.add(favlist.get(index));
mediaAdapter.notifyItemChanged(index);
}
}
}
toolbar.setTitle(selectedMedias.size() + "/" + favlist.size());
}
public void populateAlbum() {
albList = new ArrayList<>();
for (Album album : getAlbums().dispAlbums) {
albList.add(album);
}
}
/**
* Handles short clicks on photos.
* If in selection mode (editMode = true) , select the photo if it is unselected and unselect it if it's selected.
* This mechanism makes it possible to select photos one by one by short-clicking on them.
* If not in selection mode (editMode = false) , get current photo from album and open it in singleActivity
*/
private View.OnClickListener photosOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Media m = (Media) v.findViewById(R.id.photo_path).getTag();
if (all_photos) {
pos = getImagePosition(m.getPath());
}
if (fav_photos) {
pos = getImagePosition(m.getPath());
}
if (!all_photos && !fav_photos) {
if (!pickMode) {
//if in selection mode, toggle the selected/unselect state of photo
if (editMode) {
appBarOverlay();
mediaAdapter.notifyItemChanged(getAlbum().toggleSelectPhoto(m));
if (getAlbum().selectedMedias.size() == 0)
getNavigationBar();
invalidateOptionsMenu();
} else {
v.setTransitionName(getString(R.string.transition_photo));
getAlbum().setCurrentPhotoIndex(m);
Intent intent = new Intent(LFMainActivity.this, SingleMediaActivity.class);
intent.putExtra("path", Uri.fromFile(new File(m.getPath())).toString());
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(LFMainActivity.this, v, v.getTransitionName());
intent.setAction(SingleMediaActivity.ACTION_OPEN_ALBUM);
startActivity(intent, options.toBundle());
}
} else {
setResult(RESULT_OK, new Intent().setData(m.getUri()));
finish();
}
} else if (all_photos && !fav_photos) {
if (!editMode) {
Intent intent = new Intent(REVIEW_ACTION, Uri.fromFile(new File(m.getPath())));
intent.putExtra(getString(R.string.all_photo_mode), true);
intent.putExtra(getString(R.string.position), pos);
intent.putExtra(getString(R.string.allMediaSize), size);
v.setTransitionName(getString(R.string.transition_photo));
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(LFMainActivity.this, v, v.getTransitionName());
intent.setClass(getApplicationContext(), SingleMediaActivity.class);
startActivity(intent, options.toBundle());
} else {
mediaAdapter.notifyItemChanged(toggleSelectPhoto(m));
}
} else if (!all_photos && fav_photos) {
if (!editMode) {
Intent intent = new Intent(REVIEW_ACTION, Uri.fromFile(new File(m.getPath())));
intent.putExtra("fav_photos", true);
intent.putExtra(getString(R.string.position), pos);
intent.putParcelableArrayListExtra("favouriteslist", favouriteslist);
intent.putExtra(getString(R.string.allMediaSize), favouriteslist.size());
v.setTransitionName(getString(R.string.transition_photo));
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(LFMainActivity.this, v, v.getTransitionName());
intent.setClass(getApplicationContext(), SingleMediaActivity.class);
startActivity(intent, options.toBundle());
} else {
mediaAdapter.notifyItemChanged(toggleSelectPhoto(m));
}
}
}
};
private View.OnLongClickListener albumOnLongCLickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final Album album = (Album) v.findViewById(R.id.album_name).getTag();
if(securityObj.isActiveSecurity() && securityObj.isPasswordOnfolder()) {
final boolean passco[] = {false};
if (check(album.getPath())) {
AlertDialog.Builder passwordDialogBuilder =
new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword =
securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
editTextPassword.setHintTextColor(getResources().getColor(R.color.grey, null));
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog on wrong password
}
});
editTextPassword.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void afterTextChanged(Editable editable) {
if(securityObj.getTextInputLayout().getVisibility() == View.VISIBLE && !passco[0]){
securityObj.getTextInputLayout().setVisibility(View.INVISIBLE);
}
else{
passco[0]=false;
}
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
passwordDialog.show();
AlertDialogsHelper.setButtonTextColor(
new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE},
getAccentColor(), passwordDialog);
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
passwordDialog.dismiss();
if (checkForReveal) {
enterReveal();
checkForReveal = false;
}
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(album));
editMode = true;
invalidateOptionsMenu();
if (getAlbums().getSelectedCount() == 0)
getNavigationBar();
else {
hideNavigationBar();
hidenav = true;
}
}
// if password is incorrect, notify user of incorrect password
else {
passco[0] = true;
securityObj.getTextInputLayout().setVisibility(View.VISIBLE);
SnackBarHandler
.showWithBottomMargin(mDrawerLayout, getString(R.string.wrong_password),
navigationView.getHeight());
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else {
if (checkForReveal) {
enterReveal();
checkForReveal = false;
}
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(album));
editMode = true;
invalidateOptionsMenu();
if (getAlbums().getSelectedCount() == 0)
getNavigationBar();
else {
hideNavigationBar();
hidenav = true;
}
}
} else {
if (checkForReveal) {
enterReveal();
checkForReveal = false;
}
//for selecting albums upto a particular range
if(editMode) {
int currentAlbum = getAlbums().getCurrentAlbumIndex(album);
getAlbums().selectAllPhotosUpToAlbums(currentAlbum, albumsAdapter);
} else {
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(album));
}
editMode = true;
invalidateOptionsMenu();
if (getAlbums().getSelectedCount() == 0)
getNavigationBar();
else {
hideNavigationBar();
hidenav = true;
}
}
return true;
}
};
private boolean check(String path) {
boolean dr = false;
for (String s : securityObj.getSecuredfolders()) {
if (s.equals(path)) {
dr = true;
break;
}
}
return dr;
}
private View.OnClickListener albumOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
fromOnClick = true;
final Album album = (Album) v.findViewById(R.id.album_name).getTag();
showAppBar();
//int index = Integer.parseInt(v.findViewById(R.id.album_name).getTag().toString());
if (editMode) {
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(album));
if (getAlbums().getSelectedCount() == 0)
getNavigationBar();
invalidateOptionsMenu();
} else if(securityObj.isActiveSecurity() && securityObj.isPasswordOnfolder()){
final boolean[] passco = {false};
if (check(album.getPath())) {
AlertDialog.Builder passwordDialogBuilder =
new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword =
securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
editTextPassword.setHintTextColor(getResources().getColor(R.color.grey, null));
editTextPassword.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void afterTextChanged(Editable editable) {
if(securityObj.getTextInputLayout().getVisibility() == View.VISIBLE && !passco[0]){
securityObj.getTextInputLayout().setVisibility(View.INVISIBLE);
}
else{
passco[0]=false;
}
}
});
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog on wrong password
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
passwordDialog.show();
AlertDialogsHelper.setButtonTextColor(
new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE},
getAccentColor(), passwordDialog);
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
passwordDialog.dismiss();
getAlbums().setCurrentAlbum(album);
displayCurrentAlbumMedia(true);
}
// if password is incorrect, notify user of incorrect password
else {
passco[0] =true;
securityObj.getTextInputLayout().setVisibility(View.VISIBLE);
SnackBarHandler
.showWithBottomMargin(mDrawerLayout, getString(R.string.wrong_password),
navigationView.getHeight());
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else {
getAlbums().setCurrentAlbum(album);
displayCurrentAlbumMedia(true);
}
} else {
getAlbums().setCurrentAlbum(album);
displayCurrentAlbumMedia(true);
}
}
};
/**
* Method for clearing the scroll flags.
*/
private void appBarOverlay() {
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED); // clear all scroll flags
}
/**
* Method for adding the scroll flags.
*/
private void clearOverlay() {
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
| AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
}
private void showAppBar() {
if (toolbar.getParent() instanceof AppBarLayout) {
((AppBarLayout)toolbar.getParent()).setExpanded(true, true);
}
}
public int getImagePosition(String path) {
int pos = 0;
if (all_photos) {
for (int i = 0; i < listAll.size(); i++) {
if (listAll.get(i).getPath().equals(path)) {
pos = i;
break;
}
}
} else if (fav_photos) {
Collections.sort(favouriteslist, MediaComparators.getComparator(getAlbum().settings.getSortingMode(), getAlbum().settings
.getSortingOrder()));
for (int i = 0; i < favouriteslist.size(); i++) {
if (favouriteslist.get(i).getPath().equals(path)) {
pos = i;
break;
}
}
}
return pos;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TAG", "lfmain");
ButterKnife.bind(this);
navigationView = findViewById(R.id.bottombar);
favicon = findViewById(R.id.Drawer_favourite_Icon);
rvAlbums = findViewById(R.id.grid_albums);
rvMedia = findViewById(R.id.grid_photos);
overridePendingTransition(R.anim.right_to_left,
R.anim.left_to_right);
SP = PreferenceUtil.getInstance(getApplicationContext());
albumsMode = true;
editMode = false;
securityObj = new SecurityHelper(LFMainActivity.this);
if (getIntent().getExtras() != null)
pickMode = getIntent().getExtras().getBoolean(SplashScreen.PICK_MODE);
SP.putBoolean(getString(R.string.preference_use_alternative_provider), false);
initUI();
activityContext = this;
new initAllPhotos().execute();
new SortModeSet(activityContext).execute(DATE);
displayData(getIntent().getExtras());
checkNothing();
populateAlbum();
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int itemID = item.getItemId();
if (itemID == R.id.navigation_home) {
if(textView.getVisibility() == View.VISIBLE){
textView.setVisibility(View.GONE);
}
if (!localFolder) {
hidden = false;
localFolder = true;
findViewById(R.id.ll_drawer_hidden).setBackgroundColor(Color.TRANSPARENT);
findViewById(R.id.ll_drawer_Default).setBackgroundColor(getHighlightedItemColor());
tint();
}
displayAlbums();
return true;
}
return LFMainActivity.super.onNavigationItemSelected(item);
}
});
}
@Override
public void onResume() {
super.onResume();
ActivitySwitchHelper.setContext(this);
securityObj.updateSecuritySetting();
setupUI();
if (all_photos && !fav_photos) {
new PrepareAllPhotos(activityContext).execute();
getNavigationBar();
} else if (!all_photos && fav_photos) {
new FavouritePhotos(activityContext).execute();
} else {
getNavigationBar();
if (SP.getBoolean("auto_update_media", false)) {
if (albumsMode) {
if (!firstLaunch) new PrepareAlbumTask(activityContext).execute();
} else new PreparePhotosTask(activityContext).execute();
} else {
albumsAdapter.notifyDataSetChanged();
mediaAdapter.notifyDataSetChanged();
}
}
invalidateOptionsMenu();
firstLaunch = false;
}
private void displayCurrentAlbumMedia(boolean reload) {
toolbar.setTitle(getAlbum().getName());
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mediaAdapter.swapDataSet(getAlbum().getMedia(), false);
if (reload) new PreparePhotosTask(activityContext).execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = false;
invalidateOptionsMenu();
}
private void displayAllMedia(boolean reload) {
clearSelectedPhotos();
toolbar.setTitle(getString(R.string.all_media));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mediaAdapter.swapDataSet(listAll, false);
if (reload) new PrepareAllPhotos(activityContext).execute();
if (reload) new PrepareAllPhotos(activityContext).execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = false;
invalidateOptionsMenu();
}
private void getfavouriteslist() {
favouriteslist = new ArrayList<Media>();
ArrayList<String> todelete = new ArrayList<>();
realm = Realm.getDefaultInstance();
RealmQuery<FavouriteImagesModel> favouriteImagesModelRealmQuery = realm.where(FavouriteImagesModel.class);
int count = Integer.parseInt(String.valueOf(favouriteImagesModelRealmQuery.count()));
for (int i = 0; i < count; i++) {
final String path = favouriteImagesModelRealmQuery.findAll().get(i).getPath();
if (new File(favouriteImagesModelRealmQuery.findAll().get(i).getPath()).exists()) {
favouriteslist.add(new Media(new File(favouriteImagesModelRealmQuery.findAll().get(i).getPath())));
} else {
todelete.add(path);
}
}
for(int i = 0; i < todelete.size(); i++){
final String path = todelete.get(i);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<FavouriteImagesModel> result = realm.where(FavouriteImagesModel.class).equalTo
("path", path).findAll();
result.deleteAllFromRealm();
}
});
}
}
private void displayfavourites() {
toolbar.setTitle(getResources().getString(R.string.favourite_title));
getfavouriteslist();
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
fav_photos=true;
mediaAdapter.swapDataSet(favouriteslist, true);
if(fav_photos){
new FavouritePhotos(activityContext).execute();
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = all_photos = false;
invalidateOptionsMenu();
}
private void displayAlbums() {
all_photos = false;
fav_photos = false;
displayAlbums(true);
}
private void displayAlbums(boolean reload) {
if (localFolder) {
toolbar.setTitle(getString(R.string.local_folder));
} else {
toolbar.setTitle(getString(R.string.hidden_folder));
}
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_menu));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
if (reload) new PrepareAlbumTask(activityContext).execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
albumsMode = true;
editMode = false;
invalidateOptionsMenu();
mediaAdapter.swapDataSet(new ArrayList<Media>(), false);
rvMedia.scrollToPosition(0);
}
private ArrayList<Media> getselecteditems(){
ArrayList<Media> storeselmedia = new ArrayList<>();
for(Media m: getAlbum().getSelectedMedia()){
storeselmedia.add(m);
}
return storeselmedia;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
int photopos = 0;
int albumpos = 0;
super.onConfigurationChanged(newConfig);
if(albumsMode){
albumpos = ((GridLayoutManager) rvAlbums.getLayoutManager()).findFirstVisibleItemPosition();
updateColumnsRvs();
(rvAlbums.getLayoutManager()).scrollToPosition(albumpos);
} else {
photopos = ((GridLayoutManager) rvMedia.getLayoutManager()).findFirstVisibleItemPosition();
updateColumnsRvs();
(rvMedia.getLayoutManager()).scrollToPosition(photopos);
}
}
private boolean displayData(Bundle data) {
if (data != null) {
switch (data.getInt(SplashScreen.CONTENT)) {
case SplashScreen.ALBUMS_PREFETCHED:
displayAlbums(false);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(true);
return true;
case SplashScreen.ALBUMS_BACKUP:
displayAlbums(true);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(true);
return true;
case SplashScreen.PHOTOS_PREFETCHED:
//TODO ask password if hidden
new Thread(new Runnable() {
@Override
public void run() {
getAlbums().loadAlbums(getApplicationContext(), getAlbum().isHidden());
}
}).start();
displayCurrentAlbumMedia(false);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(false);
return true;
}
}
displayAlbums(true);
return false;
}
private class initAllPhotos extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
listAll = StorageProvider.getAllShownImages(LFMainActivity.this);
size = listAll.size();
media = listAll;
Collections.sort(listAll, MediaComparators.getComparator(getAlbum().settings.getSortingMode(), getAlbum().settings.getSortingOrder()));
return null;
}
}
private void initUI() {
clearOverlay();
setSupportActionBar(toolbar);
rvAlbums.setHasFixedSize(true);
rvAlbums.setItemAnimator(new DefaultItemAnimator());
rvMedia.setHasFixedSize(true);
rvMedia.setItemAnimator(new DefaultItemAnimator());
albumsAdapter = new AlbumsAdapter(getAlbums().dispAlbums, LFMainActivity.this);
albumsAdapter.setOnClickListener(albumOnClickListener);
albumsAdapter.setOnLongClickListener(albumOnLongCLickListener);
rvAlbums.setAdapter(albumsAdapter);
//set scale gesture detector for resizing the gridItem
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
if (detector.getCurrentSpan() > 200 && detector.getTimeDelta() > 200) {
int spanCount;
if (albumsMode)
spanCount = columnsCount();
else
spanCount = mediaCount();
//zooming out
if ((detector.getCurrentSpan() - detector.getPreviousSpan() < -300) && spanCount < 6) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
if (albumsMode)
SP.putInt("n_columns_folders", spanCount + 1);
else
SP.putInt("n_columns_media", spanCount + 1);
} else {
if (albumsMode)
SP.putInt("n_columns_folders_landscape", spanCount + 1);
else
SP.putInt("n_columns_media_landscape", spanCount + 1);
}
if (albumsMode)
updateColumnsRvAlbums();
else
updateColumnsRvMedia();
}
//zooming in
else if ((detector.getCurrentSpan() - detector.getPreviousSpan() > 300) && spanCount > 1) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
if (albumsMode)
SP.putInt("n_columns_folders", spanCount - 1);
else
SP.putInt("n_columns_media", spanCount - 1);
} else {
if (albumsMode)
SP.putInt("n_columns_folders_landscape", spanCount - 1);
else
SP.putInt("n_columns_media_landscape", spanCount - 1);
}
if (albumsMode)
updateColumnsRvAlbums();
else
updateColumnsRvMedia();
}
}
return false;
}
});
//set touch listener on recycler view
rvAlbums.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mScaleGestureDetector.onTouchEvent(event);
return false;
}
});
rvMedia.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mScaleGestureDetector.onTouchEvent(event);
return false;
}
});
mediaAdapter = new MediaAdapter(getAlbum().getMedia(), LFMainActivity.this);
mediaAdapter.setOnClickListener(photosOnClickListener);
mediaAdapter.setOnLongClickListener(photosOnLongClickListener);
rvMedia.setAdapter(mediaAdapter);
int spanCount = columnsCount();
rvAlbumsDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvAlbums.addItemDecoration(rvAlbumsDecoration);
rvAlbums.setLayoutManager(new GridLayoutManager(this, spanCount));
spanCount = mediaCount();
rvMediaDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvMedia.setLayoutManager(new GridLayoutManager(getApplicationContext(), spanCount));
rvMedia.addItemDecoration(rvMediaDecoration);
/**** SWIPE TO REFRESH ****/
swipeRefreshLayout.setColorSchemeColors(getAccentColor());
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getBackgroundColor());
refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getNavigationBar();
if (albumsMode) {
getAlbums().clearSelectedAlbums();
new PrepareAlbumTask(activityContext).execute();
} else {
if (!all_photos && !fav_photos) {
getAlbum().clearSelectedPhotos();
new PreparePhotosTask(activityContext).execute();
} else {
if (all_photos && !fav_photos) {
new PrepareAllPhotos(activityContext).execute();
} else if (!all_photos && fav_photos) {
new FavouritePhotos(activityContext).execute();
}
}
}
}
};
swipeRefreshLayout.setOnRefreshListener(refreshListener);
/**** DRAWER ****/
mDrawerLayout.addDrawerListener(new ActionBarDrawerToggle(this,
mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
//Put your code here
// materialMenu.animateIconState(MaterialMenuDrawable.IconState.BURGER);
Intent intent = null;
if (settings) {
intent = new Intent(LFMainActivity.this, SettingsActivity.class);
startActivity(intent);
settings = false;
} else if (about) {
intent = new Intent(LFMainActivity.this, AboutActivity.class);
startActivity(intent);
about = false;
} else if (uploadHistory) {
intent = new Intent(LFMainActivity.this, UploadHistory.class);
startActivity(intent);
uploadHistory = false;
} else if (favourites) {
displayfavourites();
favourites = false;
} else if (trashbin) {
Intent intent1 = new Intent(LFMainActivity.this, TrashBinActivity.class);
startActivity(intent1);
trashbin = false;
}
}
public void onDrawerOpened(View drawerView) {
//Put your code here
//materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW);
}
});
/**
* Floating Action Button to Scroll Up
*/
setUpFab();
setRecentApp(getString(R.string.app_name));
setupUI();
if (pickMode) {
hideNavigationBar();
swipeRefreshLayout.setPadding(0, 0, 0, 0);
}
}
/**
* Method to set scroll listeners for recycler view
*/
private void setUpFab() {
fabScrollUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rvMedia.smoothScrollToPosition(0);
fabScrollUp.hide();
}
});
fabScrollUp.hide();
rvMedia.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (linearLayoutManager.findFirstVisibleItemPosition() > 30 && !fabScrollUp.isShown())
fabScrollUp.show();
else if (linearLayoutManager.findFirstVisibleItemPosition() < 30 && fabScrollUp.isShown())
fabScrollUp.hide();
fabScrollUp.setAlpha(0.7f);
}
});
}
public int columnsCount() {
return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
? SP.getInt("n_columns_folders", 2)
: SP.getInt("n_columns_folders_landscape", 3);
}
public int mediaCount() {
return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
? SP.getInt("n_columns_media", 3)
: SP.getInt("n_columns_media_landscape", 4);
}
private void updateColumnsRvs() {
updateColumnsRvAlbums();
updateColumnsRvMedia();
}
private void updateColumnsRvAlbums() {
int spanCount = columnsCount();
if (spanCount != ((GridLayoutManager) rvAlbums.getLayoutManager()).getSpanCount()) {
rvAlbums.removeItemDecoration(rvAlbumsDecoration);
rvAlbumsDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvAlbums.addItemDecoration(rvAlbumsDecoration);
rvAlbums.setLayoutManager(new GridLayoutManager(this, spanCount));
}
}
private void updateColumnsRvMedia() {
int spanCount = mediaCount();
if (spanCount != ((GridLayoutManager) rvMedia.getLayoutManager()).getSpanCount()) {
((GridLayoutManager) rvMedia.getLayoutManager()).getSpanCount();
rvMedia.removeItemDecoration(rvMediaDecoration);
rvMediaDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvMedia.setLayoutManager(new GridLayoutManager(getApplicationContext(), spanCount));
rvMedia.addItemDecoration(rvMediaDecoration);
}
}
//region TESTING
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public final void onActivityResult(final int requestCode, final int resultCode, final Intent resultData) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_SD_CARD_PERMISSIONS) {
Uri treeUri = resultData.getData();
// Persist URI in shared preference so that you can use it later.
ContentHelper.saveSdCardInfo(getApplicationContext(), treeUri);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.got_permission_wr_sdcard), 0);
}
}
}
//endregion
private void requestSdCardPermissions() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(LFMainActivity.this, dialogBuilder,
R.string.sd_card_write_permission_title, R.string.sd_card_permissions_message, null);
dialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_CODE_SD_CARD_PERMISSIONS);
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), alertDialog);
}
//region UI/GRAPHIC
private void setupUI() {
updateColumnsRvs();
//TODO: MUST BE FIXED
toolbar.setPopupTheme(getPopupToolbarStyle());
toolbar.setBackgroundColor(getPrimaryColor());
if (localFolder) {
toolbar.setTitle(getString(R.string.local_folder));
} else {
toolbar.setTitle(getString(R.string.hidden_folder));
}
//navigationView.setVisibility(View.VISIBLE);
/**** SWIPE TO REFRESH ****/
swipeRefreshLayout.setColorSchemeColors(getAccentColor());
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getBackgroundColor());
setStatusBarColor();
setNavBarColor();
setDrawerTheme();
rvAlbums.setBackgroundColor(getBackgroundColor());
rvMedia.setBackgroundColor(getBackgroundColor());
rvAlbums.setScrollBarColor(getPrimaryColor());
rvMedia.setScrollBarColor(getPrimaryColor());
mediaAdapter.updatePlaceholder(getApplicationContext());
albumsAdapter.updateTheme();
/**** DRAWER ****/
setScrollViewColor(scrollView);
/**** recyclers drawable *****/
Drawable drawableScrollBar = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_scrollbar);
drawableScrollBar.setColorFilter(new PorterDuffColorFilter(getPrimaryColor(), PorterDuff.Mode.SRC_ATOP));
/**** FAB ****/
fabScrollUp.setBackgroundTintList(ColorStateList.valueOf(getAccentColor()));
fabScrollUp.setAlpha(0.7f);
}
private void setDrawerTheme() {
findViewById(R.id.Drawer_Header).setBackgroundColor(getPrimaryColor());
findViewById(R.id.Drawer_Body).setBackgroundColor(getDrawerBackground());
findViewById(R.id.drawer_scrollbar).setBackgroundColor(getDrawerBackground());
findViewById(R.id.Drawer_Body_Divider).setBackgroundColor(getIconColor());
/** TEXT VIEWS **/
int color = getTextColor();
defaultText.setTextColor(color);
drawerSettingText.setTextColor(color);
drawerAboutText.setTextColor(color);
hiddenText.setTextColor(color);
drawerShareText.setTextColor(color);
drawerRateText.setTextColor(color);
drawerUploadText.setTextColor(color);
drawerTrashText.setTextColor(color);
((TextView) findViewById(R.id.Drawer_Default_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_Setting_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_About_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_hidden_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_share_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_rate_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_Upload_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_TrashBin_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_favourite_Item)).setTextColor(color);
/** ICONS **/
color = getIconColor();
defaultIcon.setColor(color);
drawerSettingIcon.setColor(color);
drawerAboutIcon.setColor(color);
hiddenIcon.setColor(color);
drawerShareIcon.setColor(color);
drawerRateIcon.setColor(color);
drawerUploadIcon.setColor(color);
drawerTrashIcon.setColor(color);
favicon.setColor(color);
// Default setting
if (localFolder)
findViewById(R.id.ll_drawer_Default).setBackgroundColor(getHighlightedItemColor());
else
findViewById(R.id.ll_drawer_hidden).setBackgroundColor(getHighlightedItemColor());
tint();
findViewById(R.id.ll_drawer_Setting).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
settings = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
findViewById(R.id.ll_drawer_About).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
about = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
findViewById(R.id.ll_drawer_favourites).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
favourites = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
findViewById(R.id.ll_drawer_uploadhistory).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadHistory = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
findViewById(R.id.ll_drawer_trashbin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
trashbin = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
//toolbar.setTitle("Trash Bin");
}
});
findViewById(R.id.ll_drawer_Default).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
localFolder = true;
findViewById(R.id.ll_drawer_hidden).setBackgroundColor(Color.TRANSPARENT);
findViewById(R.id.ll_drawer_Default).setBackgroundColor(getHighlightedItemColor());
tint();
toolbar.setTitle(getString(R.string.local_folder));
hidden = false;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask(activityContext).execute();
}
});
findViewById(R.id.ll_drawer_hidden).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
localFolder = false;
findViewById(R.id.ll_drawer_Default).setBackgroundColor(Color.TRANSPARENT);
findViewById(R.id.ll_drawer_hidden).setBackgroundColor(getHighlightedItemColor());
tint();
toolbar.setTitle(getString(R.string.hidden_folder));
if (securityObj.isActiveSecurity() && securityObj.isPasswordOnHidden()) {
final boolean[] passco = {false};
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
editTextPassword.setHintTextColor(getResources().getColor(R.color.grey, null));
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
editTextPassword.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void afterTextChanged(Editable editable) {
if(securityObj.getTextInputLayout().getVisibility() == View.VISIBLE && !passco[0]){
securityObj.getTextInputLayout().setVisibility(View.INVISIBLE);
}
else{
passco[0]=false;
}
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
passwordDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), passwordDialog);
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View
.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
hidden = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask(activityContext).execute();
passwordDialog.dismiss();
} else {
passco[0] = true;
securityObj.getTextInputLayout().setVisibility(View.VISIBLE);
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.wrong_password), 0);
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else {
hidden = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask(activityContext).execute();
}
}
});
findViewById(R.id.ll_share_phimpme).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onInviteClicked();
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
findViewById(R.id.ll_rate_phimpme).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String appPackageName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
}
private void onInviteClicked() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.install_phimpme) + "\n " + getString(R.string.invitation_deep_link));
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
//endregion
private void updateSelectedStuff() {
if (albumsMode) {
if (getAlbums().getSelectedCount() == 0) {
clearOverlay();
checkForReveal = true;
swipeRefreshLayout.setEnabled(true);
} else {
appBarOverlay();
swipeRefreshLayout.setEnabled(false);
}
if (editMode)
toolbar.setTitle(getAlbums().getSelectedCount() + "/" + getAlbums().dispAlbums.size());
else {
if (hidden)
toolbar.setTitle(getString(R.string.hidden_folder));
else toolbar.setTitle(getString(R.string.local_folder));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_menu));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
} else {
if (!all_photos) {
if (getAlbum().getSelectedCount() == 0) {
clearOverlay();
checkForReveal = true;
swipeRefreshLayout.setEnabled(true);
} else {
appBarOverlay();
swipeRefreshLayout.setEnabled(false);
}
} else {
if (selectedMedias.size() == 0) {
clearOverlay();
swipeRefreshLayout.setEnabled(true);
} else {
appBarOverlay();
swipeRefreshLayout.setEnabled(false);
}
}
if (editMode) {
if (!all_photos && !fav_photos)
toolbar.setTitle(getAlbum().getSelectedCount() + "/" + getAlbum().getMedia().size());
else if (!fav_photos && all_photos) {
toolbar.setTitle(selectedMedias.size() + "/" + size);
} else if (fav_photos && !all_photos) {
toolbar.setTitle(selectedMedias.size() + "/" + favouriteslist.size());
}
} else {
if (!all_photos && !fav_photos)
toolbar.setTitle(getAlbum().getName());
else if (all_photos && !fav_photos) {
toolbar.setTitle(getString(R.string.all_media));
} else if (fav_photos && !all_photos) {
toolbar.setTitle(getResources().getString(R.string.favourite_title));
}
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
}
}
if (editMode) {
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_clear));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNavigationBar();
finishEditMode();
clearSelectedPhotos();
}
});
}
}
//called from onBackPressed()
private void finishEditMode() {
if (editMode)
enterReveal();
editMode = false;
if (albumsMode) {
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
if (!all_photos) {
getAlbum().clearSelectedPhotos();
mediaAdapter.notifyDataSetChanged();
} else {
clearSelectedPhotos();
mediaAdapter.notifyDataSetChanged();
}
}
invalidateOptionsMenu();
}
private void checkNothing() {
nothingToShow.setTextColor(getTextColor());
nothingToShow.setText(getString(R.string.there_is_nothing_to_show));
nothingToShow.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0) ||
(!albumsMode && getAlbum().getMedia().size() == 0) ? View.VISIBLE : View.GONE);
TextView a = findViewById(R.id.nothing_to_show);
a.setTextColor(getTextColor());
a.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0 && !fav_photos) || (!albumsMode && getAlbum
().getMedia().size() == 0 && !fav_photos) || (fav_photos && favouriteslist.size() == 0) ? View
.VISIBLE : View
.GONE);
starImageView.setVisibility(View.GONE);
}
private void checkNothingFavourites() {
nothingToShow.setTextColor(getTextColor());
nothingToShow.setText(R.string.no_favourites_text);
nothingToShow.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0 && !fav_photos) || (!albumsMode && getAlbum
().getMedia().size() == 0 && !fav_photos) || (fav_photos && favouriteslist.size() == 0) ? View
.VISIBLE : View
.GONE);
noFavMsg.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0 && !fav_photos) || (!albumsMode && getAlbum
().getMedia().size() == 0 && !fav_photos) || (fav_photos && favouriteslist.size() == 0) ? View
.VISIBLE : View
.GONE);
noFavMsg.setText(R.string.no_favourites_message);
noFavMsg.setTextColor(getTextColor());
starImageView.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0 && !fav_photos) || (!albumsMode && getAlbum
().getMedia().size() == 0 && !fav_photos) || (fav_photos && favouriteslist.size() == 0) ? View
.VISIBLE : View
.GONE);
starImageView.setColorFilter(getPrimaryColor());
}
private void showsnackbar(Boolean result) {
if(result) {
SnackBarHandler.show(mDrawerLayout,getApplicationContext().getString(R.string.photo_deleted_msg), navigationView.getHeight());
} else {
SnackBarHandler.show(mDrawerLayout,getApplicationContext().getString(R.string.photo_deletion_failed), navigationView.getHeight());
}
}
private void checkNoSearchResults(String result){
textView.setText(getString(R.string.null_search_result) + " " + '"' + result + '"' );
textView.setTextColor(getTextColor());
textView.setVisibility(View.VISIBLE);
}
//region MENU
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_albums, menu);
MenuItem menuitem = menu.findItem(R.id.search_action);
searchView = (SearchView) MenuItemCompat.getActionView(menuitem);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override public void onFocusChange(final View view, boolean b) {
if (b) {
view.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context
.INPUT_METHOD_SERVICE);
imm.showSoftInput(view.findFocus(), 0);
}
}, 200);
} else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context
.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
if (albumsMode) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return searchTitle(newText);
}
});
menu.findItem(R.id.select_all).setVisible(getAlbums().getSelectedCount() != albumsAdapter.getItemCount() ? true : false);
menu.findItem(R.id.ascending_sort_action).setChecked(getAlbums().getSortingOrder() == SortingOrder.ASCENDING);
switch (getAlbums().getSortingMode()) {
case NAME:
menu.findItem(R.id.name_sort_action).setChecked(true);
break;
case SIZE:
menu.findItem(R.id.size_sort_action).setChecked(true);
break;
case DATE:
default:
menu.findItem(R.id.date_taken_sort_action).setChecked(true);
break;
case NUMERIC:
menu.findItem(R.id.numeric_sort_action).setChecked(true);
break;
}
} else {
getfavouriteslist();
menu.findItem(R.id.select_all).setVisible(getAlbum().getSelectedCount() == mediaAdapter
.getItemCount() || selectedMedias.size() == size || (selectedMedias.size() == favouriteslist.size
() && fav_photos) ? false : true);
menu.findItem(R.id.ascending_sort_action).setChecked(getAlbum().settings.getSortingOrder() == SortingOrder.ASCENDING);
switch (getAlbum().settings.getSortingMode()) {
case NAME:
menu.findItem(R.id.name_sort_action).setChecked(true);
break;
case SIZE:
menu.findItem(R.id.size_sort_action).setChecked(true);
break;
case DATE:
default:
menu.findItem(R.id.date_taken_sort_action).setChecked(true);
break;
case NUMERIC:
menu.findItem(R.id.numeric_sort_action).setChecked(true);
break;
}
}
menu.findItem(R.id.hideAlbumButton).setTitle(hidden ? getString(R.string.unhide) : getString(R.string.hide));
menu.findItem(R.id.delete_action).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_delete));
menu.findItem(R.id.sort_action).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_sort));
menu.findItem(R.id.sharePhotos).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_share));
return true;
}
public boolean searchTitle(String newText) {
if (!fromOnClick) {
String queryText = newText;
queryText = queryText.toLowerCase();
final ArrayList<Album> newList = new ArrayList<>();
for (Album album : albList) {
String name = album.getName().toLowerCase();
if (name.contains(queryText)) {
newList.add(album);
}
}
if(newList.isEmpty()){
checkNoSearchResults(newText);
}
else{
if(textView.getVisibility() == View.VISIBLE){
textView.setVisibility(View.INVISIBLE);
}
}
albumsAdapter.swapDataSet(newList);
} else {
fromOnClick = false;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
if (albumsMode) {
editMode = getAlbums().getSelectedCount() != 0;
menu.setGroupVisible(R.id.album_options_menu, editMode);
menu.setGroupVisible(R.id.photos_option_men, false);
menu.findItem(R.id.all_photos).setVisible(!editMode && !hidden);
menu.findItem(R.id.search_action).setVisible(!editMode);
menu.findItem(R.id.create_gif).setVisible(false);
menu.findItem(R.id.create_zip).setVisible(false);
menu.findItem(R.id.select_all).setVisible(getAlbums().getSelectedCount() != albumsAdapter.getItemCount() ? true : false);
menu.findItem(R.id.settings).setVisible(false);
if (getAlbums().getSelectedCount() >= 1) {
if (getAlbums().getSelectedCount() > 1) {
menu.findItem(R.id.album_details).setVisible(false);
}
if (getAlbums().getSelectedCount() == 1) {
menu.findItem(R.id.search_action).setVisible(false);
}
}
} else {
menu.findItem(R.id.search_action).setVisible(false);
if (!all_photos && !fav_photos) {
editMode = getAlbum().areMediaSelected();
menu.setGroupVisible(R.id.photos_option_men, editMode);
menu.setGroupVisible(R.id.album_options_menu, !editMode);
menu.findItem(R.id.settings).setVisible(!editMode);
menu.findItem(R.id.all_photos).setVisible(false);
menu.findItem(R.id.album_details).setVisible(false);
} else if (all_photos && !fav_photos) {
editMode = selectedMedias.size() != 0;
menu.setGroupVisible(R.id.photos_option_men, editMode);
menu.setGroupVisible(R.id.album_options_menu, !editMode);
menu.findItem(R.id.all_photos).setVisible(false);
menu.findItem(R.id.action_move).setVisible(false);
menu.findItem(R.id.settings).setVisible(!editMode);
menu.findItem(R.id.album_details).setVisible(false);
} else if (!all_photos && fav_photos) {
editMode = selectedMedias.size() != 0;
menu.setGroupVisible(R.id.photos_option_men, editMode);
menu.setGroupVisible(R.id.album_options_menu, !editMode);
menu.findItem(R.id.settings).setVisible(!editMode);
menu.findItem(R.id.create_gif).setVisible(false);
menu.findItem(R.id.create_zip).setVisible(false);
menu.findItem(R.id.album_details).setVisible(false);
menu.findItem(R.id.all_photos).setVisible(false);
}
menu.findItem(R.id.select_all).setVisible(getAlbum().getSelectedCount() == mediaAdapter
.getItemCount() || selectedMedias.size() == size || (selectedMedias.size() == favouriteslist.size
() && fav_photos) ? false : true);
}
togglePrimaryToolbarOptions(menu);
updateSelectedStuff();
if(!albumsMode)
visible = getAlbum().getSelectedCount() > 0;
else
visible = false;
menu.findItem(R.id.action_copy).setVisible(visible);
menu.findItem(R.id.action_move).setVisible((visible || editMode) && !fav_photos);
menu.findItem(R.id.action_add_favourites).setVisible((visible || editMode) && (!albumsMode && !fav_photos));
menu.findItem(R.id.excludeAlbumButton).setVisible(editMode && !all_photos && albumsMode && !fav_photos);
menu.findItem(R.id.zipAlbumButton).setVisible(editMode && !all_photos && albumsMode && !fav_photos && !hidden &&
getAlbums().getSelectedCount() == 1);
menu.findItem(R.id.delete_action).setVisible((!albumsMode || editMode) && (!all_photos || editMode));
if (fav_photos){
menu.findItem(R.id.delete_action).setVisible(editMode);
}
if(fav_photos && favouriteslist.size() == 0 ){
menu.findItem(R.id.delete_action).setVisible(false);
menu.findItem(R.id.sort_action).setVisible(false);
}
menu.findItem(R.id.hideAlbumButton).setVisible(!all_photos && !fav_photos && getAlbums().getSelectedCount() >
0);
menu.findItem(R.id.clear_album_preview).setVisible(!albumsMode && getAlbum().hasCustomCover() && !fav_photos && !all_photos);
menu.findItem(R.id.renameAlbum).setVisible(((albumsMode && getAlbums().getSelectedCount() == 1) ||
(!albumsMode && !editMode)) && (!all_photos && !fav_photos));
if (getAlbums().getSelectedCount() == 1)
menu.findItem(R.id.set_pin_album).setTitle(getAlbums().getSelectedAlbum(0).isPinned() ? getString(R.string.un_pin) : getString(R.string.pin));
menu.findItem(R.id.set_pin_album).setVisible(albumsMode && getAlbums().getSelectedCount() == 1);
menu.findItem(R.id.setAsAlbumPreview).setVisible(!albumsMode && !all_photos && getAlbum()
.getSelectedCount() == 1);
menu.findItem(R.id.affixPhoto).setVisible((!albumsMode && (getAlbum().getSelectedCount() > 1) ||
selectedMedias.size() > 1) && !fav_photos);
if (albumsMode)
menu.findItem(R.id.action_move).setVisible(getAlbums().getSelectedCount() == 1);
return super.onPrepareOptionsMenu(menu);
}
private void togglePrimaryToolbarOptions(final Menu menu) {
menu.setGroupVisible(R.id.general_action, !editMode);
}
//endregion
@Override
public boolean onOptionsItemSelected(MenuItem item) {
getNavigationBar();
switch (item.getItemId()) {
case R.id.all_photos:
if (!all_photos) {
boolean check_security_on_local = true;
check_security_on_local = SP.getBoolean(getString(R.string.preference_use_password_on_folder), check_security_on_local);
if(securityObj.isActiveSecurity() && check_security_on_local){
final boolean[] passco = {false};
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
editTextPassword.setHintTextColor(getResources().getColor(R.color.grey, null));
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
editTextPassword.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void afterTextChanged(Editable editable) {
if(securityObj.getTextInputLayout().getVisibility() == View.VISIBLE && !passco[0]){
securityObj.getTextInputLayout().setVisibility(View.INVISIBLE);
}
else{
passco[0]=false;
}
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
passwordDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), passwordDialog);
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View
.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
all_photos = true;
displayAllMedia(true);
passwordDialog.dismiss();
} else {
passco[0] = true;
securityObj.getTextInputLayout().setVisibility(View.VISIBLE);
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else{
all_photos = true;
displayAllMedia(true);
}
} else {
displayAlbums();
}
return true;
case R.id.album_details:
AlertDialog.Builder detailsDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialog detailsDialog;
detailsDialog =
AlertDialogsHelper.getAlbumDetailsDialog(this, detailsDialogBuilder, getAlbums().getSelectedAlbum(0));
detailsDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string
.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishEditMode();
}
});
detailsDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE}, getAccentColor(), detailsDialog);
return true;
case R.id.select_all:
if (albumsMode) {
getAlbums().selectAllAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
if (!all_photos && !fav_photos) {
getAlbum().selectAllPhotos();
mediaAdapter.notifyDataSetChanged();
} else if(all_photos && !fav_photos){
clearSelectedPhotos();
selectAllPhotos();
mediaAdapter.notifyDataSetChanged();
}
else if(fav_photos && !all_photos){
clearSelectedPhotos();
selectAllPhotos();
Collections.sort(favouriteslist, MediaComparators.getComparator(getAlbum().settings.getSortingMode(),
getAlbum().settings.getSortingOrder()));
mediaAdapter.swapDataSet(favouriteslist, true);
}
}
invalidateOptionsMenu();
return true;
case R.id.create_gif:
new CreateGIFTask().execute();
return true;
case R.id.create_zip:
path = new ArrayList<>();
if(!albumsMode && !all_photos && !fav_photos){
for(Media m: getAlbum().getSelectedMedia()){
path.add(m.getPath());
}
}else if(!albumsMode && all_photos && !fav_photos){
for(Media m: selectedMedias){
path.add(m.getPath());
}
}
new CreateZipTask().execute();
return true;
case R.id.set_pin_album:
getAlbums().getSelectedAlbum(0).settings.togglePin(getApplicationContext());
getAlbums().sortAlbums();
getAlbums().clearSelectedAlbums();
invalidateOptionsMenu();
albumsAdapter.notifyDataSetChanged();
return true;
case R.id.settings:
startActivity(new Intent(LFMainActivity.this, SettingsActivity.class));
return true;
case R.id.hideAlbumButton:
final AlertDialog.Builder hideDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(LFMainActivity.this, hideDialogBuilder,
hidden ? R.string.unhide : R.string.hide,
hidden ? R.string.unhide_album_message : R.string.hide_album_message, null);
hideDialogBuilder.setPositiveButton(getString(hidden ? R.string.unhide : R.string.hide).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (albumsMode) {
if (hidden) getAlbums().unHideSelectedAlbums(getApplicationContext());
else getAlbums().hideSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
if (hidden)
getAlbums().unHideAlbum(getAlbum().getPath(), getApplicationContext());
else
getAlbums().hideAlbum(getAlbum().getPath(), getApplicationContext());
displayAlbums(true);
}
}
});
if (!hidden) {
hideDialogBuilder.setNeutralButton(this.getString(R.string.exclude).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (albumsMode) {
getAlbums().excludeSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
customAlbumsHelper.excludeAlbum(getAlbum().getPath());
displayAlbums(true);
}
}
});
}
hideDialogBuilder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
AlertDialog alertDialog = hideDialogBuilder.create();
alertDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE, DialogInterface.BUTTON_NEUTRAL}, getAccentColor(), alertDialog);
return true;
case R.id.delete_action:
getNavigationBar();
class DeletePhotos extends AsyncTask<String, Integer, Boolean> {
private boolean succ = false;
private int imagesUnfav = 0;
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
//if in album mode, delete selected albums
if (albumsMode) {
if (AlertDialogsHelper.check) {
succ = addToTrash();
if (succ) {
addTrashObjectsToRealm(selectedAlbumMedia);
succ = getAlbums().deleteSelectedAlbums(LFMainActivity.this);
}
} else {
succ = getAlbums().deleteSelectedAlbums(LFMainActivity.this);
}
}
else {
// if in selection mode, delete selected media
if (editMode) {
if (!all_photos && !fav_photos) {
checkForShare(getAlbum().getSelectedMedia());
//clearSelectedPhotos();
if (AlertDialogsHelper.check) {
succ = addToTrash();
if (succ) {
addTrashObjectsToRealm(getAlbum().getSelectedMedia());
}
getAlbum().clearSelectedPhotos();
} else {
succ = getAlbum().deleteSelectedMedia(getApplicationContext());
}
} else if (all_photos && !fav_photos) {
checkForShare(selectedMedias);
// addToTrash();
if (AlertDialogsHelper.check) {
succ = addToTrash();
if (succ) {
addTrashObjectsToRealm(selectedMedias);
}
} else {
for (Media media : selectedMedias) {
String[] projection = {MediaStore.Images.Media._ID};
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[]{media.getPath()};
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c =
contentResolver
.query(queryUri, projection, selection, selectionArgs,
null);
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id =
c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris
.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id);
contentResolver.delete(deleteUri, null, null);
succ = true;
} else {
succ = false;
// File not found in media store DB
}
c.close();
}
}
} else if (!all_photos && fav_photos) {
checkForShare(selectedMedias);
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (int i = 0; i < selectedMedias.size(); i++) {
RealmResults<FavouriteImagesModel> favouriteImagesModels = realm.where
(FavouriteImagesModel.class)
.equalTo("path", selectedMedias.get(i).getPath()).findAll();
imagesUnfav++;
favouriteImagesModels.deleteAllFromRealm();
}
}
});
succ = true;
}
}
// if not in selection mode, delete current album entirely
else if (!editMode) {
if (!fav_photos) {
checkForShare(getAlbum().getMedia());
if (AlertDialogsHelper.check) {
succ = addToTrash();
if (succ) {
addTrashObjectsToRealm(getAlbum().getMedia());
}
//succ = getAlbums().deleteAlbum(getAlbum(), getApplicationContext());
getAlbum().getMedia().clear();
} else {
succ = getAlbums().deleteAlbum(getAlbum(), getApplicationContext());
getAlbum().getMedia().clear();
}
} else {
checkForShare(favouriteslist);
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override public void execute(Realm realm) {
RealmQuery<FavouriteImagesModel> favouriteImagesModelRealmQuery = realm
.where(FavouriteImagesModel.class);
succ = favouriteImagesModelRealmQuery.findAll().deleteAllFromRealm();
favouriteslist.clear();
}
});
}
}
}
return succ;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
// in albumsMode, the selected albums have been deleted.
if (albumsMode) {
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
if (!all_photos && !fav_photos) {
//if all media in current album have been deleted, delete current album too.
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
showsnackbar(succ);
swipeRefreshLayout.setRefreshing(true);
} else
mediaAdapter.swapDataSet(getAlbum().getMedia(), false);
} else if(all_photos && !fav_photos){
clearSelectedPhotos();
listAll = StorageProvider.getAllShownImages(LFMainActivity.this);
media = listAll;
size = listAll.size();
showsnackbar(succ);
Collections.sort(listAll, MediaComparators.getComparator(getAlbum().settings
.getSortingMode(), getAlbum().settings.getSortingOrder()));
mediaAdapter.swapDataSet(listAll, false);
}
else if(fav_photos && !all_photos){
if (imagesUnfav >= 2)
SnackBarHandler.show(mDrawerLayout, imagesUnfav + " " + getResources().getString(R.string.remove_from_favourite));
else
SnackBarHandler.show(mDrawerLayout, getResources().getString(R.string.single_image_removed));
clearSelectedPhotos();
getfavouriteslist();
new FavouritePhotos(activityContext).execute();
}
}
} else requestSdCardPermissions();
invalidateOptionsMenu();
checkNothing();
swipeRefreshLayout.setRefreshing(false);
}
}
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
if(fav_photos && !all_photos){
AlertDialogsHelper.getTextDialog(this, deleteDialog, R.string.remove_from_favourites, R.string.remove_favourites_body, null);
deleteDialog.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
deleteDialog.setPositiveButton(getString(R.string.remove).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
new DeletePhotos().execute();
}
});
AlertDialog alertDialog1=deleteDialog.create();
alertDialog1.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), alertDialog1);
return true;
}else
AlertDialogsHelper.getTextCheckboxDialog(this, deleteDialog, R.string.delete, albumsMode || !editMode ?
R.string.delete_album_message :
R.string.delete_photos_message, null, getResources().getString(R.string.move_to_trashbin), getAccentColor());
deleteDialog.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
deleteDialog.setPositiveButton(getString(R.string.delete).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (securityObj.isActiveSecurity() && securityObj.isPasswordOnDelete()) {
final boolean passco[] = {false};
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
editTextPassword.setHintTextColor(getResources().getColor(R.color.grey, null));
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should be empty. It will be overwritten later
//to avoid dismiss of the dialog on wrong password
}
});
editTextPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override public void afterTextChanged(Editable editable) {
if(securityObj.getTextInputLayout().getVisibility() == View.VISIBLE && !passco[0]){
securityObj.getTextInputLayout().setVisibility(View.INVISIBLE);
}
else{
passco[0]=false;
}
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
passwordDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), passwordDialog);
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if password is correct, call DeletePhotos and perform deletion
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
passwordDialog.dismiss();
new DeletePhotos().execute();
}
// if password is incorrect, don't delete and notify user of incorrect password
else {
passco[0] = true;
securityObj.getTextInputLayout().setVisibility(View.VISIBLE);
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.wrong_password), navigationView.getHeight());
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else {
new DeletePhotos().execute();
}
}
});
AlertDialog alertDialogDelete = deleteDialog.create();
alertDialogDelete.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), alertDialogDelete);
return true;
case R.id.excludeAlbumButton:
final AlertDialog.Builder excludeDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final View excludeDialogLayout = getLayoutInflater().inflate(R.layout.dialog_exclude, null);
TextView textViewExcludeTitle = excludeDialogLayout.findViewById(R.id.text_dialog_title);
TextView textViewExcludeMessage = excludeDialogLayout.findViewById(R.id.text_dialog_message);
final Spinner spinnerParents = excludeDialogLayout.findViewById(R.id.parents_folder);
spinnerParents.getBackground().setColorFilter(getIconColor(), PorterDuff.Mode.SRC_ATOP);
((CardView) excludeDialogLayout.findViewById(R.id.message_card)).setCardBackgroundColor(getCardBackgroundColor());
textViewExcludeTitle.setBackgroundColor(getPrimaryColor());
textViewExcludeTitle.setText(getString(R.string.exclude));
if ((albumsMode && getAlbums().getSelectedCount() > 1)) {
textViewExcludeMessage.setText(R.string.exclude_albums_message);
spinnerParents.setVisibility(View.GONE);
} else {
textViewExcludeMessage.setText(R.string.exclude_album_message);
spinnerParents.setAdapter(getSpinnerAdapter(albumsMode ? getAlbums().getSelectedAlbum(0).getParentsFolders() : getAlbum().getParentsFolders()));
}
textViewExcludeMessage.setTextColor(getTextColor());
excludeDialogBuilder.setView(excludeDialogLayout);
excludeDialogBuilder.setPositiveButton(this.getString(R.string.exclude).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if ((albumsMode && getAlbums().getSelectedCount() > 1)) {
getAlbums().excludeSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
customAlbumsHelper.excludeAlbum(spinnerParents.getSelectedItem().toString());
finishEditMode();
displayAlbums(true);
}
}
});
excludeDialogBuilder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
AlertDialog alertDialogExclude = excludeDialogBuilder.create();
alertDialogExclude.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), alertDialogExclude);
return true;
case R.id.zipAlbumButton:
path = new ArrayList<>();
File folder = new File(getAlbums().getSelectedAlbum(0).getPath() + "/");
File[] fpath = folder.listFiles();
for (int i = 0; i < fpath.length; i++) {
if (fpath[i].getPath().endsWith(".jpg")||fpath[i].getPath().endsWith(".jpeg")||fpath[i].getPath().endsWith(".png")) {
path.add(fpath[i].getPath());
}
}
new ZipAlbumTask().execute();
return true;
case R.id.sharePhotos:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.sent_to_action));
// list of all selected media in current album
ArrayList<Uri> files = new ArrayList<Uri>();
if (!all_photos && !fav_photos) {
for (Media f : getAlbum().getSelectedMedia())
files.add(f.getUri());
} else if (all_photos && !fav_photos) {
for (Media f : selectedMedias)
files.add(f.getUri());
} else if (fav_photos && !all_photos) {
for (Media m : selectedMedias) {
files.add(m.getUri());
}
}
if (!all_photos && !fav_photos) {
for (Media f : getAlbum().getSelectedMedia()) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
UploadHistoryRealmModel uploadHistory;
uploadHistory = realm.createObject(UploadHistoryRealmModel.class);
uploadHistory.setName("OTHERS");
uploadHistory.setPathname(f.getPath());
uploadHistory.setDatetime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()));
uploadHistory.setStatus(getString(R.string.upload_done));
realm.commitTransaction();
Intent result = new Intent();
result.putExtra(Constants.SHARE_RESULT, 0);
setResult(RESULT_OK, result);
}
} else if (all_photos || fav_photos) {
for (Media m : selectedMedias) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
UploadHistoryRealmModel uploadHistory;
uploadHistory = realm.createObject(UploadHistoryRealmModel.class);
uploadHistory.setName("OTHERS");
uploadHistory.setPathname(m.getPath());
uploadHistory.setDatetime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()));
uploadHistory.setStatus(getString(R.string.upload_done));
realm.commitTransaction();
Intent result = new Intent();
result.putExtra(Constants.SHARE_RESULT, 0);
setResult(RESULT_OK, result);
}
}
String extension = files.get(0).getPath().substring(files.get(0).getPath().lastIndexOf('.') + 1);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
if (!all_photos && !fav_photos)
intent.setType(StringUtils.getGenericMIME(getAlbum().getSelectedMedia(0).getMimeType()));
else if (all_photos && !fav_photos)
intent.setType(mimeType);
else if (fav_photos && !all_photos)
intent.setType(mimeType);
finishEditMode();
startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to)));
return true;
case R.id.name_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(NAME);
new SortingUtilsAlbums(activityContext).execute();
} else {
new SortModeSet(activityContext).execute(NAME);
if (!all_photos && !fav_photos) {
new SortingUtilsPhtots(activityContext).execute();
} else if (all_photos && !fav_photos) {
new SortingUtilsListAll(activityContext).execute();
} else if (fav_photos && !all_photos) {
new SortingUtilsFavouritelist(activityContext).execute();
}
}
item.setChecked(true);
return true;
case R.id.date_taken_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(DATE);
new SortingUtilsAlbums(activityContext).execute();
} else {
new SortModeSet(activityContext).execute(DATE);
if (!all_photos && !fav_photos) {
new SortingUtilsPhtots(activityContext).execute();
} else if (all_photos && !fav_photos) {
new SortingUtilsListAll(activityContext).execute();
} else if (fav_photos && !all_photos) {
new SortingUtilsFavouritelist(activityContext).execute();
}
}
item.setChecked(true);
return true;
case R.id.size_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(SIZE);
new SortingUtilsAlbums(activityContext).execute();
} else {
new SortModeSet(activityContext).execute(SIZE);
if (!all_photos && !fav_photos) {
new SortingUtilsPhtots(activityContext).execute();
} else if (all_photos && !fav_photos) {
new SortingUtilsListAll(activityContext).execute();
} else if (fav_photos && !all_photos) {
new SortingUtilsFavouritelist(activityContext).execute();
}
}
item.setChecked(true);
return true;
case R.id.numeric_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(NUMERIC);
new SortingUtilsAlbums(activityContext).execute();
} else {
new SortModeSet(activityContext).execute(NUMERIC);
if (!all_photos && !fav_photos) {
new SortingUtilsPhtots(activityContext).execute();
} else if (all_photos && !fav_photos) {
new SortingUtilsListAll(activityContext).execute();
} else if (fav_photos && !all_photos) {
new SortingUtilsFavouritelist(activityContext).execute();
}
}
item.setChecked(true);
return true;
case R.id.ascending_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingAscending(item.isChecked() ? SortingOrder.DESCENDING : SortingOrder.ASCENDING);
new SortingUtilsAlbums(activityContext).execute();
} else {
getAlbum().setDefaultSortingAscending(getApplicationContext(), item.isChecked() ? SortingOrder.DESCENDING : SortingOrder.ASCENDING);
if (!all_photos && !fav_photos) {
new SortingUtilsPhtots(activityContext).execute();
} else if (all_photos && !fav_photos) {
new SortingUtilsListAll(activityContext).execute();
} else if (fav_photos && !all_photos) {
new SortingUtilsFavouritelist(activityContext).execute();
}
}
item.setChecked(!item.isChecked());
return true;
//region Affix
case R.id.affixPhoto:
//region Async MediaAffix
class affixMedia extends AsyncTask<Affix.Options, Integer, Void> {
private AlertDialog dialog;
@Override
protected void onPreExecute() {
AlertDialog.Builder progressDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
dialog = AlertDialogsHelper.getProgressDialog(LFMainActivity.this, progressDialog,
getString(R.string.affix), getString(R.string.affix_text));
dialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Affix.Options... arg0) {
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
if (!all_photos) {
for (int i = 0; i < getAlbum().getSelectedCount(); i++) {
bitmapArray.add(getBitmap(getAlbum().getSelectedMedia(i).getPath()));
}
} else {
for (int i = 0; i < selectedMedias.size(); i++) {
bitmapArray.add(getBitmap(selectedMedias.get(i).getPath()));
}
}
if (bitmapArray.size() > 1)
Affix.AffixBitmapList(getApplicationContext(), bitmapArray, arg0[0]);
else runOnUiThread(new Runnable() {
@Override
public void run() {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.affix_error), navigationView.getHeight());
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
editMode = false;
if (!all_photos)
getAlbum().clearSelectedPhotos();
else clearSelectedPhotos();
dialog.dismiss();
invalidateOptionsMenu();
mediaAdapter.notifyDataSetChanged();
if (!all_photos)
new PreparePhotosTask(activityContext).execute();
else clearSelectedPhotos();
}
}
//endregion
final AlertDialog.Builder builder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final View dialogLayout = getLayoutInflater().inflate(R.layout.dialog_affix, null);
dialogLayout.findViewById(R.id.affix_title).setBackgroundColor(getPrimaryColor());
((CardView) dialogLayout.findViewById(R.id.affix_card)).setCardBackgroundColor(getCardBackgroundColor());
//ITEMS
final SwitchCompat swVertical = dialogLayout.findViewById(R.id.affix_vertical_switch);
final SwitchCompat swSaveHere = dialogLayout.findViewById(R.id.save_here_switch);
final RadioGroup radioFormatGroup = dialogLayout.findViewById(R.id.radio_format);
final TextView txtQuality = dialogLayout.findViewById(R.id.affix_quality_title);
final SeekBar seekQuality = dialogLayout.findViewById(R.id.seek_bar_quality);
//region THEME STUFF
setScrollViewColor((ScrollView) dialogLayout.findViewById(R.id.affix_scrollView));
/** TextViews **/
int color = getTextColor();
((TextView) dialogLayout.findViewById(R.id.affix_vertical_title)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.compression_settings_title)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.save_here_title)).setTextColor(color);
/** Sub TextViews **/
color = getTextColor();
((TextView) dialogLayout.findViewById(R.id.save_here_sub)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.affix_vertical_sub)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.affix_format_sub)).setTextColor(color);
txtQuality.setTextColor(color);
/** Icons **/
color = getIconColor();
((IconicsImageView) dialogLayout.findViewById(R.id.affix_quality_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.affix_format_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.affix_vertical_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.save_here_icon)).setColor(color);
seekQuality.getProgressDrawable().setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));
seekQuality.getThumb().setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_jpeg));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_png));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_webp));
updateSwitchColor(swVertical, getAccentColor());
updateSwitchColor(swSaveHere, getAccentColor());
//endregion
seekQuality.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
txtQuality.setText(Html.fromHtml(
String.format(Locale.getDefault(), "%s <b>%d</b>", getString(R.string.quality), progress)));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekQuality.setProgress(90); //DEFAULT
swVertical.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateSwitchColor(swVertical, getAccentColor());
}
});
swSaveHere.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateSwitchColor(swSaveHere, getAccentColor());
}
});
builder.setView(dialogLayout);
builder.setPositiveButton(this.getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Bitmap.CompressFormat compressFormat;
switch (radioFormatGroup.getCheckedRadioButtonId()) {
case R.id.radio_jpeg:
default:
compressFormat = Bitmap.CompressFormat.JPEG;
break;
case R.id.radio_png:
compressFormat = Bitmap.CompressFormat.PNG;
break;
case R.id.radio_webp:
compressFormat = Bitmap.CompressFormat.WEBP;
break;
}
Affix.Options options = new Affix.Options(
swSaveHere.isChecked() ? getAlbum().getPath() : Affix.getDefaultDirectoryPath(),
compressFormat,
seekQuality.getProgress(),
swVertical.isChecked());
new affixMedia().execute(options);
}
});
builder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
AlertDialog affixDialog = builder.create();
affixDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE}, getAccentColor(), affixDialog);
return true;
//endregion
case R.id.action_move:
final Snackbar[] snackbar = {null};
final ArrayList<Media> dr = getselecteditems();
final String[] pathofalbum = {null};
bottomSheetDialogFragment = new SelectAlbumBottomSheet();
bottomSheetDialogFragment.setTitle(getString(R.string.move_to));
if (!albumsMode) {
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(final String path) {
final ArrayList<Media> stringio = storeTemporaryphotos(path);
pathofalbum[0] = path;
swipeRefreshLayout.setRefreshing(true);
int numberOfImagesMoved;
if ((numberOfImagesMoved = getAlbum().moveSelectedMedia(getApplicationContext(), path)) > 0) {
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
}
mediaAdapter.swapDataSet(getAlbum().getMedia(), false);
finishEditMode();
invalidateOptionsMenu();
checkForFavourites(path, dr);
checkDescription(path, dr);
if (numberOfImagesMoved > 1){
snackbar[0] = SnackBarHandler.showWithBottomMargin2(mDrawerLayout, getString(R.string.photos_moved_successfully), navigationView.getHeight(), Snackbar.LENGTH_SHORT);
snackbar[0].setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
getAlbum().moveAllMedia(getApplicationContext(), getAlbum().getPath(), stringio);
}
});
snackbar[0].show();
}
else{
Snackbar snackbar1 = SnackBarHandler.showWithBottomMargin2(mDrawerLayout, getString(R.string.photo_moved_successfully), navigationView.getHeight(), Snackbar.LENGTH_SHORT);
snackbar1.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
getAlbum().moveAllMedia(getApplicationContext(), getAlbum().getPath(), stringio);
}
});
snackbar1.show();
}
} else if (numberOfImagesMoved == -1 && getAlbum().getPath().equals(path)) {
//moving to the same folder
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
alertDialog.setCancelable(false);
AlertDialogsHelper.getTextDialog(LFMainActivity.this, alertDialog, R.string.move_to, R.string.move, null);
alertDialog.setNeutralButton(getString(R.string.make_copies).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new CopyPhotos(path, true, false, activityContext).execute();
}
});
alertDialog.setPositiveButton(getString(R.string.cancel).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialog.setNegativeButton(getString(R.string.replace).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
finishEditMode();
invalidateOptionsMenu();
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.photo_moved_successfully), navigationView.getHeight());
}
});
AlertDialog alert = alertDialog.create();
alert.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE, DialogInterface.BUTTON_NEUTRAL}, getAccentColor(), alert);
} else
requestSdCardPermissions();
swipeRefreshLayout.setRefreshing(false);
bottomSheetDialogFragment.dismiss();
}
});
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
} else {
AlertDialog.Builder alertDialogMoveAll = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
alertDialogMoveAll.setCancelable(false);
AlertDialogsHelper.getTextDialog(LFMainActivity.this, alertDialogMoveAll, R.string.move_to, R.string.move_all_photos, null);
alertDialogMoveAll.setPositiveButton(R.string.ok_action, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
});
alertDialogMoveAll.setNegativeButton(getString(R.string.cancel).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(String path) {
swipeRefreshLayout.setRefreshing(true);
if (getAlbums().moveSelectedAlbum(LFMainActivity.this, path)) {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.moved_target_folder_success), SnackBarHandler.LONG);
getAlbums().deleteSelectedAlbums(LFMainActivity.this);
getAlbums().clearSelectedAlbums();
new PrepareAlbumTask(activityContext).execute();
} else {
requestSdCardPermissions();
swipeRefreshLayout.setRefreshing(false);
invalidateOptionsMenu();
}
bottomSheetDialogFragment.dismiss();
}
});
AlertDialog dialog = alertDialogMoveAll.create();
dialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface
.BUTTON_NEGATIVE}, getAccentColor(), dialog);
}
return true;
case R.id.action_add_favourites:
new AddToFavourites().execute();
return true;
case R.id.action_copy:
bottomSheetDialogFragment = new SelectAlbumBottomSheet();
bottomSheetDialogFragment.setTitle(getString(R.string.copy_to));
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(String path) {
new CopyPhotos(path, false, true, activityContext).execute();
bottomSheetDialogFragment.dismiss();
}
});
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
return true;
case R.id.renameAlbum:
AlertDialog.Builder renameDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextNewName = new EditText(getApplicationContext());
editTextNewName.setText(albumsMode ? getAlbums().getSelectedAlbum(0).getName() : getAlbum().getName());
editTextNewName.setSelectAllOnFocus(true);
editTextNewName.setHint(R.string.description_hint);
editTextNewName.setHintTextColor(ContextCompat.getColor(getApplicationContext(), R.color.grey));
editTextNewName.setHighlightColor(ContextCompat.getColor(getApplicationContext(), R.color.cardview_shadow_start_color));
editTextNewName.selectAll();
editTextNewName.setSingleLine(false);
final String albumName = albumsMode ? getAlbums().getSelectedAlbum(0).getName() : getAlbum().getName();
AlertDialogsHelper.getInsertTextDialog(LFMainActivity.this, renameDialogBuilder,
editTextNewName, R.string.rename_album, null);
renameDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
renameDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog
}
});
final AlertDialog renameDialog = renameDialogBuilder.create();
renameDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION);
editTextNewName.setSelection(editTextNewName.getText().toString().length());
renameDialog.show();
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE, DialogInterface
.BUTTON_NEGATIVE}, getAccentColor(), renameDialog);
renameDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE}, ContextCompat.getColor(LFMainActivity.this, R.color.grey), renameDialog);
editTextNewName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//empty method body
}
@Override
public void afterTextChanged(Editable editable) {
if (TextUtils.isEmpty(editable)) {
// Disable ok button
renameDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(false);
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE}, ContextCompat.getColor(LFMainActivity.this, R.color.grey), renameDialog);
} else {
// Something into edit text. Enable the button.
renameDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(true);
AlertDialogsHelper.setButtonTextColor(new int[]{DialogInterface.BUTTON_POSITIVE}, getAccentColor(),
renameDialog);
}
}
});
renameDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View dialog) {
boolean rename = false;
if (editTextNewName.length() != 0) {
swipeRefreshLayout.setRefreshing(true);
boolean success = false;
if (albumsMode) {
if (!editTextNewName.getText().toString().equals(albumName)) {
int index = getAlbums().dispAlbums.indexOf(getAlbums().getSelectedAlbum(0));
getAlbums().getAlbum(index).updatePhotos(getApplicationContext());
success = getAlbums().getAlbum(index).renameAlbum(getApplicationContext(),
editTextNewName.getText().toString());
albumsAdapter.notifyItemChanged(index);
} else {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.rename_no_change), navigationView.getHeight());
rename = true;
}
} else {
if (!editTextNewName.getText().toString().equals(albumName)) {
success = getAlbum().renameAlbum(getApplicationContext(), editTextNewName.getText().toString());
toolbar.setTitle(getAlbum().getName());
mediaAdapter.notifyDataSetChanged();
} else {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.rename_no_change), navigationView.getHeight());
rename = true;
}
}
renameDialog.dismiss();
if (success) {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.rename_succes), navigationView.getHeight());
getAlbums().clearSelectedAlbums();
invalidateOptionsMenu();
} else if (!rename) {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.rename_error), navigationView.getHeight());
requestSdCardPermissions();
}
swipeRefreshLayout.setRefreshing(false);
} else {
SnackBarHandler.showWithBottomMargin(mDrawerLayout, getString(R.string.insert_something), navigationView.getHeight());
editTextNewName.requestFocus();
}
}
});
return true;
case R.id.clear_album_preview:
if (!albumsMode) {
getAlbum().removeCoverAlbum(getApplicationContext());
}
return true;
case R.id.setAsAlbumPreview:
if (!albumsMode) {
getAlbum().setSelectedPhotoAsPreview(getApplicationContext());
finishEditMode();
}
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
private void checkForShare(ArrayList<Media> media){
realm = Realm.getDefaultInstance();
RealmQuery<UploadHistoryRealmModel> uploadHistoryRealmModelRealmQuery = realm.where(UploadHistoryRealmModel.class);
for(Media m: media){
checkForUploadHistory(m.getPath(), uploadHistoryRealmModelRealmQuery);
}
}
private void checkForUploadHistory(String path, RealmQuery<UploadHistoryRealmModel> query){
for(int i = 0; i < query.count(); i++){
if(query.findAll().get(i).getPathname().equals(path) && backupHistory(path)){
uploadToRealm(path);
}
}
}
private boolean backupHistory(String path){
boolean succ = false;
File file = new File(Environment.getExternalStorageDirectory() + "/" +".nomedia/" + "uploadHistory");
if(file.exists() && file.isDirectory()){
succ = ContentHelper.copyFile(getApplicationContext(), new File(path), file);
//succ = getAlbum().moveAnyMedia(getApplicationContext(), file.getAbsolutePath(), path);
} else {
if(file.mkdir()){
succ = ContentHelper.copyFile(getApplicationContext(), new File(path), file);
}
}
return succ;
}
private void uploadToRealm(String path){
RealmResults<UploadHistoryRealmModel> realmModels = realm.where(UploadHistoryRealmModel.class).equalTo("pathname", path).findAll();
//RealmResults<UploadHistoryRealmModel> realmModels = realm.where(UploadHistoryRealmModel.class).findAll();
String newpath = Environment.getExternalStorageDirectory() + "/" + ".nomedia/" + "uploadHistory/" + path.substring(path.lastIndexOf("/") + 1);
realm.beginTransaction();
UploadHistoryRealmModel uploadHistoryRealmModel = realm.createObject(UploadHistoryRealmModel.class);
uploadHistoryRealmModel.setDatetime(realmModels.get(0).getDatetime());
uploadHistoryRealmModel.setName(realmModels.get(0).getName());
uploadHistoryRealmModel.setPathname(newpath);
uploadHistoryRealmModel.setStatus(realmModels.get(0).getStatus());
realm.commitTransaction();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<UploadHistoryRealmModel> realmModels = realm.where(UploadHistoryRealmModel.class).findAll();
realmModels.deleteAllFromRealm();
}
});
}
private ArrayList<Media> storeTemporaryphotos(String path){
ArrayList<Media> temp = new ArrayList<>();
if(!all_photos && !fav_photos && editMode){
for(Media m: getAlbum().getSelectedMedia()){
String name = m.getPath().substring(m.getPath().lastIndexOf("/") + 1);
temp.add(new Media(path + "/" + name));
}
}
return temp;
}
private void checkDescription(String newpath, ArrayList<Media> selecteditems){
for(int i = 0; i < selecteditems.size(); i++){
getDescriptionPaths(selecteditems.get(i).getPath(), newpath);
}
}
private void performRealmAction(final ImageDescModel descModel, String newpath){
realm = Realm.getDefaultInstance();
int index = descModel.getId().lastIndexOf("/");
String name = descModel.getId().substring(index + 1);
String newpathy = newpath + "/" + name;
realm.beginTransaction();
ImageDescModel imageDescModel = realm.createObject(ImageDescModel.class, newpathy);
imageDescModel.setTitle(descModel.getTitle());
realm.commitTransaction();
realm.executeTransaction(new Realm.Transaction() {
@Override public void execute(Realm realm) {
RealmResults<ImageDescModel> result = realm.where(ImageDescModel.class).equalTo
("path", descModel.getId()).findAll();
result.deleteAllFromRealm();
}
});
}
private void getDescriptionPaths(String patjs, String newpth){
realm = Realm.getDefaultInstance();
RealmQuery<ImageDescModel> realmQuery = realm.where(ImageDescModel.class);
for(int i = 0; i < realmQuery.count(); i++) {
if (realmQuery.findAll().get(i).getId().equals(patjs)) {
performRealmAction(realmQuery.findAll().get(i), newpth);
break;
}
}
}
private void checkForFavourites(String path, ArrayList<Media> selectedphotos){
for(Media m: selectedphotos){
checkIfFav(m.getPath(), path);
}
}
private void checkIfFav(String currentpath, String newpath){
realm = Realm.getDefaultInstance();
RealmQuery<FavouriteImagesModel> favouriteImagesModelRealmQuery = realm.where(FavouriteImagesModel.class);
for(int i = 0; i < favouriteImagesModelRealmQuery.count(); i++){
if(favouriteImagesModelRealmQuery.findAll().get(i).getPath().equals(currentpath)){
performAddToFavOp(favouriteImagesModelRealmQuery.findAll().get(i), newpath);
break;
}
}
}
private void performAddToFavOp(final FavouriteImagesModel favouriteImagesModel, String newpath) {
realm = Realm.getDefaultInstance();
int index = favouriteImagesModel.getPath().lastIndexOf("/");
String name = favouriteImagesModel.getPath().substring(index + 1);
String newpathy = newpath + "/" + name;
realm.beginTransaction();
FavouriteImagesModel favouriteImagesModel1 = realm.createObject(FavouriteImagesModel.class, newpathy);
ImageDescModel q =
realm.where(ImageDescModel.class).equalTo("path", favouriteImagesModel.getPath()).findFirst();
if (q != null) {
favouriteImagesModel1.setDescription(q.getTitle());
} else {
favouriteImagesModel1.setDescription(" ");
}
realm.commitTransaction();
realm.executeTransaction(new Realm.Transaction() {
@Override public void execute(Realm realm) {
RealmResults<FavouriteImagesModel> result = realm.where(FavouriteImagesModel.class).equalTo
("path", favouriteImagesModel.getPath()).findAll();
result.deleteAllFromRealm();
}
});
}
private boolean addToTrash(){
int no = 0;
boolean succ = false;
final ArrayList<Media> media1 = storeDeletedFilesTemporarily();
File file = new File(Environment.getExternalStorageDirectory() + "/" + ".nomedia");
if(file.exists() && file.isDirectory()){
if (albumsMode) {
no = getAlbum().moveAllMedia(getApplicationContext(), file.getAbsolutePath(), selectedAlbumMedia);
}
else if(!all_photos && !fav_photos && editMode){
no = getAlbum().moveSelectedMedia(getApplicationContext(), file.getAbsolutePath());
}else if(all_photos && !fav_photos && editMode){
no = getAlbum().moveAllMedia(getApplicationContext(), file.getAbsolutePath(), selectedMedias);
}else if(!editMode && !all_photos && !fav_photos){
no = getAlbum().moveAllMedia(getApplicationContext(), file.getAbsolutePath(), getAlbum().getMedia());
}
if(no > 0){
succ = true;
if(no == 1){
Snackbar snackbar = SnackBarHandler.showWithBottomMargin2(mDrawerLayout, String.valueOf(no) + " " + getString(R.string
.trashbin_move_onefile),
navigationView.getHeight
(), Snackbar.LENGTH_SHORT);
snackbar.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
if (albumsMode) {
undoAlbumDeletion(media1);
}else
getAlbum().moveAllMedia(getApplicationContext(), getAlbum().getPath(), media1);
refreshListener.onRefresh();
}
});
snackbar.show();
}else{
Snackbar snackbar = SnackBarHandler.showWithBottomMargin2(mDrawerLayout, String.valueOf(no) + " " + getString(R.string
.trashbin_move_onefile),
navigationView.getHeight
(), Snackbar.LENGTH_SHORT);
snackbar.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
if (albumsMode) {
undoAlbumDeletion(media1);
}else
getAlbum().moveAllMedia(getApplicationContext(), getAlbum().getPath(), media1);
refreshListener.onRefresh();
}
});
snackbar.show();
}
}else{
SnackBarHandler.showWithBottomMargin(mDrawerLayout, String.valueOf(no) + " " + getString(R.string
.trashbin_move_error),
navigationView.getHeight
());
}
}else{
if(file.mkdir()){
if (albumsMode) {
no = getAlbum().moveAllMedia(getApplicationContext(), file.getAbsolutePath(), selectedAlbumMedia);
}else if(!all_photos && !fav_photos && editMode){
no = getAlbum().moveSelectedMedia(getApplicationContext(), file.getAbsolutePath());
}else if(all_photos && !fav_photos && editMode){
no = getAlbum().moveAllMedia(getApplicationContext(), file.getAbsolutePath(), selectedMedias);
}else if(!editMode && !all_photos && !fav_photos){
no = getAlbum().moveAllMedia(getApplicationContext(), file.getAbsolutePath(), getAlbum().getMedia());
}
// no = getAlbum().moveSelectedMedia(getApplicationContext(), file.getAbsolutePath());
if(no > 0){
succ = true;
if(no == 1){
Snackbar snackbar = SnackBarHandler.showWithBottomMargin(mDrawerLayout, String.valueOf(no) + " " + getString(R.string
.trashbin_move_onefile),
navigationView.getHeight
());
snackbar.setAction(R.string.ok_action, new View.OnClickListener() {
@Override
public void onClick(View view) {
if (albumsMode) {
undoAlbumDeletion(media1);
}
refreshListener.onRefresh();
}
});
}else{
Snackbar snackbar = SnackBarHandler.showWithBottomMargin(mDrawerLayout, String.valueOf(no) + " " + getString(R.string
.trashbin_move),
navigationView.getHeight
());
snackbar.setAction(R.string.ok_action, new View.OnClickListener() {
@Override
public void onClick(View view) {
if (albumsMode) {
undoAlbumDeletion(media1);
}
refreshListener.onRefresh();
}
});
}
}else{
SnackBarHandler.showWithBottomMargin(mDrawerLayout, String.valueOf(no) + " " + getString(R.string
.trashbin_move_error),
navigationView.getHeight
());
}
}
}
// clearSelectedPhotos();
return succ;
}
private ArrayList<Media> storeDeletedFilesTemporarily(){
ArrayList<Media> deletedImages = new ArrayList<>();
if(albumsMode) {
selectedAlbumMedia.clear();
for (Album selectedAlbum : getAlbums().getSelectedAlbums()) {
checkAndAddFolder(new File(selectedAlbum.getPath()), deletedImages);
}
}else if(!all_photos && !fav_photos && editMode){
for(Media m: getAlbum().getSelectedMedia()){
String name = m.getPath().substring(m.getPath().lastIndexOf("/") + 1);
deletedImages.add(new Media(Environment.getExternalStorageDirectory() + "/" + ".nomedia" + "/" + name));
}
} else if(all_photos && !fav_photos && editMode){
for(Media m: selectedMedias){
String name = m.getPath().substring(m.getPath().lastIndexOf("/") + 1);
deletedImages.add(new Media(Environment.getExternalStorageDirectory() + "/" + ".nomedia" + "/" + name));
}
}
return deletedImages;
}
private void addTrashObjectsToRealm(ArrayList<Media> media){
String trashbinpath = Environment.getExternalStorageDirectory() + "/" + ".nomedia";
realm = Realm.getDefaultInstance();
for(int i = 0; i < media.size(); i++){
int index = media.get(i).getPath().lastIndexOf("/");
String name = media.get(i).getPath().substring(index + 1);
realm.beginTransaction();
String trashpath = trashbinpath + "/" + name;
TrashBinRealmModel trashBinRealmModel = realm.createObject(TrashBinRealmModel.class, trashpath);
trashBinRealmModel.setOldpath(media.get(i).getPath());
trashBinRealmModel.setDatetime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()));
trashBinRealmModel.setTimeperiod("null");
realm.commitTransaction();
}
}
private void checkAndAddFolder(File dir, ArrayList<Media> deletedImages) {
File[] files = dir.listFiles(new ImageFileFilter(false));
if (files != null && files.length > 0) {
for (File file : files) {
selectedAlbumMedia.add(new Media(file.getAbsolutePath()));
String name = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/") + 1);
Media media = new Media(Environment.getExternalStorageDirectory() + "/" + ".nomedia" + "/" +name );
deletedImages.add(media);
}
}
}
private void undoAlbumDeletion(ArrayList<Media> deleteImages) {
for (int i = 0; i < deleteImages.size(); i++) {
String oldPath = selectedAlbumMedia.get(i).getPath();
String oldFolder = oldPath.substring(0, oldPath.lastIndexOf("/"));
if (restoreMove(LFMainActivity.this, deleteImages.get(i).getPath(), oldFolder)) {
String datafrom = deleteImages.get(i).getPath();
scanFile(context, new String[]{ datafrom, StringUtils.getPhotoPathMoved
(datafrom,oldFolder) });
}
}
for (int i = 0; i < deleteImages.size(); i++) {
removeFromRealm(deleteImages.get(i).getPath());
}
refreshListener.onRefresh();
}
private boolean restoreMove(Context context, String source, String targetDir){
File from = new File(source);
File to = new File(targetDir);
return ContentHelper.moveFile(context, from, to);
}
private void removeFromRealm(String path){
Realm realm = Realm.getDefaultInstance();
RealmResults<TrashBinRealmModel> result = realm.where(TrashBinRealmModel.class).equalTo
("trashbinpath", path).findAll();
realm.beginTransaction();
result.deleteAllFromRealm();
realm.commitTransaction();
}
private static class SortModeSet extends AsyncTask<SortingMode, Void, Void> {
private WeakReference<LFMainActivity> reference;
public SortModeSet(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected Void doInBackground(SortingMode... sortingModes) {
for (Album a : getAlbums().dispAlbums) {
if (a.settings.getSortingMode().getValue() != sortingModes[0].getValue()) {
a.setDefaultSortingMode(reference.get(), sortingModes[0]);
}
}
return null;
}
}
public Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap bitmap = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = bitmap.getHeight();
int width = bitmap.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x,
(int) y, true);
bitmap.recycle();
bitmap = scaledBitmap;
System.gc();
} else {
bitmap = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " + bitmap.getWidth() + ", height: " +
bitmap.getHeight());
return bitmap;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return null;
}
}
public void getNavigationBar() {
if (editMode && hidenav) {
showNavigationBar();
hidenav = false;
}
}
//to copy from all photos.
private boolean copyfromallphotos(Context context, String folderPath) {
boolean success = false;
for (Media m : selectedMedias) {
try {
File from = new File(m.getPath());
File to = new File(folderPath);
if (success = ContentHelper.copyFile(context, from, to))
scanFile(context, new String[]{StringUtils.getPhotoPathMoved(m.getPath(), folderPath)});
} catch (Exception e) {
e.printStackTrace();
}
}
return success;
}
public void scanFile(Context context, String[] path) {
MediaScannerConnection.scanFile(context, path, null, null);
}
/**
* If we are in albumsMode, make the albums recyclerView visible. If we are not, make media recyclerView visible.
*
* @param albumsMode it indicates whether we are in album selection mode or not
*/
private void toggleRecyclersVisibility(boolean albumsMode) {
rvAlbums.setVisibility(albumsMode ? View.VISIBLE : View.GONE);
rvMedia.setVisibility(albumsMode ? View.GONE : View.VISIBLE);
nothingToShow.setVisibility(View.GONE);
starImageView.setVisibility(View.GONE);
noFavMsg.setVisibility(View.GONE);
if (albumsMode)
fabScrollUp.hide();
//touchScrollBar.setScrollBarHidden(albumsMode);
}
private void tint() {
if (localFolder) {
defaultIcon.setColor(getPrimaryColor());
defaultText.setTextColor(getPrimaryColor());
hiddenIcon.setColor(getIconColor());
hiddenText.setTextColor(getTextColor());
} else {
hiddenIcon.setColor(getPrimaryColor());
hiddenText.setTextColor(getPrimaryColor());
defaultIcon.setColor(getIconColor());
defaultText.setTextColor(getTextColor());
}
}
/**
* handles back presses.
* If search view is open, back press will close it.
* If we are currently in selection mode, back press will take us out of selection mode.
* If we are not in selection mode but in albumsMode and the drawer is open, back press will close it.
* If we are not in selection mode but in albumsMode and the drawer is closed, finish the activity.
* If we are neither in selection mode nor in albumsMode, display the albums again.
*/
@Override
public void onBackPressed() {
checkForReveal = true;
if (!searchView.isIconified())
searchView.setIconified(true);
if ((editMode && all_photos) || (editMode && fav_photos))
clearSelectedPhotos();
getNavigationBar();
if (editMode) finishEditMode();
else {
if (albumsMode) {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
mDrawerLayout.closeDrawer(GravityCompat.START);
else {
if (doubleBackToExitPressedOnce && isTaskRoot())
finish();
else if (isTaskRoot()) {
doubleBackToExitPressedOnce = true;
View rootView = LFMainActivity.this.getWindow().getDecorView().findViewById(android.R.id.content);
Snackbar snackbar = Snackbar
.make(rootView, R.string.press_back_again_to_exit, Snackbar.LENGTH_LONG)
.setAction(R.string.exit, new View.OnClickListener() {
@Override
public void onClick(View view) {
finishAffinity();
}
})
.setActionTextColor(getAccentColor());
View sbView = snackbar.getView();
final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) sbView.getLayoutParams();
params.setMargins(params.leftMargin,
params.topMargin,
params.rightMargin,
params.bottomMargin + navigationView.getHeight());
sbView.setLayoutParams(params);
snackbar.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else
super.onBackPressed();
}
} else {
displayAlbums();
}
}
}
private class CreateGIFTask extends AsyncTask<Void, Void, Void>{
private ArrayList<Bitmap> bitmaps = new ArrayList<>();
@Override protected void onPreExecute() {
super.onPreExecute();
swipeRefreshLayout.setRefreshing(true);
}
@Override protected Void doInBackground(Void... voids) {
if(!albumsMode && !all_photos && !fav_photos){
for(Media m: getAlbum().getSelectedMedia()){
bitmaps.add(getBitmap(m.getPath()));
}
}else if(!albumsMode && all_photos && !fav_photos){
for(Media m: selectedMedias){
bitmaps.add(getBitmap(m.getPath()));
}
}
byte[] bytes = createGIFFromImages(bitmaps);
File file = new File(Environment.getExternalStorageDirectory() + "/" + "Phimpme_gifs");
DateFormat dateFormat = new SimpleDateFormat("ddMMyy_HHmm");
String date = dateFormat.format(Calendar.getInstance().getTime());
if(file.exists() && file.isDirectory()){
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream(file.getPath() + "/" + "GIF_"+date+".gif");
outStream.write(bytes);
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}else {
if (file.mkdir()) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file.getPath() + "/" + "GIF_"+date+".gif");
outStream.write(bytes);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
@Override protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(!albumsMode && !all_photos && !fav_photos){
getAlbum().clearSelectedPhotos();
}else if(!albumsMode && all_photos && !fav_photos){
clearSelectedPhotos();
}
swipeRefreshLayout.setRefreshing(false);
}
}
private byte[] createGIFFromImages(ArrayList<Bitmap> bitmaps){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
private class CreateZipTask extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
swipeRefreshLayout.setRefreshing(true);
NotificationHandler.make(R.string.Images, R.string.zip_fol, R.drawable.ic_archive_black_24dp);
}
@Override
protected String doInBackground(Void... voids) {
DateFormat dateFormat = new SimpleDateFormat("ddMMyy_HHmm");
String dateAndTime = dateFormat.format(Calendar.getInstance().getTime());
try {
double c = 0.0;
File file = new File(Environment.getExternalStorageDirectory() + "/" + "Phimpme_ImageZip");
FileOutputStream dest = null;
if(file.exists() && file.isDirectory()){
try{
dest = new FileOutputStream(file.getPath() + "/" + "ZIP_"+dateAndTime+".zip");
}catch(Exception e){
e.printStackTrace();
}
}else {
if (file.mkdir()) {
dest = null;
try {
dest = new FileOutputStream(file.getPath() + "/" + "ZIP_"+dateAndTime+".zip");
} catch (Exception e) {
e.printStackTrace();
}
}
}
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < path.size(); i++) {
FileInputStream fi = new FileInputStream(path.get(i));
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(path.get(i).substring(path.get(i).lastIndexOf("/") + 1));
out.putNextEntry(entry);
c++;
if ((int) ((c / size) * 100) > 100) {
NotificationHandler.actionProgress((int) c, path.size(), 100, R.string.zip_operation);
} else {
NotificationHandler.actionProgress((int) c, path.size(), (int) ((c / path.size()) * 100), R.string
.zip_operation);
}
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
if (isCancelled()) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return dateAndTime;
}
@Override
protected void onPostExecute(String dateAndTime) {
super.onPostExecute(dateAndTime);
NotificationHandler.actionPassed(R.string.zip_completion);
String path = "ZIP: "+dateAndTime+".zip";
SnackBarHandler.show(mDrawerLayout, getResources().getString(R.string.zip_location) +
path);
if(!albumsMode && !all_photos && !fav_photos){
getAlbum().clearSelectedPhotos();
}
else if(!albumsMode && all_photos && !fav_photos){
clearSelectedPhotos();
}
swipeRefreshLayout.setRefreshing(false);
}
}
private class ZipAlbumTask extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
NotificationHandler.make(R.string.folder, R.string.zip_fol, R.drawable.ic_archive_black_24dp);
}
@Override
protected Void doInBackground(Void... voids) {
try {
double c = 0.0;
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(getAlbums().getSelectedAlbum(0).getParentsFolders().get
(1) + "/" + getAlbums().getSelectedAlbum(0).getName() +
".zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < path.size(); i++) {
FileInputStream fi = new FileInputStream(path.get(i));
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(path.get(i).substring(path.get(i).lastIndexOf("/") + 1));
out.putNextEntry(entry);
c++;
if ((int) ((c / size) * 100) > 100) {
NotificationHandler.actionProgress((int) c, path.size(), 100, R.string.zip_operation);
} else {
NotificationHandler.actionProgress((int) c, path.size(), (int) ((c / path.size()) * 100), R.string
.zip_operation);
}
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
if (isCancelled()) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
NotificationHandler.actionPassed(R.string.zip_completion);
String path = getAlbums().getSelectedAlbum(0).getParentsFolders().get(1) + getAlbums().getSelectedAlbum
(0).getName() + ".zip";
SnackBarHandler.show(mDrawerLayout, getResources().getString(R.string.zip_location) +
path);
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
}
private static class PrepareAlbumTask extends AsyncTask<Void, Integer, Void> {
private WeakReference<LFMainActivity> reference;
PrepareAlbumTask(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
asyncActivityRef.toggleRecyclersVisibility(true);
if(!asyncActivityRef.navigationView.isShown()){
asyncActivityRef.navigationView.setVisibility(View.VISIBLE);
}
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
LFMainActivity asynActivityRef = reference.get();
getAlbums().loadAlbums(asynActivityRef.getApplicationContext(), asynActivityRef.hidden);
return null;
}
@Override
protected void onPostExecute(Void result) {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.albumsAdapter.swapDataSet(getAlbums().dispAlbums);
asyncActivityRef.albList = new ArrayList<>();
asyncActivityRef.populateAlbum();
asyncActivityRef.checkNothing();
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
getAlbums().saveBackup(asyncActivityRef);
asyncActivityRef.invalidateOptionsMenu();
asyncActivityRef.finishEditMode();
}
}
private static class PreparePhotosTask extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
PreparePhotosTask(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
// Declaring globally in Async might lead to leakage of the context
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
asyncActivityRef.toggleRecyclersVisibility(false);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
reference.get().getAlbum().updatePhotos(reference.get());
return null;
}
@Override
protected void onPostExecute(Void result) {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.mediaAdapter.swapDataSet(asyncActivityRef.getAlbum().getMedia(), false);
if (!asyncActivityRef.hidden)
HandlingAlbums.addAlbumToBackup(asyncActivityRef, reference.get().getAlbum());
asyncActivityRef.checkNothing();
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.invalidateOptionsMenu();
asyncActivityRef.finishEditMode();
}
}
private static class PrepareAllPhotos extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
PrepareAllPhotos(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
asyncActivityRef.toggleRecyclersVisibility(false);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.getAlbum().updatePhotos(asyncActivityRef);
return null;
}
@Override
protected void onPostExecute(Void result) {
LFMainActivity asyncActivityRef = reference.get();
listAll = StorageProvider.getAllShownImages(asyncActivityRef);
asyncActivityRef.size = listAll.size();
Collections.sort(listAll, MediaComparators.getComparator(asyncActivityRef.getAlbum().settings.getSortingMode(),
asyncActivityRef.getAlbum().settings.getSortingOrder()));
asyncActivityRef.mediaAdapter.swapDataSet(listAll, false);
if (!asyncActivityRef.hidden)
HandlingAlbums.addAlbumToBackup(asyncActivityRef, asyncActivityRef.getAlbum());
asyncActivityRef.checkNothing();
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.invalidateOptionsMenu();
asyncActivityRef.finishEditMode();
asyncActivityRef.toolbar.setTitle(asyncActivityRef.getString(R.string.all_media));
asyncActivityRef.clearSelectedPhotos();
}
}
private static class FavouritePhotos extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
FavouritePhotos(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
asyncActivityRef.toggleRecyclersVisibility(false);
asyncActivityRef.navigationView.setVisibility(View.INVISIBLE);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.getAlbum().updatePhotos(asyncActivityRef);
return null;
}
@Override
protected void onPostExecute(Void result) {
LFMainActivity asyncActivityRef = reference.get();
Collections.sort(asyncActivityRef.favouriteslist, MediaComparators.getComparator(asyncActivityRef.getAlbum().settings.getSortingMode(),
asyncActivityRef.getAlbum().settings.getSortingOrder()));
asyncActivityRef.mediaAdapter.swapDataSet(asyncActivityRef.favouriteslist, true);
asyncActivityRef.checkNothingFavourites();
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.invalidateOptionsMenu();
asyncActivityRef.finishEditMode();
asyncActivityRef.toolbar.setTitle(asyncActivityRef.getResources().getString(R.string.favourite_title));
asyncActivityRef.clearSelectedPhotos();
}
}
/* AsyncTask for Add to favourites operation */
private class AddToFavourites extends AsyncTask<Void, Integer, Integer>{
@Override
protected void onPreExecute() {
getNavigationBar();
swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override protected Integer doInBackground(Void... voids) {
int count = 0;
realm = Realm.getDefaultInstance();
ArrayList<Media> favadd;
if (!all_photos) {
favadd = getAlbum().getSelectedMedia();
} else {
favadd = selectedMedias;
}
for (int i = 0; i < favadd.size(); i++) {
String realpath = favadd.get(i).getPath();
RealmQuery<FavouriteImagesModel> query = realm.where(FavouriteImagesModel.class).equalTo("path",
realpath);
if (query.count() == 0) {
count++;
realm.beginTransaction();
FavouriteImagesModel fav = realm.createObject(FavouriteImagesModel.class,
realpath);
ImageDescModel q = realm.where(ImageDescModel.class).equalTo("path", realpath).findFirst();
if (q != null) {
fav.setDescription(q.getTitle());
} else {
fav.setDescription(" ");
}
realm.commitTransaction();
}
}
return count;
}
@Override protected void onPostExecute(Integer count) {
super.onPostExecute(count);
swipeRefreshLayout.setRefreshing(false);
finishEditMode();
if (count == 0) {
SnackBarHandler.show(mDrawerLayout, getResources().getString(R.string.check_favourite_multipleitems));
} else if (count == 1) {
final Snackbar snackbar = SnackBarHandler.show(mDrawerLayout,
getResources().getString(R.string.add_favourite) );
snackbar.setAction(R.string.openfav, new View.OnClickListener() {
@Override
public void onClick(View view) {
displayfavourites();
favourites = false;
}
});
snackbar.show();
} else {
SnackBarHandler.show(mDrawerLayout, count + " " + getResources().getString(R.string
.add_favourite_multiple));
final Snackbar snackbar = SnackBarHandler.show(mDrawerLayout,
getResources().getString(R.string.add_favourite) );
snackbar.setAction(R.string.openfav, new View.OnClickListener() {
@Override
public void onClick(View view) {
displayfavourites();
favourites = false;
}
});
snackbar.show();
}
mediaAdapter.notifyDataSetChanged();
}
}
/*
Async Class for Sorting Photos - NOT listAll
*/
private static class SortingUtilsPhtots extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
SortingUtilsPhtots(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
super.onPreExecute();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
}
@Override
protected Void doInBackground(Void... aVoid) {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.getAlbum().sortPhotos();
return null;
}
protected void onPostExecute(Void aVoid) {
LFMainActivity asyncActivityRef = reference.get();
super.onPostExecute(aVoid);
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.mediaAdapter.swapDataSet(asyncActivityRef.getAlbum().getMedia(), false);
}
}
/*
Async Class for Sorting Photos - listAll
*/
private static class SortingUtilsListAll extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
SortingUtilsListAll(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
super.onPreExecute();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
}
@Override
protected Void doInBackground(Void... aVoid) {
LFMainActivity asyncActivityRef = reference.get();
Collections.sort(listAll, MediaComparators.getComparator(asyncActivityRef.getAlbum().settings.getSortingMode(),
asyncActivityRef.getAlbum().settings.getSortingOrder()));
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
LFMainActivity asyncActivityRef = reference.get();
super.onPostExecute(aVoid);
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.mediaAdapter.swapDataSet(listAll, false);
}
}
/*
Async Class for Sorting Favourites
*/
private static class SortingUtilsFavouritelist extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
SortingUtilsFavouritelist(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
super.onPreExecute();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
}
@Override
protected Void doInBackground(Void... aVoid) {
LFMainActivity asyncActivityRef = reference.get();
Collections.sort(asyncActivityRef.favouriteslist, MediaComparators.getComparator(asyncActivityRef.getAlbum().settings.getSortingMode(),
asyncActivityRef.getAlbum().settings.getSortingOrder()));
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
LFMainActivity asyncActivityRef = reference.get();
super.onPostExecute(aVoid);
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.mediaAdapter.swapDataSet(asyncActivityRef.favouriteslist, true);
}
}
/*
Async Class for Sorting Albums
*/
private static class SortingUtilsAlbums extends AsyncTask<Void, Void, Void> {
private WeakReference<LFMainActivity> reference;
SortingUtilsAlbums(LFMainActivity reference) {
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
super.onPreExecute();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
}
@Override
protected Void doInBackground(Void... aVoid) {
getAlbums().sortAlbums();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
LFMainActivity asyncActivityRef = reference.get();
super.onPostExecute(aVoid);
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.albumsAdapter.swapDataSet(getAlbums().dispAlbums);
new PrepareAlbumTask(asyncActivityRef.activityContext).execute();
}
}
/*
Async Class for coping images
*/
private class CopyPhotos extends AsyncTask<String, Integer, Boolean> {
private WeakReference<LFMainActivity> reference;
private String path;
private Snackbar snackbar;
private ArrayList<Media> temp;
private Boolean moveAction, copyAction, success;
CopyPhotos(String path, Boolean moveAction, Boolean copyAction, LFMainActivity reference) {
this.path = path;
this.moveAction = moveAction;
this.copyAction = copyAction;
this.reference = new WeakReference<>(reference);
}
@Override
protected void onPreExecute() {
LFMainActivity asyncActivityRef = reference.get();
asyncActivityRef.swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
temp = storeTemporaryphotos(path);
LFMainActivity asyncActivityRef = reference.get();
if (!asyncActivityRef.all_photos) {
success = asyncActivityRef.getAlbum().copySelectedPhotos(asyncActivityRef, path);
MediaStoreProvider.getAlbums(asyncActivityRef);
asyncActivityRef.getAlbum().updatePhotos(asyncActivityRef);
} else {
success = asyncActivityRef.copyfromallphotos(asyncActivityRef.getApplicationContext(), path);
}
return success;
}
@Override
protected void onPostExecute(Boolean result) {
LFMainActivity asyncActivityRef = reference.get();
if(result)
{
if(!asyncActivityRef.all_photos){
asyncActivityRef.mediaAdapter.swapDataSet(asyncActivityRef.getAlbum().getMedia(), false);
}else {
asyncActivityRef.mediaAdapter.swapDataSet(listAll, false);
}
asyncActivityRef.mediaAdapter.notifyDataSetChanged();
asyncActivityRef.invalidateOptionsMenu();
asyncActivityRef.swipeRefreshLayout.setRefreshing(false);
asyncActivityRef.finishEditMode();
if (moveAction)
SnackBarHandler.showWithBottomMargin(asyncActivityRef.mDrawerLayout,
asyncActivityRef.getString(R.string.photos_moved_successfully),
asyncActivityRef.navigationView.getHeight());
else if (copyAction){
snackbar = SnackBarHandler.showWithBottomMargin2(asyncActivityRef.mDrawerLayout,
asyncActivityRef.getString(R.string.copied_successfully),
asyncActivityRef.navigationView.getHeight(), Snackbar.LENGTH_SHORT);
snackbar.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
for (Media media : temp) {
String[] projection = {MediaStore.Images.Media._ID};
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[]{media.getPath()};
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c =
contentResolver
.query(queryUri, projection, selection, selectionArgs,
null);
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id =
c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris
.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id);
contentResolver.delete(deleteUri, null, null);
}
c.close();
}
}
});
}
} else
asyncActivityRef.requestSdCardPermissions();
}
}
}
| 1 | 12,977 | Just hide the textview | fossasia-phimpme-android | java |
@@ -54,7 +54,14 @@ type SessionDto struct {
Config json.RawMessage `json:"config"`
}
+// PaymentVersion represents the different payment versions we have
+type PaymentVersion string
+
+// PaymentVersionV2 represents the new pingpong version
+const PaymentVersionV2 PaymentVersion = "v2"
+
// ConsumerInfo represents the consumer related information
type ConsumerInfo struct {
IssuerID identity.Identity `json:"issuerID"`
+ Supports PaymentVersion `json:"supports"`
} | 1 | /*
* Copyright (C) 2017 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 session
import (
"encoding/json"
"github.com/mysteriumnetwork/node/communication"
"github.com/mysteriumnetwork/node/identity"
"github.com/mysteriumnetwork/node/session/promise"
)
const endpointSessionCreate = communication.RequestEndpoint("session-create")
var (
responseInvalidProposal = CreateResponse{Success: false, Message: "Invalid Proposal"}
responseInternalError = CreateResponse{Success: false, Message: "Internal Error"}
)
// CreateRequest structure represents message from service consumer to initiate session for given proposal id
type CreateRequest struct {
ProposalID int `json:"proposal_id"`
Config json.RawMessage `json:"config"`
ConsumerInfo *ConsumerInfo `json:"consumer_info,omitempty"`
}
// CreateResponse structure represents service provider response to given session request from consumer
type CreateResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Session SessionDto `json:"session"`
// Keeping this as a pointer for maximum backwards compatibility
PaymentInfo *promise.PaymentInfo `json:"paymentInfo,omitempty"`
}
// SessionDto structure represents session information data within session creation response (session id and configuration options for underlying service type)
type SessionDto struct {
ID ID `json:"id"`
Config json.RawMessage `json:"config"`
}
// ConsumerInfo represents the consumer related information
type ConsumerInfo struct {
IssuerID identity.Identity `json:"issuerID"`
}
| 1 | 14,952 | 'Supports'? Very uninformative naming inside protocol. Why not just paymentVersion, or just recognise supported payment version from generic protocol version supported by the client. | mysteriumnetwork-node | go |
@@ -162,7 +162,11 @@ func (s *DiskSuite) TestExplicitBundleAndVerify() {
csr, pubKey, err := util.NewCSRTemplate(validSpiffeID)
require.NoError(err)
- resp, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr})
+ stream, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr})
+ require.NoError(err)
+ require.NotNil(stream)
+
+ resp, err := stream.Recv()
require.NoError(err)
require.NotNil(resp)
| 1 | package disk
import (
"context"
"crypto"
"crypto/x509"
"encoding/json"
"testing"
"time"
"github.com/spiffe/spire/pkg/common/cryptoutil"
"github.com/spiffe/spire/pkg/common/x509svid"
"github.com/spiffe/spire/pkg/common/x509util"
"github.com/spiffe/spire/pkg/server/plugin/upstreamauthority"
spi "github.com/spiffe/spire/proto/spire/common/plugin"
"github.com/spiffe/spire/test/clock"
"github.com/spiffe/spire/test/spiretest"
"github.com/spiffe/spire/test/util"
testutil "github.com/spiffe/spire/test/util"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
config = `{
"ttl":"1h",
"key_file_path":"_test_data/keys/EC/private_key.pem",
"cert_file_path":"_test_data/keys/EC/cert.pem"
}`
)
var (
ctx = context.Background()
)
func TestDisk(t *testing.T) {
spiretest.Run(t, new(DiskSuite))
}
type DiskSuite struct {
spiretest.Suite
clock *clock.Mock
rawPlugin *Plugin
p upstreamauthority.Plugin
}
func (s *DiskSuite) SetupTest() {
s.clock = clock.NewMock(s.T())
p := New()
p.clock = s.clock
// This ensures that there are only specific tests that do the verify
// flow lowering the cost of "refreshing" all of the cert material
// associated with the tests in this package. TODO before 2029 generate
// all the cert and key material for tests on the fly to avoid this problem.
p._testOnlyShouldVerify = false
s.rawPlugin = p
s.LoadPlugin(builtin(p), &s.p)
s.configure()
}
func (s *DiskSuite) configure() {
resp, err := s.p.Configure(ctx, &spi.ConfigureRequest{
Configuration: config,
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: "localhost"},
})
s.Require().NoError(err)
s.Require().Equal(&spi.ConfigureResponse{}, resp)
}
func (s *DiskSuite) TestConfigureUsingECKey() {
err := s.configureWith("_test_data/keys/EC/private_key.pem", "_test_data/keys/EC/cert.pem")
s.Require().NoError(err)
}
func (s *DiskSuite) TestConfigureUsingPKCS1Key() {
err := s.configureWith("_test_data/keys/PKCS1/private_key.pem", "_test_data/keys/PKCS1/cert.pem")
s.Require().NoError(err)
}
func (s *DiskSuite) TestConfigureUsingPKCS8Key() {
err := s.configureWith("_test_data/keys/PKCS8/private_key.pem", "_test_data/keys/PKCS8/cert.pem")
s.Require().NoError(err)
}
func (s *DiskSuite) TestConfigureUsingNonMatchingKeyAndCert() {
err := s.configureWith("_test_data/keys/PKCS1/private_key.pem", "_test_data/keys/PKCS8/cert.pem")
s.Require().Error(err)
}
func (s *DiskSuite) TestConfigureUsingEmptyKey() {
err := s.configureWith("_test_data/keys/empty/private_key.pem", "_test_data/keys/empty/cert.pem")
s.Require().Error(err)
}
func (s *DiskSuite) TestConfigureUsingEmptyCert() {
err := s.configureWith("_test_data/keys/EC/private_key.pem", "_test_data/keys/empty/cert.pem")
s.Require().Error(err)
}
func (s *DiskSuite) TestConfigureUsingUnknownKey() {
err := s.configureWith("_test_data/keys/unknonw/private_key.pem", "_test_data/keys/unknonw/cert.pem")
s.Require().Error(err)
}
func (s *DiskSuite) TestConfigureUsingBadCert() {
err := s.configureWith("_test_data/keys/PKCS1/private_key.pem", "_test_data/keys/unknonw/cert.pem")
s.Require().Error(err)
}
func (s *DiskSuite) TestConfigureWithMismatchedCertKey() {
err := s.configureWith("_test_data/keys/PKCS1/private_key.pem", "_test_data/keys/EC/cert.pem")
s.Require().Error(err)
}
func (s *DiskSuite) TestGetPluginInfo() {
res, err := s.p.GetPluginInfo(ctx, &spi.GetPluginInfoRequest{})
s.Require().NoError(err)
s.Require().NotNil(res)
}
func (s *DiskSuite) TestExplicitBundleAndVerify() {
// On OSX
// openssl ecparam -name prime256v1 -genkey -noout -out root_key.pem
//openssl req -days 3650 -x509 -new -key root_key.pem -out root_cert.pem -config <(cat /etc/ssl/openssl.cnf ; printf "\n[v3]\nsubjectAltName=URI:spiffe://root\nbasicConstraints=CA:true") -extensions v3
//openssl ecparam -name prime256v1 -genkey -noout -out intermediate_key.pem
//openssl req -new -key intermediate_key.pem -out intermediate_csr.pem -config <(cat /etc/ssl/openssl.cnf ; printf "\n[v3]\nsubjectAltName=URI:spiffe://intermediate\nbasicConstraints=CA:true") -extensions v3
//openssl x509 -days 3650 -req -CA root_cert.pem -CAkey root_key.pem -in intermediate_csr.pem -out intermediate_cert.pem -CAcreateserial -extfile <(cat /etc/ssl/openssl.cnf ; printf "\n[v3]\nsubjectAltName=URI:spiffe://intermediate\nbasicConstraints=CA:true") -extensions v3
//openssl ecparam -name prime256v1 -genkey -noout -out upstream_key.pem
//openssl req -new -key upstream_key.pem -out upstream_csr.pem -config <(cat /etc/ssl/openssl.cnf ; printf "\n[v3]\nsubjectAltName=URI:spiffe://upstream\nbasicConstraints=CA:true") -extensions v3
//openssl x509 -days 3650 -req -CA intermediate_cert.pem -CAkey intermediate_key.pem -in upstream_csr.pem -out upstream_cert.pem -CAcreateserial -extfile <(cat /etc/ssl/openssl.cnf ; printf "\n[v3]\nsubjectAltName=URI:spiffe://upstream\nbasicConstraints=CA:true") -extensions v3
// cat upstream_cert.pem intermediate_cert.pem > upstream_and_intermediate.pem
// This test verifies the cert chain and will start failing on May 15 2029
require := s.Require()
s.rawPlugin._testOnlyShouldVerify = true
_, err := s.p.Configure(ctx, &spi.ConfigureRequest{
Configuration: `{
"key_file_path": "_test_data/keys/EC/upstream_key.pem",
"cert_file_path": "_test_data/keys/EC/upstream_cert.pem",
"bundle_file_path": "_test_data/keys/EC/root_cert.pem",
"ttl": "1h",
}`,
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: "localhost"},
})
require.Error(err, "should fail to verify as an intermediate is missing")
_, err = s.p.Configure(ctx, &spi.ConfigureRequest{
Configuration: `{
"key_file_path": "_test_data/keys/EC/upstream_key.pem",
"cert_file_path": "_test_data/keys/EC/upstream_and_intermediate.pem",
"bundle_file_path": "_test_data/keys/EC/root_cert.pem",
"ttl": "1h",
}`,
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: "localhost"},
})
require.NoError(err)
validSpiffeID := "spiffe://localhost"
csr, pubKey, err := util.NewCSRTemplate(validSpiffeID)
require.NoError(err)
resp, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr})
require.NoError(err)
require.NotNil(resp)
testCSRResp(s.T(), resp, pubKey, []string{"spiffe://localhost", "spiffe://upstream", "spiffe://intermediate"}, []string{"spiffe://root"})
}
func (s *DiskSuite) TestBadBundleFile() {
require := s.Require()
_, err := s.p.Configure(ctx, &spi.ConfigureRequest{
Configuration: `{
"key_file_path": "_test_data/keys/EC/upstream_key.pem",
"cert_file_path": "_test_data/keys/EC/upstream_cert.pem",
"bundle_file_path": "_test_data/keys/empty/cert.pem",
"ttl": "1h",
}`,
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: "localhost"},
})
require.Error(err)
}
func (s *DiskSuite) TestNotSelfSignedWithoutBundle() {
require := s.Require()
_, err := s.p.Configure(ctx, &spi.ConfigureRequest{
Configuration: `{
"key_file_path": "_test_data/keys/EC/upstream_key.pem",
"cert_file_path": "_test_data/keys/EC/upstream_and_intermediate.pem",
"ttl": "1h",
}`,
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: "localhost"},
})
require.Error(err)
}
func (s *DiskSuite) TestSubmitValidCSR() {
require := s.Require()
testCSR := func() {
validSpiffeID := "spiffe://localhost"
csr, pubKey, err := util.NewCSRTemplate(validSpiffeID)
require.NoError(err)
resp, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr})
require.NoError(err)
require.NotNil(resp)
testCSRResp(s.T(), resp, pubKey, []string{"spiffe://localhost"}, []string{"spiffe://local"})
}
testCSR()
// Modify the cert and key file paths. The CSR will still be
// signed by the cached upstreamCA.
s.rawPlugin.mtx.Lock()
s.rawPlugin.config.CertFilePath = "invalid-file"
s.rawPlugin.config.KeyFilePath = "invalid-file"
s.rawPlugin.mtx.Unlock()
testCSR()
}
func (s *DiskSuite) TestDeprecatedTTLUsedIfSet() {
err := s.configureWithTTL("_test_data/keys/EC/private_key.pem", "_test_data/keys/EC/cert.pem", "10h")
s.Require().NoError(err)
// Submit CSR with 1 hour preferred TTL. The deprecated TTL configurable
// (10 hours) should take precedence.
s.testCSRTTL(3600, time.Hour*10)
}
func (s *DiskSuite) TestDeprecatedTTLUsesPreferredIfNoDeprecatedTTLSet() {
err := s.configureWith("_test_data/keys/EC/private_key.pem", "_test_data/keys/EC/cert.pem")
s.Require().NoError(err)
// If the preferred TTL is set, it should be used.
s.testCSRTTL(3600, time.Hour)
// If the preferred TTL is zero, the default should be used.
s.testCSRTTL(0, x509svid.DefaultUpstreamCATTL)
}
func (s *DiskSuite) testCSRTTL(preferredTTL int32, expectedTTL time.Duration) {
validSpiffeID := "spiffe://localhost"
csr, _, err := util.NewCSRTemplate(validSpiffeID)
s.Require().NoError(err)
resp, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr, PreferredTtl: preferredTTL})
s.Require().NoError(err)
s.Require().NotNil(resp)
certs, err := x509util.RawCertsToCertificates(resp.X509CaChain)
s.Require().NoError(err)
s.Require().Len(certs, 1)
s.Require().Equal(s.clock.Now().Add(expectedTTL).UTC(), certs[0].NotAfter)
}
func testCSRResp(t *testing.T, resp *upstreamauthority.MintX509CAResponse, pubKey crypto.PublicKey, expectCertChainURIs []string, expectTrustBundleURIs []string) {
certs, err := x509util.RawCertsToCertificates(resp.X509CaChain)
require.NoError(t, err)
trustBundle, err := x509util.RawCertsToCertificates(resp.UpstreamX509Roots)
require.NoError(t, err)
for i, cert := range certs {
assert.Equal(t, expectCertChainURIs[i], certURI(cert))
}
for i, cert := range trustBundle {
assert.Equal(t, expectTrustBundleURIs[i], certURI(cert))
}
isEqual, err := cryptoutil.PublicKeyEqual(certs[0].PublicKey, pubKey)
require.NoError(t, err)
require.True(t, isEqual)
}
func (s *DiskSuite) TestSubmitInvalidCSR() {
require := s.Require()
invalidSpiffeIDs := []string{"invalid://localhost", "spiffe://not-trusted"}
for _, invalidSpiffeID := range invalidSpiffeIDs {
csr, _, err := util.NewCSRTemplate(invalidSpiffeID)
require.NoError(err)
resp, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr})
require.Error(err)
require.Nil(resp)
}
invalidSequenceOfBytesAsCSR := []byte("invalid-csr")
resp, err := s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: invalidSequenceOfBytesAsCSR})
require.Error(err)
require.Nil(resp)
}
func (s *DiskSuite) TestRace() {
validSpiffeID := "spiffe://localhost"
csr, _, err := util.NewCSRTemplate(validSpiffeID)
s.Require().NoError(err)
testutil.RaceTest(s.T(), func(t *testing.T) {
// the results of these RPCs aren't important; the test is just trying
// to get a bunch of stuff happening at once.
_, _ = s.p.Configure(ctx, &spi.ConfigureRequest{Configuration: config})
_, _ = s.p.MintX509CA(ctx, &upstreamauthority.MintX509CARequest{Csr: csr})
})
}
func (s *DiskSuite) configureWith(keyFilePath, certFilePath string) error {
return s.configureWithTTL(keyFilePath, certFilePath, "")
}
func (s *DiskSuite) configureWithTTL(keyFilePath, certFilePath, deprecatedTTL string) error {
config, err := json.Marshal(Configuration{
KeyFilePath: keyFilePath,
CertFilePath: certFilePath,
DeprecatedTTL: deprecatedTTL,
})
s.Require().NoError(err)
_, err = s.p.Configure(ctx, &spi.ConfigureRequest{
Configuration: string(config),
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: "localhost"},
})
return err
}
func (s *DiskSuite) TestPublishJWTKey() {
resp, err := s.p.PublishJWTKey(context.Background(), &upstreamauthority.PublishJWTKeyRequest{})
s.Require().Nil(resp)
s.Require().EqualError(err, "rpc error: code = Unimplemented desc = upstreamauthority-disk: publishing upstream is unsupported")
}
func certURI(cert *x509.Certificate) string {
if len(cert.URIs) == 1 {
return cert.URIs[0].String()
}
return ""
}
func TestInvalidConfigs(t *testing.T) {
tests := []struct {
msg string
inputConfig string
trustDomain string
expectErrContains string
}{
{
msg: "fail to decode",
trustDomain: "trust.domain",
inputConfig: `this is :[ invalid ^^^ hcl`,
expectErrContains: "illegal char",
},
{
msg: "no trust domain",
expectErrContains: "trust_domain is required",
},
{
msg: "invalid ttl",
trustDomain: "trust.domain",
inputConfig: `{
"key_file_path": "path",
"cert_file_path": "path",
"ttl": "monday",
}`,
expectErrContains: "invalid duration monday",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.msg, func(t *testing.T) {
p := New()
_, err := p.Configure(ctx, &spi.ConfigureRequest{
Configuration: tt.inputConfig,
GlobalConfig: &spi.ConfigureRequest_GlobalConfig{TrustDomain: tt.trustDomain},
})
assert.Contains(t, err.Error(), tt.expectErrContains)
})
}
}
| 1 | 12,980 | We should add an additional call to Recv() somewhere after here that we assert returns io.EOF. | spiffe-spire | go |
@@ -16,10 +16,13 @@
package azkaban.database;
+import static azkaban.ServiceProvider.SERVICE_PROVIDER;
+
import azkaban.metrics.CommonMetrics;
import azkaban.utils.Props;
import java.io.IOException;
import java.sql.Connection;
+import javax.inject.Inject;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
| 1 | /*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.database;
import azkaban.metrics.CommonMetrics;
import azkaban.utils.Props;
import java.io.IOException;
import java.sql.Connection;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
public abstract class AbstractJdbcLoader {
private final AzkabanDataSource dataSource;
public AbstractJdbcLoader(final Props props) {
this.dataSource = DataSourceUtils.getDataSource(props);
}
protected Connection getDBConnection(final boolean autoCommit) throws IOException {
Connection connection = null;
CommonMetrics.INSTANCE.markDBConnection();
final long startMs = System.currentTimeMillis();
try {
connection = this.dataSource.getConnection();
connection.setAutoCommit(autoCommit);
} catch (final Exception e) {
DbUtils.closeQuietly(connection);
throw new IOException("Error getting DB connection.", e);
}
CommonMetrics.INSTANCE.setDBConnectionTime(System.currentTimeMillis() - startMs);
return connection;
}
protected QueryRunner createQueryRunner() {
return new QueryRunner(this.dataSource);
}
protected boolean allowsOnDuplicateKey() {
return this.dataSource.allowsOnDuplicateKey();
}
/**
* Used for when we store text data. Plain uses UTF8 encoding.
*/
public enum EncodingType {
PLAIN(1), GZIP(2);
private final int numVal;
EncodingType(final int numVal) {
this.numVal = numVal;
}
public static EncodingType fromInteger(final int x) {
switch (x) {
case 1:
return PLAIN;
case 2:
return GZIP;
default:
return PLAIN;
}
}
public int getNumVal() {
return this.numVal;
}
}
}
| 1 | 13,704 | What is this used for? | azkaban-azkaban | java |
@@ -7,9 +7,8 @@ package net.sourceforge.pmd.lang.java.ast;
import java.util.List;
-public class ASTAnnotationTypeDeclaration extends AbstractJavaAccessTypeNode implements ASTAnyTypeDeclaration {
+public class ASTAnnotationTypeDeclaration extends ASTAnyTypeDeclaration {
- private JavaQualifiedName qualifiedName;
public ASTAnnotationTypeDeclaration(int id) {
super(id); | 1 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/* Generated By:JJTree: Do not edit this line. ASTAnnotationTypeDeclaration.java */
package net.sourceforge.pmd.lang.java.ast;
import java.util.List;
public class ASTAnnotationTypeDeclaration extends AbstractJavaAccessTypeNode implements ASTAnyTypeDeclaration {
private JavaQualifiedName qualifiedName;
public ASTAnnotationTypeDeclaration(int id) {
super(id);
}
public ASTAnnotationTypeDeclaration(JavaParser p, int id) {
super(p, id);
}
/**
* Accept the visitor.
*/
@Override
public Object jjtAccept(JavaParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public boolean isNested() {
return jjtGetParent() instanceof ASTClassOrInterfaceBodyDeclaration
|| jjtGetParent() instanceof ASTAnnotationTypeMemberDeclaration;
}
@Override
public JavaQualifiedName getQualifiedName() {
if (qualifiedName == null) {
if (isNested()) {
ASTAnyTypeDeclaration parent = this.getFirstParentOfType(ASTAnyTypeDeclaration.class);
JavaQualifiedName parentQN = parent.getQualifiedName();
qualifiedName = JavaQualifiedName.ofNestedClass(parentQN, this.getImage());
return qualifiedName;
}
qualifiedName = JavaQualifiedName.ofOuterClass(this);
}
return qualifiedName;
}
@Override
public TypeKind getTypeKind() {
return TypeKind.ANNOTATION;
}
@Override
public List<ASTAnyTypeBodyDeclaration> getDeclarations() {
return getFirstChildOfType(ASTAnnotationTypeBody.class)
.findChildrenOfType(ASTAnyTypeBodyDeclaration.class);
}
}
| 1 | 13,538 | this is a breaking API change. Do we really need to do it in 6.2.0? Can't we just deprecate the methods? | pmd-pmd | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.