text
stringlengths 5
1.04M
|
|---|
// REDMOND\glennha
// <Snippet1>
using namespace System;
using namespace System::Collections::Generic;
void main()
{
List<String^>^ dinosaurs = gcnew List<String^>();
dinosaurs->Add("Pachycephalosaurus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nSort");
dinosaurs->Sort();
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
int index = dinosaurs->BinarySearch("Coelophysis");
if (index < 0)
{
dinosaurs->Insert(~index, "Coelophysis");
}
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
index = dinosaurs->BinarySearch("Tyrannosaurus");
if (index < 0)
{
dinosaurs->Insert(~index, "Tyrannosaurus");
}
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Sort
Amargasaurus
Deinonychus
Mamenchisaurus
Pachycephalosaurus
BinarySearch and Insert "Coelophysis":
Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus
BinarySearch and Insert "Tyrannosaurus":
Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
*/
// </Snippet1>
|
/* Copyright 2019, Gurobi Optimization, LLC */
/* This example considers the following separable, convex problem:
minimize f(x) - y + g(z)
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z <= 1
where f(u) = exp(-u) and g(u) = 2 u^2 - 4 u, for all real u. It
formulates and solves a simpler LP model by approximating f and
g with piecewise-linear functions. Then it transforms the model
into a MIP by negating the approximation for f, which corresponds
to a non-convex piecewise-linear function, and solves it again.
*/
#include "gurobi_c++.h"
#include <cmath>
using namespace std;
double f(double u) { return exp(-u); }
double g(double u) { return 2 * u * u - 4 * u; }
int
main(int argc,
char *argv[])
{
double *ptu = NULL;
double *ptf = NULL;
double *ptg = NULL;
try {
// Create environment
GRBEnv env = GRBEnv();
// Create a new model
GRBModel model = GRBModel(env);
// Create variables
double lb = 0.0, ub = 1.0;
GRBVar x = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "x");
GRBVar y = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "y");
GRBVar z = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "z");
// Set objective for y
model.setObjective(-y);
// Add piecewise-linear objective functions for x and z
int npts = 101;
ptu = new double[npts];
ptf = new double[npts];
ptg = new double[npts];
for (int i = 0; i < npts; i++) {
ptu[i] = lb + (ub - lb) * i / (npts - 1);
ptf[i] = f(ptu[i]);
ptg[i] = g(ptu[i]);
}
model.setPWLObj(x, npts, ptu, ptf);
model.setPWLObj(z, npts, ptu, ptg);
// Add constraint: x + 2 y + 3 z <= 4
model.addConstr(x + 2 * y + 3 * z <= 4, "c0");
// Add constraint: x + y >= 1
model.addConstr(x + y >= 1, "c1");
// Optimize model as an LP
model.optimize();
cout << "IsMIP: " << model.get(GRB_IntAttr_IsMIP) << endl;
cout << x.get(GRB_StringAttr_VarName) << " "
<< x.get(GRB_DoubleAttr_X) << endl;
cout << y.get(GRB_StringAttr_VarName) << " "
<< y.get(GRB_DoubleAttr_X) << endl;
cout << z.get(GRB_StringAttr_VarName) << " "
<< z.get(GRB_DoubleAttr_X) << endl;
cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
cout << endl;
// Negate piecewise-linear objective function for x
for (int i = 0; i < npts; i++) {
ptf[i] = -ptf[i];
}
model.setPWLObj(x, npts, ptu, ptf);
// Optimize model as a MIP
model.optimize();
cout << "IsMIP: " << model.get(GRB_IntAttr_IsMIP) << endl;
cout << x.get(GRB_StringAttr_VarName) << " "
<< x.get(GRB_DoubleAttr_X) << endl;
cout << y.get(GRB_StringAttr_VarName) << " "
<< y.get(GRB_DoubleAttr_X) << endl;
cout << z.get(GRB_StringAttr_VarName) << " "
<< z.get(GRB_DoubleAttr_X) << endl;
cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
delete[] ptu;
delete[] ptf;
delete[] ptg;
return 0;
}
|
//
// msgf_audio_buffer.cpp
//
// Musical Sound Generator Framework
//
// Created by Hasebe Masahiko on 2012/10/23.
// Copyright (c) 2012 Hasebe Masahiko. All rights reserved.
//
#include "msgf_audio_buffer.h"
using namespace msgf;
//---------------------------------------------------------
// Mix And Check
//---------------------------------------------------------
const double DAMP_LIMIT_DEPTH = 0.0001;
//---------------------------------------------------------
bool TgAudioBuffer::mixAndCheckNoSound( TgAudioBuffer &srcBuf )
{
int cnt = 0;
for ( int i=0; i<_bufSize; i++ ){
double val = srcBuf.getAudioBuffer(i);
addAudioBuffer( i, val );
if ( val < DAMP_LIMIT_DEPTH ){
cnt++;
}
}
if ( cnt >= _bufSize ){
return true;
}
else {
return false;
}
}
//---------------------------------------------------------
// Get Sound Level (MAX Level every buffer)
//---------------------------------------------------------
double TgAudioBuffer::getSoundLevel( void )
{
double lvl = 0;
for ( int i=0; i<_bufSize; i++ ){
double newlvl = getAudioBuffer(i);
if ( lvl < newlvl ){
lvl = newlvl;
}
}
return lvl;
}
|
/*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true
#include "KokkosKernels_config.h"
#if defined (KOKKOSKERNELS_INST_KOKKOS_COMPLEX_DOUBLE_) \
&& defined (KOKKOSKERNELS_INST_LAYOUTRIGHT) \
&& defined (KOKKOSKERNELS_INST_EXECSPACE_CUDA) \
&& defined (KOKKOSKERNELS_INST_MEMSPACE_CUDAUVMSPACE) \
&& defined (KOKKOSKERNELS_INST_ORDINAL_INT) \
&& defined (KOKKOSKERNELS_INST_OFFSET_SIZE_T)
#include "KokkosSparse_sptrsv_symbolic_spec.hpp"
namespace KokkosSparse {
namespace Impl {
KOKKOSSPARSE_SPTRSV_SYMBOLIC_ETI_SPEC_INST(Kokkos::complex<double>, int, size_t, Kokkos::LayoutRight, Kokkos::Cuda, Kokkos::CudaUVMSpace)
} // Impl
} // KokkosSparse
#endif
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Scripting/Natives/Generated/red/Event.hpp>
namespace RED4ext
{
namespace ent { struct Entity; }
namespace game::targeting {
struct SystemEntityTargetedEvent : red::Event
{
static constexpr const char* NAME = "gametargetingSystemEntityTargetedEvent";
static constexpr const char* ALIAS = NAME;
WeakHandle<ent::Entity> targetingEntity; // 40
};
RED4EXT_ASSERT_SIZE(SystemEntityTargetedEvent, 0x50);
} // namespace game::targeting
} // namespace RED4ext
|
/*
* Copyright (C) 2010 El proyecto de código abierto de Android
*
* Concedido bajo la licencia de Apache, versión 2.0 (la "Licencia");
* solo podrá usar este archivo en cumplimiento con la Licencia.
* Puede obtener una copia de la Licencia en
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* A menos que lo exija la legislación vigente o que se convenga por escrito, el software
* distribuido bajo la Licencia se distribuye "TAL CUAL",
* SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.
* Vea la Licencia para consultar el lenguaje específico que rige los permisos y
* las limitaciones en virtud de la Licencia.
*
*/
#include <malloc.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__))
/**
* Nuestros datos guardados.
*/
struct saved_state {
float angle;
int32_t x;
int32_t y;
};
/**
* El estado compartido de nuestra aplicación.
*/
struct engine {
struct android_app* app;
ASensorManager* sensorManager;
const ASensor* accelerometerSensor;
ASensorEventQueue* sensorEventQueue;
int animating;
EGLDisplay display;
EGLSurface surface;
EGLContext context;
int32_t width;
int32_t height;
struct saved_state state;
};
/**
* Inicialice un contexto de EGL para la visualización actual.
*/
static int engine_init_display(struct engine* engine) {
// inicialice OpenGL ES y EGL
/*
* Indique aquí los atributos de la configuración deseada.
* Abajo seleccione una EGLConfig con al menos 8 bits por componente
* de color compatible con una ventana en pantalla
*/
const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint w, h, format;
EGLint numConfigs;
EGLConfig config;
EGLSurface surface;
EGLContext context;
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display, 0, 0);
/* Aquí, la aplicación elige la configuración que quiere. En este
* ejemplo, tenemos un proceso de selección muy simplificado en el que elegimos
* la primera EGLConfig que coincide con nuestros criterios */
eglChooseConfig(display, attribs, &config, 1, &numConfigs);
/* EGL_NATIVE_VISUAL_ID es un atributo de la EGLConfig que tenemos
* garantizado que ANativeWindow_setBuffersGeometry() aceptará.
* Cuando elijamos EGLConfig, podremos volver a configurar los
* búferes ANativeWindow que buscamos usando EGL_NATIVE_VISUAL_ID. */
eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
context = eglCreateContext(display, config, NULL, NULL);
if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
LOGW("Unable to eglMakeCurrent");
return -1;
}
eglQuerySurface(display, surface, EGL_WIDTH, &w);
eglQuerySurface(display, surface, EGL_HEIGHT, &h);
engine->display = display;
engine->context = context;
engine->surface = surface;
engine->width = w;
engine->height = h;
engine->state.angle = 0;
// Inicialice el estado de GL.
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glDisable(GL_DEPTH_TEST);
return 0;
}
/**
* Solo el fotograma actual de la visualización.
*/
static void engine_draw_frame(struct engine* engine) {
if (engine->display == NULL) {
// No hay visualización.
return;
}
// Rellene la pantalla con un color.
glClearColor(((float)engine->state.x) / engine->width, engine->state.angle,
((float)engine->state.y) / engine->height, 1);
glClear(GL_COLOR_BUFFER_BIT);
eglSwapBuffers(engine->display, engine->surface);
}
/**
* Anule el contexto de EGL asociado actualmente con la visualización.
*/
static void engine_term_display(struct engine* engine) {
if (engine->display != EGL_NO_DISPLAY) {
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (engine->context != EGL_NO_CONTEXT) {
eglDestroyContext(engine->display, engine->context);
}
if (engine->surface != EGL_NO_SURFACE) {
eglDestroySurface(engine->display, engine->surface);
}
eglTerminate(engine->display);
}
engine->animating = 0;
engine->display = EGL_NO_DISPLAY;
engine->context = EGL_NO_CONTEXT;
engine->surface = EGL_NO_SURFACE;
}
/**
* Procese el evento de entrada siguiente.
*/
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
struct engine* engine = (struct engine*)app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
engine->state.x = AMotionEvent_getX(event, 0);
engine->state.y = AMotionEvent_getY(event, 0);
return 1;
}
return 0;
}
/**
* Procese el comando principal siguiente.
*/
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
struct engine* engine = (struct engine*)app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
// El sistema nos ha pedido que guardemos nuestro estado actual. Hágalo.
engine->app->savedState = malloc(sizeof(struct saved_state));
*((struct saved_state*)engine->app->savedState) = engine->state;
engine->app->savedStateSize = sizeof(struct saved_state);
break;
case APP_CMD_INIT_WINDOW:
// La ventana se va a mostrar, prepárela.
if (engine->app->window != NULL) {
engine_init_display(engine);
engine_draw_frame(engine);
}
break;
case APP_CMD_TERM_WINDOW:
// La ventana se va a ocultar o cerrar, límpiela.
engine_term_display(engine);
break;
case APP_CMD_GAINED_FOCUS:
// Cuando nuestra aplicación gana foco, empezamos a supervisar el acelerómetro.
if (engine->accelerometerSensor != NULL) {
ASensorEventQueue_enableSensor(engine->sensorEventQueue,
engine->accelerometerSensor);
// Nos gustaría obtener 60 eventos por segundo (en microsegundos).
ASensorEventQueue_setEventRate(engine->sensorEventQueue,
engine->accelerometerSensor, (1000L / 60) * 1000);
}
break;
case APP_CMD_LOST_FOCUS:
// Cuando nuestra aplicación pierde foco, dejamos de supervisar el acelerómetro.
// Esto evita consumir batería mientras no se está usando.
if (engine->accelerometerSensor != NULL) {
ASensorEventQueue_disableSensor(engine->sensorEventQueue,
engine->accelerometerSensor);
}
// Detenga también la animación.
engine->animating = 0;
engine_draw_frame(engine);
break;
}
}
/**
* Este es el punto de entrada principal de una aplicación nativa que usa
* android_native_app_glue. Se ejecuta en su propio subproceso con su propio
* bucle de eventos para recibir eventos de entrada y hacer otras cosas.
*/
void android_main(struct android_app* state) {
struct engine engine;
memset(&engine, 0, sizeof(engine));
state->userData = &engine;
state->onAppCmd = engine_handle_cmd;
state->onInputEvent = engine_handle_input;
engine.app = state;
// Prepararse para supervisar el acelerómetro
engine.sensorManager = ASensorManager_getInstance();
engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
ASENSOR_TYPE_ACCELEROMETER);
engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
state->looper, LOOPER_ID_USER, NULL, NULL);
if (state->savedState != NULL) {
// Estamos empezando con un estado guardado anterior; restaure a partir de él.
engine.state = *(struct saved_state*)state->savedState;
}
engine.animating = 1;
// bucle en espera de hacer cosas.
while (1) {
// Lea todos los eventos pendientes.
int ident;
int events;
struct android_poll_source* source;
// Si no hay animación, bloquearemos para siempre la espera de eventos.
// Si hay animación, repetiremos el bucle hasta que se lean todos los eventos y luego
// dibujaremos el siguiente fotograma de animación.
while ((ident = ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
(void**)&source)) >= 0) {
// Procese este evento.
if (source != NULL) {
source->process(state, source);
}
// Si un sensor tiene datos, procéselo ahora.
if (ident == LOOPER_ID_USER) {
if (engine.accelerometerSensor != NULL) {
ASensorEvent event;
while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
&event, 1) > 0) {
LOGI("accelerometer: x=%f y=%f z=%f",
event.acceleration.x, event.acceleration.y,
event.acceleration.z);
}
}
}
// Compruebe si vamos a cerrar.
if (state->destroyRequested != 0) {
engine_term_display(&engine);
return;
}
}
if (engine.animating) {
// Operaciones de eventos acabadas; dibuje el siguiente fotograma de animación.
engine.state.angle += .01f;
if (engine.state.angle > 1) {
engine.state.angle = 0;
}
// La operación de dibujo está limitada según la tasa de actualización de la pantalla, por lo que
// no es necesario hacer intervalos aquí.
engine_draw_frame(&engine);
}
}
}
|
// Copyright 2005, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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.
//
// The Google C++ Testing and Mocking Framework (Google Test)
#include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h"
#include "gtest/gtest-spi.h"
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>
#include <algorithm>
#include <iomanip>
#include <limits>
#include <list>
#include <map>
#include <ostream> // NOLINT
#include <sstream>
#include <vector>
#if GTEST_OS_LINUX
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <fcntl.h> // NOLINT
# include <limits.h> // NOLINT
# include <sched.h> // NOLINT
// Declares vsnprintf(). This header is not available on Windows.
# include <strings.h> // NOLINT
# include <sys/mman.h> // NOLINT
# include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT
# include <string>
#elif GTEST_OS_ZOS
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
# include <strings.h> // NOLINT
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
# include <windows.h> // NOLINT
# undef min
#elif GTEST_OS_WINDOWS // We are on Windows proper.
# include <io.h> // NOLINT
# include <sys/timeb.h> // NOLINT
# include <sys/types.h> // NOLINT
# include <sys/stat.h> // NOLINT
# if GTEST_OS_WINDOWS_MINGW
// MinGW has gettimeofday() but not _ftime64().
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
# endif // GTEST_OS_WINDOWS_MINGW
// cpplint thinks that the header is already included, so we want to
// silence it.
# include <windows.h> // NOLINT
# undef min
#else
// Assume other platforms have gettimeofday().
# define GTEST_HAS_GETTIMEOFDAY_ 1
// cpplint thinks that the header is already included, so we want to
// silence it.
# include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT
#endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS
# include <stdexcept>
#endif
#if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT
# include <sys/socket.h> // NOLINT
# include <sys/types.h> // NOLINT
#endif
#include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS
# define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS
#if GTEST_OS_MAC
#ifndef GTEST_OS_IOS
#include <crt_externs.h>
#endif
#endif
#if GTEST_HAS_ABSL
#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/stacktrace.h"
#include "absl/debugging/symbolize.h"
#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
namespace testing {
using internal::CountIf;
using internal::ForEach;
using internal::GetElementOr;
using internal::Shuffle;
// Constants.
// A test whose test suite name or test name matches this filter is
// disabled and not run.
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
// A test suite whose name matches this filter is considered a death
// test suite and will be run before test suites whose name doesn't
// match this filter.
static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
// A test filter that matches everything.
static const char kUniversalFilter[] = "*";
// The default output format.
static const char kDefaultOutputFormat[] = "xml";
// The default output file.
static const char kDefaultOutputFile[] = "test_detail";
// The environment variable name for the test shard index.
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
// The environment variable name for the total number of test shards.
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
// The environment variable name for the test shard status file.
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
namespace internal {
// The text used in failure messages to indicate the start of the
// stack trace.
const char kStackTraceMarker[] = "\nStack trace:\n";
// g_help_flag is true iff the --help flag or an equivalent form is
// specified on the command line.
bool g_help_flag = false;
// Utilty function to Open File for Writing
static FILE* OpenFileForWriting(const std::string& output_file) {
FILE* fileout = nullptr;
FilePath output_file_path(output_file);
FilePath output_dir(output_file_path.RemoveFileName());
if (output_dir.CreateDirectoriesRecursively()) {
fileout = posix::FOpen(output_file.c_str(), "w");
}
if (fileout == nullptr) {
GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
}
return fileout;
}
} // namespace internal
// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
// environment variable.
static const char* GetDefaultFilter() {
const char* const testbridge_test_only =
internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
if (testbridge_test_only != nullptr) {
return testbridge_test_only;
}
return kUniversalFilter;
}
GTEST_DEFINE_bool_(
also_run_disabled_tests,
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
"Run disabled tests too, in addition to the tests normally being run.");
GTEST_DEFINE_bool_(
break_on_failure,
internal::BoolFromGTestEnv("break_on_failure", false),
"True iff a failed assertion should be a debugger break-point.");
GTEST_DEFINE_bool_(
catch_exceptions,
internal::BoolFromGTestEnv("catch_exceptions", true),
"True iff " GTEST_NAME_
" should catch exceptions and treat them as test failures.");
GTEST_DEFINE_string_(
color,
internal::StringFromGTestEnv("color", "auto"),
"Whether to use colors in the output. Valid values: yes, no, "
"and auto. 'auto' means to use colors if the output is "
"being sent to a terminal and the TERM environment variable "
"is set to a terminal type that supports colors.");
GTEST_DEFINE_string_(
filter,
internal::StringFromGTestEnv("filter", GetDefaultFilter()),
"A colon-separated list of glob (not regex) patterns "
"for filtering the tests to run, optionally followed by a "
"'-' and a : separated list of negative patterns (tests to "
"exclude). A test is run if it matches one of the positive "
"patterns and does not match any of the negative patterns.");
GTEST_DEFINE_bool_(
install_failure_signal_handler,
internal::BoolFromGTestEnv("install_failure_signal_handler", false),
"If true and supported on the current platform, " GTEST_NAME_ " should "
"install a signal handler that dumps debugging information when fatal "
"signals are raised.");
GTEST_DEFINE_bool_(list_tests, false,
"List all tests without running them.");
// The net priority order after flag processing is thus:
// --gtest_output command line flag
// GTEST_OUTPUT environment variable
// XML_OUTPUT_FILE environment variable
// ''
GTEST_DEFINE_string_(
output,
internal::StringFromGTestEnv("output",
internal::OutputFlagAlsoCheckEnvVar().c_str()),
"A format (defaults to \"xml\" but can be specified to be \"json\"), "
"optionally followed by a colon and an output file name or directory. "
"A directory is indicated by a trailing pathname separator. "
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
"If a directory is specified, output files will be created "
"within that directory, with file-names based on the test "
"executable's name and, if necessary, made unique by adding "
"digits.");
GTEST_DEFINE_bool_(
print_time,
internal::BoolFromGTestEnv("print_time", true),
"True iff " GTEST_NAME_
" should display elapsed time in text output.");
GTEST_DEFINE_bool_(
print_utf8,
internal::BoolFromGTestEnv("print_utf8", true),
"True iff " GTEST_NAME_
" prints UTF8 characters as text.");
GTEST_DEFINE_int32_(
random_seed,
internal::Int32FromGTestEnv("random_seed", 0),
"Random number seed to use when shuffling test orders. Must be in range "
"[1, 99999], or 0 to use a seed based on the current time.");
GTEST_DEFINE_int32_(
repeat,
internal::Int32FromGTestEnv("repeat", 1),
"How many times to repeat each test. Specify a negative number "
"for repeating forever. Useful for shaking out flaky tests.");
GTEST_DEFINE_bool_(
show_internal_stack_frames, false,
"True iff " GTEST_NAME_ " should include internal stack frames when "
"printing test failure stack traces.");
GTEST_DEFINE_bool_(
shuffle,
internal::BoolFromGTestEnv("shuffle", false),
"True iff " GTEST_NAME_
" should randomize tests' order on every run.");
GTEST_DEFINE_int32_(
stack_trace_depth,
internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
"The maximum number of stack frames to print when an "
"assertion fails. The valid range is 0 through 100, inclusive.");
GTEST_DEFINE_string_(
stream_result_to,
internal::StringFromGTestEnv("stream_result_to", ""),
"This flag specifies the host name and the port number on which to stream "
"test results. Example: \"localhost:555\". The flag is effective only on "
"Linux.");
GTEST_DEFINE_bool_(
throw_on_failure,
internal::BoolFromGTestEnv("throw_on_failure", false),
"When this flag is specified, a failed assertion will throw an exception "
"if exceptions are enabled or exit the program with a non-zero code "
"otherwise. For use with an external test framework.");
#if GTEST_USE_OWN_FLAGFILE_FLAG_
GTEST_DEFINE_string_(
flagfile,
internal::StringFromGTestEnv("flagfile", ""),
"This flag specifies the flagfile to read command-line flags from.");
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
namespace internal {
// Generates a random number from [0, range), using a Linear
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
// than kMaxRange.
UInt32 Random::Generate(UInt32 range) {
// These constants are the same as are used in glibc's rand(3).
// Use wider types than necessary to prevent unsigned overflow diagnostics.
state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
GTEST_CHECK_(range > 0)
<< "Cannot generate a number in the range [0, 0).";
GTEST_CHECK_(range <= kMaxRange)
<< "Generation of a number in [0, " << range << ") was requested, "
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
// Converting via modulus introduces a bit of downward bias, but
// it's simple, and a linear congruential generator isn't too good
// to begin with.
return state_ % range;
}
// GTestIsInitialized() returns true iff the user has initialized
// Google Test. Useful for catching the user mistake of not initializing
// Google Test before calling RUN_ALL_TESTS().
static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
// Iterates over a vector of TestSuites, keeping a running sum of the
// results of calling a given int-returning method on each.
// Returns the sum.
static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
int (TestSuite::*method)() const) {
int sum = 0;
for (size_t i = 0; i < case_list.size(); i++) {
sum += (case_list[i]->*method)();
}
return sum;
}
// Returns true iff the test suite passed.
static bool TestSuitePassed(const TestSuite* test_suite) {
return test_suite->should_run() && test_suite->Passed();
}
// Returns true iff the test suite failed.
static bool TestSuiteFailed(const TestSuite* test_suite) {
return test_suite->should_run() && test_suite->Failed();
}
// Returns true iff test_suite contains at least one test that should
// run.
static bool ShouldRunTestSuite(const TestSuite* test_suite) {
return test_suite->should_run();
}
// AssertHelper constructor.
AssertHelper::AssertHelper(TestPartResult::Type type,
const char* file,
int line,
const char* message)
: data_(new AssertHelperData(type, file, line, message)) {
}
AssertHelper::~AssertHelper() {
delete data_;
}
// Message assignment, for assertion streaming support.
void AssertHelper::operator=(const Message& message) const {
UnitTest::GetInstance()->
AddTestPartResult(data_->type, data_->file, data_->line,
AppendUserMessage(data_->message, message),
UnitTest::GetInstance()->impl()
->CurrentOsStackTraceExceptTop(1)
// Skips the stack frame for this function itself.
); // NOLINT
}
// A copy of all command line arguments. Set by InitGoogleTest().
static ::std::vector<std::string> g_argvs;
::std::vector<std::string> GetArgvs() {
#if defined(GTEST_CUSTOM_GET_ARGVS_)
// GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
// ::string. This code converts it to the appropriate type.
const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
return ::std::vector<std::string>(custom.begin(), custom.end());
#else // defined(GTEST_CUSTOM_GET_ARGVS_)
return g_argvs;
#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
}
// Returns the current application's name, removing directory path if that
// is present.
FilePath GetCurrentExecutableName() {
FilePath result;
#if GTEST_OS_WINDOWS || GTEST_OS_OS2
result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
#else
result.Set(FilePath(GetArgvs()[0]));
#endif // GTEST_OS_WINDOWS
return result.RemoveDirectoryName();
}
// Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output.
std::string UnitTestOptions::GetOutputFormat() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
const char* const colon = strchr(gtest_output_flag, ':');
return (colon == nullptr)
? std::string(gtest_output_flag)
: std::string(gtest_output_flag,
static_cast<size_t>(colon - gtest_output_flag));
}
// Returns the name of the requested output file, or the default if none
// was explicitly specified.
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
std::string format = GetOutputFormat();
if (format.empty())
format = std::string(kDefaultOutputFormat);
const char* const colon = strchr(gtest_output_flag, ':');
if (colon == nullptr)
return internal::FilePath::MakeFileName(
internal::FilePath(
UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(kDefaultOutputFile), 0,
format.c_str()).string();
internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath())
output_name = internal::FilePath::ConcatPaths(
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(colon + 1));
if (!output_name.IsDirectory())
return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(),
GetOutputFormat().c_str()));
return result.string();
}
// Returns true iff the wildcard pattern matches the string. The
// first ':' or '\0' character in pattern marks the end of it.
//
// This recursive algorithm isn't very efficient, but is clear and
// works well enough for matching test names, which are short.
bool UnitTestOptions::PatternMatchesString(const char *pattern,
const char *str) {
switch (*pattern) {
case '\0':
case ':': // Either ':' or '\0' marks the end of the pattern.
return *str == '\0';
case '?': // Matches any single character.
return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
case '*': // Matches any string (possibly empty) of characters.
return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
PatternMatchesString(pattern + 1, str);
default: // Non-special character. Matches itself.
return *pattern == *str &&
PatternMatchesString(pattern + 1, str + 1);
}
}
bool UnitTestOptions::MatchesFilter(
const std::string& name, const char* filter) {
const char *cur_pattern = filter;
for (;;) {
if (PatternMatchesString(cur_pattern, name.c_str())) {
return true;
}
// Finds the next pattern in the filter.
cur_pattern = strchr(cur_pattern, ':');
// Returns if no more pattern can be found.
if (cur_pattern == nullptr) {
return false;
}
// Skips the pattern separater (the ':' character).
cur_pattern++;
}
}
// Returns true iff the user-specified filter matches the test suite
// name and the test name.
bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
const std::string& test_name) {
const std::string& full_name = test_suite_name + "." + test_name.c_str();
// Split --gtest_filter at '-', if there is one, to separate into
// positive filter and negative filter portions
const char* const p = GTEST_FLAG(filter).c_str();
const char* const dash = strchr(p, '-');
std::string positive;
std::string negative;
if (dash == nullptr) {
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
negative = "";
} else {
positive = std::string(p, dash); // Everything up to the dash
negative = std::string(dash + 1); // Everything after the dash
if (positive.empty()) {
// Treat '-test1' as the same as '*-test1'
positive = kUniversalFilter;
}
}
// A filter is a colon-separated list of patterns. It matches a
// test if any pattern in it matches the test.
return (MatchesFilter(full_name, positive.c_str()) &&
!MatchesFilter(full_name, negative.c_str()));
}
#if GTEST_HAS_SEH
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
// Google Test should handle a SEH exception if:
// 1. the user wants it to, AND
// 2. this is not a breakpoint exception, AND
// 3. this is not a C++ exception (VC++ implements them via SEH,
// apparently).
//
// SEH exception code for C++ exceptions.
// (see http://support.microsoft.com/kb/185294 for more information).
const DWORD kCxxExceptionCode = 0xe06d7363;
bool should_handle = true;
if (!GTEST_FLAG(catch_exceptions))
should_handle = false;
else if (exception_code == EXCEPTION_BREAKPOINT)
should_handle = false;
else if (exception_code == kCxxExceptionCode)
should_handle = false;
return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
}
#endif // GTEST_HAS_SEH
} // namespace internal
// The c'tor sets this object as the test part result reporter used by
// Google Test. The 'result' parameter specifies where to report the
// results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
TestPartResultArray* result)
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
result_(result) {
Init();
}
// The c'tor sets this object as the test part result reporter used by
// Google Test. The 'result' parameter specifies where to report the
// results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result)
: intercept_mode_(intercept_mode),
result_(result) {
Init();
}
void ScopedFakeTestPartResultReporter::Init() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
old_reporter_ = impl->GetGlobalTestPartResultReporter();
impl->SetGlobalTestPartResultReporter(this);
} else {
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
impl->SetTestPartResultReporterForCurrentThread(this);
}
}
// The d'tor restores the test part result reporter used by Google Test
// before.
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
impl->SetGlobalTestPartResultReporter(old_reporter_);
} else {
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
}
}
// Increments the test part result count and remembers the result.
// This method is from the TestPartResultReporterInterface interface.
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
result_->Append(result);
}
namespace internal {
// Returns the type ID of ::testing::Test. We should always call this
// instead of GetTypeId< ::testing::Test>() to get the type ID of
// testing::Test. This is to work around a suspected linker bug when
// using Google Test as a framework on Mac OS X. The bug causes
// GetTypeId< ::testing::Test>() to return different values depending
// on whether the call is from the Google Test framework itself or
// from user test code. GetTestTypeId() is guaranteed to always
// return the same value, as it always calls GetTypeId<>() from the
// gtest.cc, which is within the Google Test framework.
TypeId GetTestTypeId() {
return GetTypeId<Test>();
}
// The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId().
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
// This predicate-formatter checks that 'results' contains a test part
// failure of the given type and that the failure message contains the
// given substring.
static AssertionResult HasOneFailure(const char* /* results_expr */,
const char* /* type_expr */,
const char* /* substr_expr */,
const TestPartResultArray& results,
TestPartResult::Type type,
const std::string& substr) {
const std::string expected(type == TestPartResult::kFatalFailure ?
"1 fatal failure" :
"1 non-fatal failure");
Message msg;
if (results.size() != 1) {
msg << "Expected: " << expected << "\n"
<< " Actual: " << results.size() << " failures";
for (int i = 0; i < results.size(); i++) {
msg << "\n" << results.GetTestPartResult(i);
}
return AssertionFailure() << msg;
}
const TestPartResult& r = results.GetTestPartResult(0);
if (r.type() != type) {
return AssertionFailure() << "Expected: " << expected << "\n"
<< " Actual:\n"
<< r;
}
if (strstr(r.message(), substr.c_str()) == nullptr) {
return AssertionFailure() << "Expected: " << expected << " containing \""
<< substr << "\"\n"
<< " Actual:\n"
<< r;
}
return AssertionSuccess();
}
// The constructor of SingleFailureChecker remembers where to look up
// test part results, what type of failure we expect, and what
// substring the failure message should contain.
SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
TestPartResult::Type type,
const std::string& substr)
: results_(results), type_(type), substr_(substr) {}
// The destructor of SingleFailureChecker verifies that the given
// TestPartResultArray contains exactly one failure that has the given
// type and contains the given substring. If that's not the case, a
// non-fatal failure will be generated.
SingleFailureChecker::~SingleFailureChecker() {
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
}
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
unit_test_->current_test_result()->AddTestPartResult(result);
unit_test_->listeners()->repeater()->OnTestPartResult(result);
}
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
}
// Returns the global test part result reporter.
TestPartResultReporterInterface*
UnitTestImpl::GetGlobalTestPartResultReporter() {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
return global_test_part_result_repoter_;
}
// Sets the global test part result reporter.
void UnitTestImpl::SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter) {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
global_test_part_result_repoter_ = reporter;
}
// Returns the test part result reporter for the current thread.
TestPartResultReporterInterface*
UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
return per_thread_test_part_result_reporter_.get();
}
// Sets the test part result reporter for the current thread.
void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
TestPartResultReporterInterface* reporter) {
per_thread_test_part_result_reporter_.set(reporter);
}
// Gets the number of successful test suites.
int UnitTestImpl::successful_test_suite_count() const {
return CountIf(test_suites_, TestSuitePassed);
}
// Gets the number of failed test suites.
int UnitTestImpl::failed_test_suite_count() const {
return CountIf(test_suites_, TestSuiteFailed);
}
// Gets the number of all test suites.
int UnitTestImpl::total_test_suite_count() const {
return static_cast<int>(test_suites_.size());
}
// Gets the number of all test suites that contain at least one test
// that should run.
int UnitTestImpl::test_suite_to_run_count() const {
return CountIf(test_suites_, ShouldRunTestSuite);
}
// Gets the number of successful tests.
int UnitTestImpl::successful_test_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
}
// Gets the number of skipped tests.
int UnitTestImpl::skipped_test_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
}
// Gets the number of failed tests.
int UnitTestImpl::failed_test_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
}
// Gets the number of disabled tests that will be reported in the XML report.
int UnitTestImpl::reportable_disabled_test_count() const {
return SumOverTestSuiteList(test_suites_,
&TestSuite::reportable_disabled_test_count);
}
// Gets the number of disabled tests.
int UnitTestImpl::disabled_test_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
}
// Gets the number of tests to be printed in the XML report.
int UnitTestImpl::reportable_test_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
}
// Gets the number of all tests.
int UnitTestImpl::total_test_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
}
// Gets the number of tests that should run.
int UnitTestImpl::test_to_run_count() const {
return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
}
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter
// specifies the number of top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
return os_stack_trace_getter()->CurrentStackTrace(
static_cast<int>(GTEST_FLAG(stack_trace_depth)),
skip_count + 1
// Skips the user-specified number of frames plus this function
// itself.
); // NOLINT
}
// Returns the current time in milliseconds.
TimeInMillis GetTimeInMillis() {
#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
// Difference between 1970-01-01 and 1601-01-01 in milliseconds.
// http://analogous.blogspot.com/2005/04/epoch.html
const TimeInMillis kJavaEpochToWinFileTimeDelta =
static_cast<TimeInMillis>(116444736UL) * 100000UL;
const DWORD kTenthMicrosInMilliSecond = 10000;
SYSTEMTIME now_systime;
FILETIME now_filetime;
ULARGE_INTEGER now_int64;
GetSystemTime(&now_systime);
if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
now_int64.LowPart = now_filetime.dwLowDateTime;
now_int64.HighPart = now_filetime.dwHighDateTime;
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
kJavaEpochToWinFileTimeDelta;
return now_int64.QuadPart;
}
return 0;
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
__timeb64 now;
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
// (deprecated function) there.
GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
_ftime64(&now);
GTEST_DISABLE_MSC_DEPRECATED_POP_()
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
#elif GTEST_HAS_GETTIMEOFDAY_
struct timeval now;
gettimeofday(&now, nullptr);
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
#else
# error "Don't know how to get the current time on your system."
#endif
}
// Utilities
// class String.
#if GTEST_OS_WINDOWS_MOBILE
// Creates a UTF-16 wide string from the given ANSI string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the wide string, or NULL if the
// input is NULL.
LPCWSTR String::AnsiToUtf16(const char* ansi) {
if (!ansi) return nullptr;
const int length = strlen(ansi);
const int unicode_length =
MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1];
MultiByteToWideChar(CP_ACP, 0, ansi, length,
unicode, unicode_length);
unicode[unicode_length] = 0;
return unicode;
}
// Creates an ANSI string from the given wide string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL.
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return nullptr;
const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
0, nullptr, nullptr);
char* ansi = new char[ansi_length + 1];
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
nullptr);
ansi[ansi_length] = 0;
return ansi;
}
#endif // GTEST_OS_WINDOWS_MOBILE
// Compares two C strings. Returns true iff they have the same content.
//
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string,
// including the empty string.
bool String::CStringEquals(const char * lhs, const char * rhs) {
if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false;
return strcmp(lhs, rhs) == 0;
}
#if GTEST_HAS_STD_WSTRING
// Converts an array of wide chars to a narrow string using the UTF-8
// encoding, and streams the result to the given Message object.
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Message* msg) {
for (size_t i = 0; i != length; ) { // NOLINT
if (wstr[i] != L'\0') {
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
while (i != length && wstr[i] != L'\0')
i++;
} else {
*msg << '\0';
i++;
}
}
}
#endif // GTEST_HAS_STD_WSTRING
void SplitString(const ::std::string& str, char delimiter,
::std::vector< ::std::string>* dest) {
::std::vector< ::std::string> parsed;
::std::string::size_type pos = 0;
while (::testing::internal::AlwaysTrue()) {
const ::std::string::size_type colon = str.find(delimiter, pos);
if (colon == ::std::string::npos) {
parsed.push_back(str.substr(pos));
break;
} else {
parsed.push_back(str.substr(pos, colon - pos));
pos = colon + 1;
}
}
dest->swap(parsed);
}
} // namespace internal
// Constructs an empty Message.
// We allocate the stringstream separately because otherwise each use of
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
// stack frame leading to huge stack frames in some cases; gcc does not reuse
// the stack space.
Message::Message() : ss_(new ::std::stringstream) {
// By default, we want there to be enough precision when printing
// a double to a Message.
*ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
}
// These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding.
Message& Message::operator <<(const wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
Message& Message::operator <<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
#if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
Message& Message::operator <<(const ::std::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this;
}
#endif // GTEST_HAS_STD_WSTRING
// Gets the text streamed to this object so far as an std::string.
// Each '\0' character in the buffer is replaced with "\\0".
std::string Message::GetString() const {
return internal::StringStreamToString(ss_.get());
}
// AssertionResult constructors.
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult::AssertionResult(const AssertionResult& other)
: success_(other.success_),
message_(other.message_.get() != nullptr
? new ::std::string(*other.message_)
: static_cast< ::std::string*>(nullptr)) {}
// Swaps two AssertionResults.
void AssertionResult::swap(AssertionResult& other) {
using std::swap;
swap(success_, other.success_);
swap(message_, other.message_);
}
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
AssertionResult AssertionResult::operator!() const {
AssertionResult negation(!success_);
if (message_.get() != nullptr) negation << *message_;
return negation;
}
// Makes a successful assertion result.
AssertionResult AssertionSuccess() {
return AssertionResult(true);
}
// Makes a failed assertion result.
AssertionResult AssertionFailure() {
return AssertionResult(false);
}
// Makes a failed assertion result with the given failure message.
// Deprecated; use AssertionFailure() << message.
AssertionResult AssertionFailure(const Message& message) {
return AssertionFailure() << message;
}
namespace internal {
namespace edit_distance {
std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
const std::vector<size_t>& right) {
std::vector<std::vector<double> > costs(
left.size() + 1, std::vector<double>(right.size() + 1));
std::vector<std::vector<EditType> > best_move(
left.size() + 1, std::vector<EditType>(right.size() + 1));
// Populate for empty right.
for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
costs[l_i][0] = static_cast<double>(l_i);
best_move[l_i][0] = kRemove;
}
// Populate for empty left.
for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
costs[0][r_i] = static_cast<double>(r_i);
best_move[0][r_i] = kAdd;
}
for (size_t l_i = 0; l_i < left.size(); ++l_i) {
for (size_t r_i = 0; r_i < right.size(); ++r_i) {
if (left[l_i] == right[r_i]) {
// Found a match. Consume it.
costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
best_move[l_i + 1][r_i + 1] = kMatch;
continue;
}
const double add = costs[l_i + 1][r_i];
const double remove = costs[l_i][r_i + 1];
const double replace = costs[l_i][r_i];
if (add < remove && add < replace) {
costs[l_i + 1][r_i + 1] = add + 1;
best_move[l_i + 1][r_i + 1] = kAdd;
} else if (remove < add && remove < replace) {
costs[l_i + 1][r_i + 1] = remove + 1;
best_move[l_i + 1][r_i + 1] = kRemove;
} else {
// We make replace a little more expensive than add/remove to lower
// their priority.
costs[l_i + 1][r_i + 1] = replace + 1.00001;
best_move[l_i + 1][r_i + 1] = kReplace;
}
}
}
// Reconstruct the best path. We do it in reverse order.
std::vector<EditType> best_path;
for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
EditType move = best_move[l_i][r_i];
best_path.push_back(move);
l_i -= move != kAdd;
r_i -= move != kRemove;
}
std::reverse(best_path.begin(), best_path.end());
return best_path;
}
namespace {
// Helper class to convert string into ids with deduplication.
class InternalStrings {
public:
size_t GetId(const std::string& str) {
IdMap::iterator it = ids_.find(str);
if (it != ids_.end()) return it->second;
size_t id = ids_.size();
return ids_[str] = id;
}
private:
typedef std::map<std::string, size_t> IdMap;
IdMap ids_;
};
} // namespace
std::vector<EditType> CalculateOptimalEdits(
const std::vector<std::string>& left,
const std::vector<std::string>& right) {
std::vector<size_t> left_ids, right_ids;
{
InternalStrings intern_table;
for (size_t i = 0; i < left.size(); ++i) {
left_ids.push_back(intern_table.GetId(left[i]));
}
for (size_t i = 0; i < right.size(); ++i) {
right_ids.push_back(intern_table.GetId(right[i]));
}
}
return CalculateOptimalEdits(left_ids, right_ids);
}
namespace {
// Helper class that holds the state for one hunk and prints it out to the
// stream.
// It reorders adds/removes when possible to group all removes before all
// adds. It also adds the hunk header before printint into the stream.
class Hunk {
public:
Hunk(size_t left_start, size_t right_start)
: left_start_(left_start),
right_start_(right_start),
adds_(),
removes_(),
common_() {}
void PushLine(char edit, const char* line) {
switch (edit) {
case ' ':
++common_;
FlushEdits();
hunk_.push_back(std::make_pair(' ', line));
break;
case '-':
++removes_;
hunk_removes_.push_back(std::make_pair('-', line));
break;
case '+':
++adds_;
hunk_adds_.push_back(std::make_pair('+', line));
break;
}
}
void PrintTo(std::ostream* os) {
PrintHeader(os);
FlushEdits();
for (std::list<std::pair<char, const char*> >::const_iterator it =
hunk_.begin();
it != hunk_.end(); ++it) {
*os << it->first << it->second << "\n";
}
}
bool has_edits() const { return adds_ || removes_; }
private:
void FlushEdits() {
hunk_.splice(hunk_.end(), hunk_removes_);
hunk_.splice(hunk_.end(), hunk_adds_);
}
// Print a unified diff header for one hunk.
// The format is
// "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
// where the left/right parts are omitted if unnecessary.
void PrintHeader(std::ostream* ss) const {
*ss << "@@ ";
if (removes_) {
*ss << "-" << left_start_ << "," << (removes_ + common_);
}
if (removes_ && adds_) {
*ss << " ";
}
if (adds_) {
*ss << "+" << right_start_ << "," << (adds_ + common_);
}
*ss << " @@\n";
}
size_t left_start_, right_start_;
size_t adds_, removes_, common_;
std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
};
} // namespace
// Create a list of diff hunks in Unified diff format.
// Each hunk has a header generated by PrintHeader above plus a body with
// lines prefixed with ' ' for no change, '-' for deletion and '+' for
// addition.
// 'context' represents the desired unchanged prefix/suffix around the diff.
// If two hunks are close enough that their contexts overlap, then they are
// joined into one hunk.
std::string CreateUnifiedDiff(const std::vector<std::string>& left,
const std::vector<std::string>& right,
size_t context) {
const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
size_t l_i = 0, r_i = 0, edit_i = 0;
std::stringstream ss;
while (edit_i < edits.size()) {
// Find first edit.
while (edit_i < edits.size() && edits[edit_i] == kMatch) {
++l_i;
++r_i;
++edit_i;
}
// Find the first line to include in the hunk.
const size_t prefix_context = std::min(l_i, context);
Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
for (size_t i = prefix_context; i > 0; --i) {
hunk.PushLine(' ', left[l_i - i].c_str());
}
// Iterate the edits until we found enough suffix for the hunk or the input
// is over.
size_t n_suffix = 0;
for (; edit_i < edits.size(); ++edit_i) {
if (n_suffix >= context) {
// Continue only if the next hunk is very close.
auto it = edits.begin() + static_cast<int>(edit_i);
while (it != edits.end() && *it == kMatch) ++it;
if (it == edits.end() ||
static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
// There is no next edit or it is too far away.
break;
}
}
EditType edit = edits[edit_i];
// Reset count when a non match is found.
n_suffix = edit == kMatch ? n_suffix + 1 : 0;
if (edit == kMatch || edit == kRemove || edit == kReplace) {
hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
}
if (edit == kAdd || edit == kReplace) {
hunk.PushLine('+', right[r_i].c_str());
}
// Advance indices, depending on edit type.
l_i += edit != kAdd;
r_i += edit != kRemove;
}
if (!hunk.has_edits()) {
// We are done. We don't want this hunk.
break;
}
hunk.PrintTo(&ss);
}
return ss.str();
}
} // namespace edit_distance
namespace {
// The string representation of the values received in EqFailure() are already
// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
// characters the same.
std::vector<std::string> SplitEscapedString(const std::string& str) {
std::vector<std::string> lines;
size_t start = 0, end = str.size();
if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
++start;
--end;
}
bool escaped = false;
for (size_t i = start; i + 1 < end; ++i) {
if (escaped) {
escaped = false;
if (str[i] == 'n') {
lines.push_back(str.substr(start, i - start - 1));
start = i + 1;
}
} else {
escaped = str[i] == '\\';
}
}
lines.push_back(str.substr(start, end - start));
return lines;
}
} // namespace
// Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
//
// The first four parameters are the expressions used in the assertion
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
// where foo is 5 and bar is 6, we have:
//
// lhs_expression: "foo"
// rhs_expression: "bar"
// lhs_value: "5"
// rhs_value: "6"
//
// The ignoring_case parameter is true iff the assertion is a
// *_STRCASEEQ*. When it's true, the string "Ignoring case" will
// be inserted into the message.
AssertionResult EqFailure(const char* lhs_expression,
const char* rhs_expression,
const std::string& lhs_value,
const std::string& rhs_value,
bool ignoring_case) {
Message msg;
msg << "Expected equality of these values:";
msg << "\n " << lhs_expression;
if (lhs_value != lhs_expression) {
msg << "\n Which is: " << lhs_value;
}
msg << "\n " << rhs_expression;
if (rhs_value != rhs_expression) {
msg << "\n Which is: " << rhs_value;
}
if (ignoring_case) {
msg << "\nIgnoring case";
}
if (!lhs_value.empty() && !rhs_value.empty()) {
const std::vector<std::string> lhs_lines =
SplitEscapedString(lhs_value);
const std::vector<std::string> rhs_lines =
SplitEscapedString(rhs_value);
if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
msg << "\nWith diff:\n"
<< edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
}
}
return AssertionFailure() << msg;
}
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result,
const char* expression_text,
const char* actual_predicate_value,
const char* expected_predicate_value) {
const char* actual_message = assertion_result.message();
Message msg;
msg << "Value of: " << expression_text
<< "\n Actual: " << actual_predicate_value;
if (actual_message[0] != '\0')
msg << " (" << actual_message << ")";
msg << "\nExpected: " << expected_predicate_value;
return msg.GetString();
}
// Helper function for implementing ASSERT_NEAR.
AssertionResult DoubleNearPredFormat(const char* expr1,
const char* expr2,
const char* abs_error_expr,
double val1,
double val2,
double abs_error) {
const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess();
return AssertionFailure()
<< "The difference between " << expr1 << " and " << expr2
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
<< expr1 << " evaluates to " << val1 << ",\n"
<< expr2 << " evaluates to " << val2 << ", and\n"
<< abs_error_expr << " evaluates to " << abs_error << ".";
}
// Helper template for implementing FloatLE() and DoubleLE().
template <typename RawType>
AssertionResult FloatingPointLE(const char* expr1,
const char* expr2,
RawType val1,
RawType val2) {
// Returns success if val1 is less than val2,
if (val1 < val2) {
return AssertionSuccess();
}
// or if val1 is almost equal to val2.
const FloatingPoint<RawType> lhs(val1), rhs(val2);
if (lhs.AlmostEquals(rhs)) {
return AssertionSuccess();
}
// Note that the above two checks will both fail if either val1 or
// val2 is NaN, as the IEEE floating-point standard requires that
// any predicate involving a NaN must return false.
::std::stringstream val1_ss;
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< val1;
::std::stringstream val2_ss;
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< val2;
return AssertionFailure()
<< "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
<< " Actual: " << StringStreamToString(&val1_ss) << " vs "
<< StringStreamToString(&val2_ss);
}
} // namespace internal
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult FloatLE(const char* expr1, const char* expr2,
float val1, float val2) {
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
}
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2) {
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
}
namespace internal {
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
// arguments.
AssertionResult CmpHelperEQ(const char* lhs_expression,
const char* rhs_expression,
BiggestInt lhs,
BiggestInt rhs) {
if (lhs == rhs) {
return AssertionSuccess();
}
return EqFailure(lhs_expression,
rhs_expression,
FormatForComparisonFailureMessage(lhs, rhs),
FormatForComparisonFailureMessage(rhs, lhs),
false);
}
// A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
// just to avoid copy-and-paste of similar code.
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
BiggestInt val1, BiggestInt val2) {\
if (val1 op val2) {\
return AssertionSuccess();\
} else {\
return AssertionFailure() \
<< "Expected: (" << expr1 << ") " #op " (" << expr2\
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
}\
}
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(NE, !=)
// Implements the helper function for {ASSERT|EXPECT}_LE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(LE, <=)
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(LT, < )
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(GE, >=)
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(GT, > )
#undef GTEST_IMPL_CMP_HELPER_
// The helper function for {ASSERT|EXPECT}_STREQ.
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression,
const char* lhs,
const char* rhs) {
if (String::CStringEquals(lhs, rhs)) {
return AssertionSuccess();
}
return EqFailure(lhs_expression,
rhs_expression,
PrintToString(lhs),
PrintToString(rhs),
false);
}
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
const char* rhs_expression,
const char* lhs,
const char* rhs) {
if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
return AssertionSuccess();
}
return EqFailure(lhs_expression,
rhs_expression,
PrintToString(lhs),
PrintToString(rhs),
true);
}
// The helper function for {ASSERT|EXPECT}_STRNE.
AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2) {
if (!String::CStringEquals(s1, s2)) {
return AssertionSuccess();
} else {
return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
<< s2_expression << "), actual: \""
<< s1 << "\" vs \"" << s2 << "\"";
}
}
// The helper function for {ASSERT|EXPECT}_STRCASENE.
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2) {
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
return AssertionSuccess();
} else {
return AssertionFailure()
<< "Expected: (" << s1_expression << ") != ("
<< s2_expression << ") (ignoring case), actual: \""
<< s1 << "\" vs \"" << s2 << "\"";
}
}
} // namespace internal
namespace {
// Helper functions for implementing IsSubString() and IsNotSubstring().
// This group of overloaded functions return true iff needle is a
// substring of haystack. NULL is considered a substring of itself
// only.
bool IsSubstringPred(const char* needle, const char* haystack) {
if (needle == nullptr || haystack == nullptr) return needle == haystack;
return strstr(haystack, needle) != nullptr;
}
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
if (needle == nullptr || haystack == nullptr) return needle == haystack;
return wcsstr(haystack, needle) != nullptr;
}
// StringType here can be either ::std::string or ::std::wstring.
template <typename StringType>
bool IsSubstringPred(const StringType& needle,
const StringType& haystack) {
return haystack.find(needle) != StringType::npos;
}
// This function implements either IsSubstring() or IsNotSubstring(),
// depending on the value of the expected_to_be_substring parameter.
// StringType here can be const char*, const wchar_t*, ::std::string,
// or ::std::wstring.
template <typename StringType>
AssertionResult IsSubstringImpl(
bool expected_to_be_substring,
const char* needle_expr, const char* haystack_expr,
const StringType& needle, const StringType& haystack) {
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
return AssertionSuccess();
const bool is_wide_string = sizeof(needle[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
return AssertionFailure()
<< "Value of: " << needle_expr << "\n"
<< " Actual: " << begin_string_quote << needle << "\"\n"
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
<< "a substring of " << haystack_expr << "\n"
<< "Which is: " << begin_string_quote << haystack << "\"";
}
} // namespace
// IsSubstring() and IsNotSubstring() check whether needle is a
// substring of haystack (NULL is considered a substring of itself
// only), and return an appropriate error message when they fail.
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
#if GTEST_HAS_STD_WSTRING
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
#endif // GTEST_HAS_STD_WSTRING
namespace internal {
#if GTEST_OS_WINDOWS
namespace {
// Helper function for IsHRESULT{SuccessFailure} predicates
AssertionResult HRESULTFailureHelper(const char* expr,
const char* expected,
long hr) { // NOLINT
# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
// Windows CE doesn't support FormatMessage.
const char error_text[] = "";
# else
// Looks up the human-readable system message for the HRESULT code
// and since we're not passing any params to FormatMessage, we don't
// want inserts expanded.
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD kBufSize = 4096;
// Gets the system's human readable message string for this HRESULT.
char error_text[kBufSize] = { '\0' };
DWORD message_length = ::FormatMessageA(kFlags,
0, // no source, we're asking system
static_cast<DWORD>(hr), // the error
0, // no line width restrictions
error_text, // output buffer
kBufSize, // buf size
nullptr); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]);
--message_length) {
error_text[message_length - 1] = '\0';
}
# endif // GTEST_OS_WINDOWS_MOBILE
const std::string error_hex("0x" + String::FormatHexInt(hr));
return ::testing::AssertionFailure()
<< "Expected: " << expr << " " << expected << ".\n"
<< " Actual: " << error_hex << " " << error_text << "\n";
}
} // namespace
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
if (SUCCEEDED(hr)) {
return AssertionSuccess();
}
return HRESULTFailureHelper(expr, "succeeds", hr);
}
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
if (FAILED(hr)) {
return AssertionSuccess();
}
return HRESULTFailureHelper(expr, "fails", hr);
}
#endif // GTEST_OS_WINDOWS
// Utility functions for encoding Unicode text (wide strings) in
// UTF-8.
// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
// like this:
//
// Code-point length Encoding
// 0 - 7 bits 0xxxxxxx
// 8 - 11 bits 110xxxxx 10xxxxxx
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// The maximum code-point a one-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
// The maximum code-point a two-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
// The maximum code-point a three-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
// The maximum code-point a four-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
// Chops off the n lowest bits from a bit pattern. Returns the n
// lowest bits. As a side effect, the original bit pattern will be
// shifted to the right by n bits.
inline UInt32 ChopLowBits(UInt32* bits, int n) {
const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
*bits >>= n;
return low_bits;
}
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
// wide enough to contain a code point.
// If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// to "(Invalid Unicode 0xXXXXXXXX)".
std::string CodePointToUtf8(UInt32 code_point) {
if (code_point > kMaxCodePoint4) {
return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
}
char str[5]; // Big enough for the largest valid code point.
if (code_point <= kMaxCodePoint1) {
str[1] = '\0';
str[0] = static_cast<char>(code_point); // 0xxxxxxx
} else if (code_point <= kMaxCodePoint2) {
str[2] = '\0';
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
} else if (code_point <= kMaxCodePoint3) {
str[3] = '\0';
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
} else { // code_point <= kMaxCodePoint4
str[4] = '\0';
str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
}
return str;
}
// The following two functions only make sense if the system
// uses UTF-16 for wide string encoding. All supported systems
// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
// Determines if the arguments constitute UTF-16 surrogate pair
// and thus should be combined into a single Unicode code point
// using CreateCodePointFromUtf16SurrogatePair.
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
return sizeof(wchar_t) == 2 &&
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
}
// Creates a Unicode code point from UTF16 surrogate pair.
inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
wchar_t second) {
const auto first_u = static_cast<UInt32>(first);
const auto second_u = static_cast<UInt32>(second);
const UInt32 mask = (1 << 10) - 1;
return (sizeof(wchar_t) == 2)
? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
:
// This function should not be called when the condition is
// false, but we provide a sensible default in case it is.
first_u;
}
// Converts a wide string to a narrow string in UTF-8 encoding.
// The wide string is assumed to have the following encoding:
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
// Parameter str points to a null-terminated wide string.
// Parameter num_chars may additionally limit the number
// of wchar_t characters processed. -1 is used when the entire string
// should be processed.
// If the string contains code points that are not valid Unicode code points
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane.
std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (num_chars == -1)
num_chars = static_cast<int>(wcslen(str));
::std::stringstream stream;
for (int i = 0; i < num_chars; ++i) {
UInt32 unicode_code_point;
if (str[i] == L'\0') {
break;
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
str[i + 1]);
i++;
} else {
unicode_code_point = static_cast<UInt32>(str[i]);
}
stream << CodePointToUtf8(unicode_code_point);
}
return StringStreamToString(&stream);
}
// Converts a wide C string to an std::string using the UTF-8 encoding.
// NULL will be converted to "(null)".
std::string String::ShowWideCString(const wchar_t * wide_c_str) {
if (wide_c_str == nullptr) return "(null)";
return internal::WideStringToUtf8(wide_c_str, -1);
}
// Compares two wide C strings. Returns true iff they have the same
// content.
//
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string,
// including the empty string.
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false;
return wcscmp(lhs, rhs) == 0;
}
// Helper function for *_STREQ on wide strings.
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression,
const wchar_t* lhs,
const wchar_t* rhs) {
if (String::WideCStringEquals(lhs, rhs)) {
return AssertionSuccess();
}
return EqFailure(lhs_expression,
rhs_expression,
PrintToString(lhs),
PrintToString(rhs),
false);
}
// Helper function for *_STRNE on wide strings.
AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const wchar_t* s1,
const wchar_t* s2) {
if (!String::WideCStringEquals(s1, s2)) {
return AssertionSuccess();
}
return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
<< s2_expression << "), actual: "
<< PrintToString(s1)
<< " vs " << PrintToString(s2);
}
// Compares two C strings, ignoring case. Returns true iff they have
// the same content.
//
// Unlike strcasecmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false;
return posix::StrCaseCmp(lhs, rhs) == 0;
}
// Compares two wide C strings, ignoring case. Returns true iff they
// have the same content.
//
// Unlike wcscasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL wide C string,
// including the empty string.
// NB: The implementations on different platforms slightly differ.
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
// environment variable. On GNU platform this method uses wcscasecmp
// which compares according to LC_CTYPE category of the current locale.
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
// current locale.
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs) {
if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false;
#if GTEST_OS_WINDOWS
return _wcsicmp(lhs, rhs) == 0;
#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
return wcscasecmp(lhs, rhs) == 0;
#else
// Android, Mac OS X and Cygwin don't define wcscasecmp.
// Other unknown OSes may not define it either.
wint_t left, right;
do {
left = towlower(*lhs++);
right = towlower(*rhs++);
} while (left && left == right);
return left == right;
#endif // OS selector
}
// Returns true iff str ends with the given suffix, ignoring case.
// Any string is considered to end with an empty suffix.
bool String::EndsWithCaseInsensitive(
const std::string& str, const std::string& suffix) {
const size_t str_len = str.length();
const size_t suffix_len = suffix.length();
return (str_len >= suffix_len) &&
CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
suffix.c_str());
}
// Formats an int value as "%02d".
std::string String::FormatIntWidth2(int value) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << value;
return ss.str();
}
// Formats an int value as "%X".
std::string String::FormatHexUInt32(UInt32 value) {
std::stringstream ss;
ss << std::hex << std::uppercase << value;
return ss.str();
}
// Formats an int value as "%X".
std::string String::FormatHexInt(int value) {
return FormatHexUInt32(static_cast<UInt32>(value));
}
// Formats a byte as "%02X".
std::string String::FormatByte(unsigned char value) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
<< static_cast<unsigned int>(value);
return ss.str();
}
// Converts the buffer in a stringstream to an std::string, converting NUL
// bytes to "\\0" along the way.
std::string StringStreamToString(::std::stringstream* ss) {
const ::std::string& str = ss->str();
const char* const start = str.c_str();
const char* const end = start + str.length();
std::string result;
result.reserve(static_cast<size_t>(2 * (end - start)));
for (const char* ch = start; ch != end; ++ch) {
if (*ch == '\0') {
result += "\\0"; // Replaces NUL with "\\0";
} else {
result += *ch;
}
}
return result;
}
// Appends the user-supplied message to the Google-Test-generated message.
std::string AppendUserMessage(const std::string& gtest_msg,
const Message& user_msg) {
// Appends the user message if it's non-empty.
const std::string user_msg_string = user_msg.GetString();
if (user_msg_string.empty()) {
return gtest_msg;
}
return gtest_msg + "\n" + user_msg_string;
}
} // namespace internal
// class TestResult
// Creates an empty TestResult.
TestResult::TestResult()
: death_test_count_(0),
elapsed_time_(0) {
}
// D'tor.
TestResult::~TestResult() {
}
// Returns the i-th test part result among all the results. i can
// range from 0 to total_part_count() - 1. If i is not in that range,
// aborts the program.
const TestPartResult& TestResult::GetTestPartResult(int i) const {
if (i < 0 || i >= total_part_count())
internal::posix::Abort();
return test_part_results_.at(static_cast<size_t>(i));
}
// Returns the i-th test property. i can range from 0 to
// test_property_count() - 1. If i is not in that range, aborts the
// program.
const TestProperty& TestResult::GetTestProperty(int i) const {
if (i < 0 || i >= test_property_count())
internal::posix::Abort();
return test_properties_.at(static_cast<size_t>(i));
}
// Clears the test part results.
void TestResult::ClearTestPartResults() {
test_part_results_.clear();
}
// Adds a test part result to the list.
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
test_part_results_.push_back(test_part_result);
}
// Adds a test property to the list. If a property with the same key as the
// supplied property is already represented, the value of this test_property
// replaces the old value for that key.
void TestResult::RecordProperty(const std::string& xml_element,
const TestProperty& test_property) {
if (!ValidateTestProperty(xml_element, test_property)) {
return;
}
internal::MutexLock lock(&test_properites_mutex_);
const std::vector<TestProperty>::iterator property_with_matching_key =
std::find_if(test_properties_.begin(), test_properties_.end(),
internal::TestPropertyKeyIs(test_property.key()));
if (property_with_matching_key == test_properties_.end()) {
test_properties_.push_back(test_property);
return;
}
property_with_matching_key->SetValue(test_property.value());
}
// The list of reserved attributes used in the <testsuites> element of XML
// output.
static const char* const kReservedTestSuitesAttributes[] = {
"disabled",
"errors",
"failures",
"name",
"random_seed",
"tests",
"time",
"timestamp"
};
// The list of reserved attributes used in the <testsuite> element of XML
// output.
static const char* const kReservedTestSuiteAttributes[] = {
"disabled",
"errors",
"failures",
"name",
"tests",
"time"
};
// The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = {
"classname", "name", "status", "time", "type_param",
"value_param", "file", "line"};
// Use a slightly different set for allowed output to ensure existing tests can
// still RecordProperty("result")
static const char* const kReservedOutputTestCaseAttributes[] = {
"classname", "name", "status", "time", "type_param",
"value_param", "file", "line", "result"};
template <int kSize>
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
return std::vector<std::string>(array, array + kSize);
}
static std::vector<std::string> GetReservedAttributesForElement(
const std::string& xml_element) {
if (xml_element == "testsuites") {
return ArrayAsVector(kReservedTestSuitesAttributes);
} else if (xml_element == "testsuite") {
return ArrayAsVector(kReservedTestSuiteAttributes);
} else if (xml_element == "testcase") {
return ArrayAsVector(kReservedTestCaseAttributes);
} else {
GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
}
// This code is unreachable but some compilers may not realizes that.
return std::vector<std::string>();
}
// TODO(jdesprez): Merge the two getReserved attributes once skip is improved
static std::vector<std::string> GetReservedOutputAttributesForElement(
const std::string& xml_element) {
if (xml_element == "testsuites") {
return ArrayAsVector(kReservedTestSuitesAttributes);
} else if (xml_element == "testsuite") {
return ArrayAsVector(kReservedTestSuiteAttributes);
} else if (xml_element == "testcase") {
return ArrayAsVector(kReservedOutputTestCaseAttributes);
} else {
GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
}
// This code is unreachable but some compilers may not realizes that.
return std::vector<std::string>();
}
static std::string FormatWordList(const std::vector<std::string>& words) {
Message word_list;
for (size_t i = 0; i < words.size(); ++i) {
if (i > 0 && words.size() > 2) {
word_list << ", ";
}
if (i == words.size() - 1) {
word_list << "and ";
}
word_list << "'" << words[i] << "'";
}
return word_list.GetString();
}
static bool ValidateTestPropertyName(
const std::string& property_name,
const std::vector<std::string>& reserved_names) {
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
reserved_names.end()) {
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
<< " (" << FormatWordList(reserved_names)
<< " are reserved by " << GTEST_NAME_ << ")";
return false;
}
return true;
}
// Adds a failure if the key is a reserved attribute of the element named
// xml_element. Returns true if the property is valid.
bool TestResult::ValidateTestProperty(const std::string& xml_element,
const TestProperty& test_property) {
return ValidateTestPropertyName(test_property.key(),
GetReservedAttributesForElement(xml_element));
}
// Clears the object.
void TestResult::Clear() {
test_part_results_.clear();
test_properties_.clear();
death_test_count_ = 0;
elapsed_time_ = 0;
}
// Returns true off the test part was skipped.
static bool TestPartSkipped(const TestPartResult& result) {
return result.skipped();
}
// Returns true iff the test was skipped.
bool TestResult::Skipped() const {
return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
}
// Returns true iff the test failed.
bool TestResult::Failed() const {
for (int i = 0; i < total_part_count(); ++i) {
if (GetTestPartResult(i).failed())
return true;
}
return false;
}
// Returns true iff the test part fatally failed.
static bool TestPartFatallyFailed(const TestPartResult& result) {
return result.fatally_failed();
}
// Returns true iff the test fatally failed.
bool TestResult::HasFatalFailure() const {
return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
}
// Returns true iff the test part non-fatally failed.
static bool TestPartNonfatallyFailed(const TestPartResult& result) {
return result.nonfatally_failed();
}
// Returns true iff the test has a non-fatal failure.
bool TestResult::HasNonfatalFailure() const {
return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
}
// Gets the number of all test parts. This is the sum of the number
// of successful test parts and the number of failed test parts.
int TestResult::total_part_count() const {
return static_cast<int>(test_part_results_.size());
}
// Returns the number of the test properties.
int TestResult::test_property_count() const {
return static_cast<int>(test_properties_.size());
}
// class Test
// Creates a Test object.
// The c'tor saves the states of all flags.
Test::Test()
: gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
}
// The d'tor restores the states of all flags. The actual work is
// done by the d'tor of the gtest_flag_saver_ field, and thus not
// visible here.
Test::~Test() {
}
// Sets up the test fixture.
//
// A sub-class may override this.
void Test::SetUp() {
}
// Tears down the test fixture.
//
// A sub-class may override this.
void Test::TearDown() {
}
// Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, const std::string& value) {
UnitTest::GetInstance()->RecordProperty(key, value);
}
// Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, int value) {
Message value_message;
value_message << value;
RecordProperty(key, value_message.GetString().c_str());
}
namespace internal {
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message) {
// This function is a friend of UnitTest and as such has access to
// AddTestPartResult.
UnitTest::GetInstance()->AddTestPartResult(
result_type,
nullptr, // No info about the source file where the exception occurred.
-1, // We have no info on which line caused the exception.
message,
""); // No stack trace, either.
}
} // namespace internal
// Google Test requires all tests in the same test suite to use the same test
// fixture class. This function checks if the current test has the
// same fixture class as the first test in the current test suite. If
// yes, it returns true; otherwise it generates a Google Test failure and
// returns false.
bool Test::HasSameFixtureClass() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
const TestSuite* const test_suite = impl->current_test_suite();
// Info about the first test in the current test suite.
const TestInfo* const first_test_info = test_suite->test_info_list()[0];
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
const char* const first_test_name = first_test_info->name();
// Info about the current test.
const TestInfo* const this_test_info = impl->current_test_info();
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
const char* const this_test_name = this_test_info->name();
if (this_fixture_id != first_fixture_id) {
// Is the first test defined using TEST?
const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
// Is this test defined using TEST?
const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
if (first_is_TEST || this_is_TEST) {
// Both TEST and TEST_F appear in same test suite, which is incorrect.
// Tell the user how to fix this.
// Gets the name of the TEST and the name of the TEST_F. Note
// that first_is_TEST and this_is_TEST cannot both be true, as
// the fixture IDs are different for the two tests.
const char* const TEST_name =
first_is_TEST ? first_test_name : this_test_name;
const char* const TEST_F_name =
first_is_TEST ? this_test_name : first_test_name;
ADD_FAILURE()
<< "All tests in the same test suite must use the same test fixture\n"
<< "class, so mixing TEST_F and TEST in the same test suite is\n"
<< "illegal. In test suite " << this_test_info->test_suite_name()
<< ",\n"
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
<< "test " << TEST_name << " is defined using TEST. You probably\n"
<< "want to change the TEST to TEST_F or move it to another test\n"
<< "case.";
} else {
// Two fixture classes with the same name appear in two different
// namespaces, which is not allowed. Tell the user how to fix this.
ADD_FAILURE()
<< "All tests in the same test suite must use the same test fixture\n"
<< "class. However, in test suite "
<< this_test_info->test_suite_name() << ",\n"
<< "you defined test " << first_test_name << " and test "
<< this_test_name << "\n"
<< "using two different test fixture classes. This can happen if\n"
<< "the two classes are from different namespaces or translation\n"
<< "units and have the same name. You should probably rename one\n"
<< "of the classes to put the tests into different test suites.";
}
return false;
}
return true;
}
#if GTEST_HAS_SEH
// Adds an "exception thrown" fatal failure to the current test. This
// function returns its result via an output parameter pointer because VC++
// prohibits creation of objects with destructors on stack in functions
// using __try (see error C2712).
static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) {
Message message;
message << "SEH exception with code 0x" << std::setbase(16) <<
exception_code << std::setbase(10) << " thrown in " << location << ".";
return new std::string(message.GetString());
}
#endif // GTEST_HAS_SEH
namespace internal {
#if GTEST_HAS_EXCEPTIONS
// Adds an "exception thrown" fatal failure to the current test.
static std::string FormatCxxExceptionMessage(const char* description,
const char* location) {
Message message;
if (description != nullptr) {
message << "C++ exception with description \"" << description << "\"";
} else {
message << "Unknown C++ exception";
}
message << " thrown in " << location << ".";
return message.GetString();
}
static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result);
GoogleTestFailureException::GoogleTestFailureException(
const TestPartResult& failure)
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
#endif // GTEST_HAS_EXCEPTIONS
// We put these helper functions in the internal namespace as IBM's xlC
// compiler rejects the code if they were declared static.
// Runs the given method and handles SEH exceptions it throws, when
// SEH is supported; returns the 0-value for type Result in case of an
// SEH exception. (Microsoft compilers cannot handle SEH and C++
// exceptions in the same function. Therefore, we provide a separate
// wrapper function for handling SEH exceptions.)
template <class T, typename Result>
Result HandleSehExceptionsInMethodIfSupported(
T* object, Result (T::*method)(), const char* location) {
#if GTEST_HAS_SEH
__try {
return (object->*method)();
} __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
GetExceptionCode())) {
// We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try
// (see error C2712).
std::string* exception_message = FormatSehExceptionMessage(
GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message);
delete exception_message;
return static_cast<Result>(0);
}
#else
(void)location;
return (object->*method)();
#endif // GTEST_HAS_SEH
}
// Runs the given method and catches and reports C++ and/or SEH-style
// exceptions, if they are supported; returns the 0-value for type
// Result in case of an SEH exception.
template <class T, typename Result>
Result HandleExceptionsInMethodIfSupported(
T* object, Result (T::*method)(), const char* location) {
// NOTE: The user code can affect the way in which Google Test handles
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before
// RUN_ALL_TESTS() starts. It is technically possible to check the flag
// after the exception is caught and either report or re-throw the
// exception based on the flag's value:
//
// try {
// // Perform the test method.
// } catch (...) {
// if (GTEST_FLAG(catch_exceptions))
// // Report the exception as failure.
// else
// throw; // Re-throws the original exception.
// }
//
// However, the purpose of this flag is to allow the program to drop into
// the debugger when the exception is thrown. On most platforms, once the
// control enters the catch block, the exception origin information is
// lost and the debugger will stop the program at the point of the
// re-throw in this function -- instead of at the point of the original
// throw statement in the code under test. For this reason, we perform
// the check early, sacrificing the ability to affect Google Test's
// exception handling in the method where the exception is thrown.
if (internal::GetUnitTestImpl()->catch_exceptions()) {
#if GTEST_HAS_EXCEPTIONS
try {
return HandleSehExceptionsInMethodIfSupported(object, method, location);
} catch (const AssertionException&) { // NOLINT
// This failure was reported already.
} catch (const internal::GoogleTestFailureException&) { // NOLINT
// This exception type can only be thrown by a failed Google
// Test assertion with the intention of letting another testing
// framework catch it. Therefore we just re-throw it.
throw;
} catch (const std::exception& e) { // NOLINT
internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure,
FormatCxxExceptionMessage(e.what(), location));
} catch (...) { // NOLINT
internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure,
FormatCxxExceptionMessage(nullptr, location));
}
return static_cast<Result>(0);
#else
return HandleSehExceptionsInMethodIfSupported(object, method, location);
#endif // GTEST_HAS_EXCEPTIONS
} else {
return (object->*method)();
}
}
} // namespace internal
// Runs the test and updates the test result.
void Test::Run() {
if (!HasSameFixtureClass()) return;
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
// We will run the test only if SetUp() was successful and didn't call
// GTEST_SKIP().
if (!HasFatalFailure() && !IsSkipped()) {
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &Test::TestBody, "the test body");
}
// However, we want to clean up as much as possible. Hence we will
// always call TearDown(), even if SetUp() or the test body has
// failed.
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &Test::TearDown, "TearDown()");
}
// Returns true iff the current test has a fatal failure.
bool Test::HasFatalFailure() {
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
}
// Returns true iff the current test has a non-fatal failure.
bool Test::HasNonfatalFailure() {
return internal::GetUnitTestImpl()->current_test_result()->
HasNonfatalFailure();
}
// Returns true iff the current test was skipped.
bool Test::IsSkipped() {
return internal::GetUnitTestImpl()->current_test_result()->Skipped();
}
// class TestInfo
// Constructs a TestInfo object. It assumes ownership of the test factory
// object.
TestInfo::TestInfo(const std::string& a_test_suite_name,
const std::string& a_name, const char* a_type_param,
const char* a_value_param,
internal::CodeLocation a_code_location,
internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory)
: test_suite_name_(a_test_suite_name),
name_(a_name),
type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
location_(a_code_location),
fixture_class_id_(fixture_class_id),
should_run_(false),
is_disabled_(false),
matches_filter_(false),
factory_(factory),
result_() {}
// Destructs a TestInfo object.
TestInfo::~TestInfo() { delete factory_; }
namespace internal {
// Creates a new TestInfo object and registers it with Google Test;
// returns the created object.
//
// Arguments:
//
// test_suite_name: name of the test suite
// name: name of the test
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
// value_param: text representation of the test's value parameter,
// or NULL if this is not a value-parameterized test.
// code_location: code location where the test is defined
// fixture_class_id: ID of the test fixture class
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
// factory: pointer to the factory that creates a test object.
// The newly created TestInfo instance will assume
// ownership of the factory object.
TestInfo* MakeAndRegisterTestInfo(
const char* test_suite_name, const char* name, const char* type_param,
const char* value_param, CodeLocation code_location,
TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
TestInfo* const test_info =
new TestInfo(test_suite_name, name, type_param, value_param,
code_location, fixture_class_id, factory);
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
return test_info;
}
void ReportInvalidTestSuiteType(const char* test_suite_name,
CodeLocation code_location) {
Message errors;
errors
<< "Attempted redefinition of test suite " << test_suite_name << ".\n"
<< "All tests in the same test suite must use the same test fixture\n"
<< "class. However, in test suite " << test_suite_name << ", you tried\n"
<< "to define a test using a fixture class different from the one\n"
<< "used earlier. This can happen if the two fixture classes are\n"
<< "from different namespaces and have the same name. You should\n"
<< "probably rename one of the classes to put the tests into different\n"
<< "test suites.";
GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
code_location.line)
<< " " << errors.GetString();
}
} // namespace internal
namespace {
// A predicate that checks the test name of a TestInfo against a known
// value.
//
// This is used for implementation of the TestSuite class only. We put
// it in the anonymous namespace to prevent polluting the outer
// namespace.
//
// TestNameIs is copyable.
class TestNameIs {
public:
// Constructor.
//
// TestNameIs has NO default constructor.
explicit TestNameIs(const char* name)
: name_(name) {}
// Returns true iff the test name of test_info matches name_.
bool operator()(const TestInfo * test_info) const {
return test_info && test_info->name() == name_;
}
private:
std::string name_;
};
} // namespace
namespace internal {
// This method expands all parameterized tests registered with macros TEST_P
// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
// This will be done just once during the program runtime.
void UnitTestImpl::RegisterParameterizedTests() {
if (!parameterized_tests_registered_) {
parameterized_test_registry_.RegisterTests();
parameterized_tests_registered_ = true;
}
}
} // namespace internal
// Creates the test object, runs it, records its result, and then
// deletes it.
void TestInfo::Run() {
if (!should_run_) return;
// Tells UnitTest where to store test result.
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->set_current_test_info(this);
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
// Notifies the unit test event listeners that a test is about to start.
repeater->OnTestStart(*this);
const TimeInMillis start = internal::GetTimeInMillis();
impl->os_stack_trace_getter()->UponLeavingGTest();
// Creates the test object.
Test* const test = internal::HandleExceptionsInMethodIfSupported(
factory_, &internal::TestFactoryBase::CreateTest,
"the test fixture's constructor");
// Runs the test if the constructor didn't generate a fatal failure or invoke
// GTEST_SKIP().
// Note that the object will not be null
if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
// This doesn't throw as all user code that can throw are wrapped into
// exception handling code.
test->Run();
}
if (test != nullptr) {
// Deletes the test object.
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
test, &Test::DeleteSelf_, "the test fixture's destructor");
}
result_.set_elapsed_time(internal::GetTimeInMillis() - start);
// Notifies the unit test event listener that a test has just finished.
repeater->OnTestEnd(*this);
// Tells UnitTest to stop associating assertion results to this
// test.
impl->set_current_test_info(nullptr);
}
// class TestSuite
// Gets the number of successful tests in this test suite.
int TestSuite::successful_test_count() const {
return CountIf(test_info_list_, TestPassed);
}
// Gets the number of successful tests in this test suite.
int TestSuite::skipped_test_count() const {
return CountIf(test_info_list_, TestSkipped);
}
// Gets the number of failed tests in this test suite.
int TestSuite::failed_test_count() const {
return CountIf(test_info_list_, TestFailed);
}
// Gets the number of disabled tests that will be reported in the XML report.
int TestSuite::reportable_disabled_test_count() const {
return CountIf(test_info_list_, TestReportableDisabled);
}
// Gets the number of disabled tests in this test suite.
int TestSuite::disabled_test_count() const {
return CountIf(test_info_list_, TestDisabled);
}
// Gets the number of tests to be printed in the XML report.
int TestSuite::reportable_test_count() const {
return CountIf(test_info_list_, TestReportable);
}
// Get the number of tests in this test suite that should run.
int TestSuite::test_to_run_count() const {
return CountIf(test_info_list_, ShouldRunTest);
}
// Gets the number of all tests.
int TestSuite::total_test_count() const {
return static_cast<int>(test_info_list_.size());
}
// Creates a TestSuite with the given name.
//
// Arguments:
//
// name: name of the test suite
// a_type_param: the name of the test suite's type parameter, or NULL if
// this is not a typed or a type-parameterized test suite.
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
TestSuite::TestSuite(const char* a_name, const char* a_type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc)
: name_(a_name),
type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
set_up_tc_(set_up_tc),
tear_down_tc_(tear_down_tc),
should_run_(false),
elapsed_time_(0) {}
// Destructor of TestSuite.
TestSuite::~TestSuite() {
// Deletes every Test in the collection.
ForEach(test_info_list_, internal::Delete<TestInfo>);
}
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
const TestInfo* TestSuite::GetTestInfo(int i) const {
const int index = GetElementOr(test_indices_, i, -1);
return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
}
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
TestInfo* TestSuite::GetMutableTestInfo(int i) {
const int index = GetElementOr(test_indices_, i, -1);
return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
}
// Adds a test to this test suite. Will delete the test upon
// destruction of the TestSuite object.
void TestSuite::AddTestInfo(TestInfo* test_info) {
test_info_list_.push_back(test_info);
test_indices_.push_back(static_cast<int>(test_indices_.size()));
}
// Runs every test in this TestSuite.
void TestSuite::Run() {
if (!should_run_) return;
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->set_current_test_suite(this);
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
// Call both legacy and the new API
repeater->OnTestSuiteStart(*this);
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
repeater->OnTestCaseStart(*this);
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
const internal::TimeInMillis start = internal::GetTimeInMillis();
for (int i = 0; i < total_test_count(); i++) {
GetMutableTestInfo(i)->Run();
}
elapsed_time_ = internal::GetTimeInMillis() - start;
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
// Call both legacy and the new API
repeater->OnTestSuiteEnd(*this);
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
repeater->OnTestCaseEnd(*this);
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
impl->set_current_test_suite(nullptr);
}
// Clears the results of all tests in this test suite.
void TestSuite::ClearResult() {
ad_hoc_test_result_.Clear();
ForEach(test_info_list_, TestInfo::ClearTestResult);
}
// Shuffles the tests in this test suite.
void TestSuite::ShuffleTests(internal::Random* random) {
Shuffle(random, &test_indices_);
}
// Restores the test order to before the first shuffle.
void TestSuite::UnshuffleTests() {
for (size_t i = 0; i < test_indices_.size(); i++) {
test_indices_[i] = static_cast<int>(i);
}
}
// Formats a countable noun. Depending on its quantity, either the
// singular form or the plural form is used. e.g.
//
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books".
static std::string FormatCountableNoun(int count,
const char * singular_form,
const char * plural_form) {
return internal::StreamableToString(count) + " " +
(count == 1 ? singular_form : plural_form);
}
// Formats the count of tests.
static std::string FormatTestCount(int test_count) {
return FormatCountableNoun(test_count, "test", "tests");
}
// Formats the count of test suites.
static std::string FormatTestSuiteCount(int test_suite_count) {
return FormatCountableNoun(test_suite_count, "test suite", "test suites");
}
// Converts a TestPartResult::Type enum to human-friendly string
// representation. Both kNonFatalFailure and kFatalFailure are translated
// to "Failure", as the user usually doesn't care about the difference
// between the two when viewing the test result.
static const char * TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) {
case TestPartResult::kSkip:
return "Skipped";
case TestPartResult::kSuccess:
return "Success";
case TestPartResult::kNonFatalFailure:
case TestPartResult::kFatalFailure:
#ifdef _MSC_VER
return "error: ";
#else
return "Failure\n";
#endif
default:
return "Unknown result type";
}
}
namespace internal {
// Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result) {
return (Message()
<< internal::FormatFileLocation(test_part_result.file_name(),
test_part_result.line_number())
<< " " << TestPartResultTypeToString(test_part_result.type())
<< test_part_result.message()).GetString();
}
// Prints a TestPartResult.
static void PrintTestPartResult(const TestPartResult& test_part_result) {
const std::string& result =
PrintTestPartResultToString(test_part_result);
printf("%s\n", result.c_str());
fflush(stdout);
// If the test program runs in Visual Studio or a debugger, the
// following statements add the test part result message to the Output
// window such that the user can double-click on it to jump to the
// corresponding source code location; otherwise they do nothing.
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
// We don't call OutputDebugString*() on Windows Mobile, as printing
// to stdout is done by OutputDebugString() there already - we don't
// want the same message printed twice.
::OutputDebugStringA(result.c_str());
::OutputDebugStringA("\n");
#endif
}
// class PrettyUnitTestResultPrinter
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
// Returns the character attribute for the given color.
static WORD GetColorAttribute(GTestColor color) {
switch (color) {
case COLOR_RED: return FOREGROUND_RED;
case COLOR_GREEN: return FOREGROUND_GREEN;
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
default: return 0;
}
}
static int GetBitOffset(WORD color_mask) {
if (color_mask == 0) return 0;
int bitOffset = 0;
while ((color_mask & 1) == 0) {
color_mask >>= 1;
++bitOffset;
}
return bitOffset;
}
static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
// Let's reuse the BG
static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
BACKGROUND_RED | BACKGROUND_INTENSITY;
static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
FOREGROUND_RED | FOREGROUND_INTENSITY;
const WORD existing_bg = old_color_attrs & background_mask;
WORD new_color =
GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
static const int bg_bitOffset = GetBitOffset(background_mask);
static const int fg_bitOffset = GetBitOffset(foreground_mask);
if (((new_color & background_mask) >> bg_bitOffset) ==
((new_color & foreground_mask) >> fg_bitOffset)) {
new_color ^= FOREGROUND_INTENSITY; // invert intensity
}
return new_color;
}
#else
// Returns the ANSI color code for the given color. COLOR_DEFAULT is
// an invalid input.
static const char* GetAnsiColorCode(GTestColor color) {
switch (color) {
case COLOR_RED: return "1";
case COLOR_GREEN: return "2";
case COLOR_YELLOW: return "3";
default:
return nullptr;
}
}
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
// Returns true iff Google Test should use colors in the output.
bool ShouldUseColor(bool stdout_is_tty) {
const char* const gtest_color = GTEST_FLAG(color).c_str();
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
// On Windows the TERM variable is usually not set, but the
// console there does support colors.
return stdout_is_tty;
#else
// On non-Windows platforms, we rely on the TERM variable.
const char* const term = posix::GetEnv("TERM");
const bool term_supports_color =
String::CStringEquals(term, "xterm") ||
String::CStringEquals(term, "xterm-color") ||
String::CStringEquals(term, "xterm-256color") ||
String::CStringEquals(term, "screen") ||
String::CStringEquals(term, "screen-256color") ||
String::CStringEquals(term, "tmux") ||
String::CStringEquals(term, "tmux-256color") ||
String::CStringEquals(term, "rxvt-unicode") ||
String::CStringEquals(term, "rxvt-unicode-256color") ||
String::CStringEquals(term, "linux") ||
String::CStringEquals(term, "cygwin");
return stdout_is_tty && term_supports_color;
#endif // GTEST_OS_WINDOWS
}
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
String::CStringEquals(gtest_color, "1");
// We take "yes", "true", "t", and "1" as meaning "yes". If the
// value is neither one of these nor "auto", we treat it as "no" to
// be conservative.
}
// Helpers for printing colored strings to stdout. Note that on Windows, we
// cannot simply emit special characters and have the terminal change colors.
// This routine must actually emit the characters rather than return a string
// that would be colored when printed, as can be done on Linux.
void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || ESP_PLATFORM
const bool use_color = AlwaysFalse();
#else
static const bool in_color_mode =
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
if (!use_color) {
vprintf(fmt, args);
va_end(args);
return;
}
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
// Gets the current text color.
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
const WORD old_color_attrs = buffer_info.wAttributes;
const WORD new_color = GetNewColor(color, old_color_attrs);
// We need to flush the stream buffers into the console before each
// SetConsoleTextAttribute call lest it affect the text that is already
// printed but has not yet reached the console.
fflush(stdout);
SetConsoleTextAttribute(stdout_handle, new_color);
vprintf(fmt, args);
fflush(stdout);
// Restores the text color.
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
#else
printf("\033[0;3%sm", GetAnsiColorCode(color));
vprintf(fmt, args);
printf("\033[m"); // Resets the terminal to default.
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
va_end(args);
}
// Text printed in Google Test's text output and --gtest_list_tests
// output to label the type parameter and value parameter for a test.
static const char kTypeParamLabel[] = "TypeParam";
static const char kValueParamLabel[] = "GetParam()";
static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
const char* const type_param = test_info.type_param();
const char* const value_param = test_info.value_param();
if (type_param != nullptr || value_param != nullptr) {
printf(", where ");
if (type_param != nullptr) {
printf("%s = %s", kTypeParamLabel, type_param);
if (value_param != nullptr) printf(" and ");
}
if (value_param != nullptr) {
printf("%s = %s", kValueParamLabel, value_param);
}
}
}
// This class implements the TestEventListener interface.
//
// Class PrettyUnitTestResultPrinter is copyable.
class PrettyUnitTestResultPrinter : public TestEventListener {
public:
PrettyUnitTestResultPrinter() {}
static void PrintTestName(const char* test_suite, const char* test) {
printf("%s.%s", test_suite, test);
}
// The following methods override what's in the TestEventListener class.
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
void OnTestCaseStart(const TestSuite& test_suite) override;
void OnTestStart(const TestInfo& test_info) override;
void OnTestPartResult(const TestPartResult& result) override;
void OnTestEnd(const TestInfo& test_info) override;
void OnTestCaseEnd(const TestSuite& test_suite) override;
void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
private:
static void PrintFailedTests(const UnitTest& unit_test);
static void PrintSkippedTests(const UnitTest& unit_test);
};
// Fired before each iteration of tests starts.
void PrettyUnitTestResultPrinter::OnTestIterationStart(
const UnitTest& unit_test, int iteration) {
if (GTEST_FLAG(repeat) != 1)
printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
const char* const filter = GTEST_FLAG(filter).c_str();
// Prints the filter if it's not *. This reminds the user that some
// tests may be skipped.
if (!String::CStringEquals(filter, kUniversalFilter)) {
ColoredPrintf(COLOR_YELLOW,
"Note: %s filter = %s\n", GTEST_NAME_, filter);
}
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
ColoredPrintf(COLOR_YELLOW,
"Note: This is test shard %d of %s.\n",
static_cast<int>(shard_index) + 1,
internal::posix::GetEnv(kTestTotalShards));
}
if (GTEST_FLAG(shuffle)) {
ColoredPrintf(COLOR_YELLOW,
"Note: Randomizing tests' orders with a seed of %d .\n",
unit_test.random_seed());
}
ColoredPrintf(COLOR_GREEN, "[==========] ");
printf("Running %s from %s.\n",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
const UnitTest& /*unit_test*/) {
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("Global test environment set-up.\n");
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) {
const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("%s from %s", counts.c_str(), test_suite.name());
if (test_suite.type_param() == nullptr) {
printf("\n");
} else {
printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
}
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
PrintTestName(test_info.test_suite_name(), test_info.name());
printf("\n");
fflush(stdout);
}
// Called after an assertion failure.
void PrettyUnitTestResultPrinter::OnTestPartResult(
const TestPartResult& result) {
switch (result.type()) {
// If the test part succeeded, or was skipped,
// we don't need to do anything.
case TestPartResult::kSkip:
case TestPartResult::kSuccess:
return;
default:
// Print failure message from the assertion
// (e.g. expected this and got that).
PrintTestPartResult(result);
fflush(stdout);
}
}
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
if (test_info.result()->Passed()) {
ColoredPrintf(COLOR_GREEN, "[ OK ] ");
} else if (test_info.result()->Skipped()) {
ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
} else {
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
}
PrintTestName(test_info.test_suite_name(), test_info.name());
if (test_info.result()->Failed())
PrintFullTestCommentIfPresent(test_info);
if (GTEST_FLAG(print_time)) {
printf(" (%s ms)\n", internal::StreamableToString(
test_info.result()->elapsed_time()).c_str());
} else {
printf("\n");
}
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) {
if (!GTEST_FLAG(print_time)) return;
const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
internal::StreamableToString(test_suite.elapsed_time()).c_str());
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
const UnitTest& /*unit_test*/) {
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("Global test environment tear-down\n");
fflush(stdout);
}
// Internal helper for printing the list of failed tests.
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
const int failed_test_count = unit_test.failed_test_count();
if (failed_test_count == 0) {
return;
}
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
continue;
}
for (int j = 0; j < test_suite.total_test_count(); ++j) {
const TestInfo& test_info = *test_suite.GetTestInfo(j);
if (!test_info.should_run() || !test_info.result()->Failed()) {
continue;
}
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s.%s", test_suite.name(), test_info.name());
PrintFullTestCommentIfPresent(test_info);
printf("\n");
}
}
}
// Internal helper for printing the list of skipped tests.
void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
const int skipped_test_count = unit_test.skipped_test_count();
if (skipped_test_count == 0) {
return;
}
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
continue;
}
for (int j = 0; j < test_suite.total_test_count(); ++j) {
const TestInfo& test_info = *test_suite.GetTestInfo(j);
if (!test_info.should_run() || !test_info.result()->Skipped()) {
continue;
}
ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
printf("%s.%s", test_suite.name(), test_info.name());
printf("\n");
}
}
}
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
ColoredPrintf(COLOR_GREEN, "[==========] ");
printf("%s from %s ran.",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
if (GTEST_FLAG(print_time)) {
printf(" (%s ms total)",
internal::StreamableToString(unit_test.elapsed_time()).c_str());
}
printf("\n");
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
const int skipped_test_count = unit_test.skipped_test_count();
if (skipped_test_count > 0) {
ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
PrintSkippedTests(unit_test);
}
int num_failures = unit_test.failed_test_count();
if (!unit_test.Passed()) {
const int failed_test_count = unit_test.failed_test_count();
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
PrintFailedTests(unit_test);
printf("\n%2d FAILED %s\n", num_failures,
num_failures == 1 ? "TEST" : "TESTS");
}
int num_disabled = unit_test.reportable_disabled_test_count();
if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
if (!num_failures) {
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
}
ColoredPrintf(COLOR_YELLOW,
" YOU HAVE %d DISABLED %s\n\n",
num_disabled,
num_disabled == 1 ? "TEST" : "TESTS");
}
// Ensure that Google Test output is printed before, e.g., heapchecker output.
fflush(stdout);
}
// End PrettyUnitTestResultPrinter
// class TestEventRepeater
//
// This class forwards events to other event listeners.
class TestEventRepeater : public TestEventListener {
public:
TestEventRepeater() : forwarding_enabled_(true) {}
~TestEventRepeater() override;
void Append(TestEventListener *listener);
TestEventListener* Release(TestEventListener* listener);
// Controls whether events will be forwarded to listeners_. Set to false
// in death test child processes.
bool forwarding_enabled() const { return forwarding_enabled_; }
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
void OnTestProgramStart(const UnitTest& unit_test) override;
void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
void OnTestCaseStart(const TestSuite& parameter) override;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
void OnTestSuiteStart(const TestSuite& parameter) override;
void OnTestStart(const TestInfo& test_info) override;
void OnTestPartResult(const TestPartResult& result) override;
void OnTestEnd(const TestInfo& test_info) override;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
void OnTestCaseEnd(const TestSuite& parameter) override;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
void OnTestSuiteEnd(const TestSuite& parameter) override;
void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
void OnTestProgramEnd(const UnitTest& unit_test) override;
private:
// Controls whether events will be forwarded to listeners_. Set to false
// in death test child processes.
bool forwarding_enabled_;
// The list of listeners that receive events.
std::vector<TestEventListener*> listeners_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
};
TestEventRepeater::~TestEventRepeater() {
ForEach(listeners_, Delete<TestEventListener>);
}
void TestEventRepeater::Append(TestEventListener *listener) {
listeners_.push_back(listener);
}
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
for (size_t i = 0; i < listeners_.size(); ++i) {
if (listeners_[i] == listener) {
listeners_.erase(listeners_.begin() + static_cast<int>(i));
return listener;
}
}
return nullptr;
}
// Since most methods are very similar, use macros to reduce boilerplate.
// This defines a member that forwards the call to all listeners.
#define GTEST_REPEATER_METHOD_(Name, Type) \
void TestEventRepeater::Name(const Type& parameter) { \
if (forwarding_enabled_) { \
for (size_t i = 0; i < listeners_.size(); i++) { \
listeners_[i]->Name(parameter); \
} \
} \
}
// This defines a member that forwards the call to all listeners in reverse
// order.
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
void TestEventRepeater::Name(const Type& parameter) { \
if (forwarding_enabled_) { \
for (size_t i = listeners_.size(); i != 0; i--) { \
listeners_[i - 1]->Name(parameter); \
} \
} \
}
GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
#undef GTEST_REPEATER_METHOD_
#undef GTEST_REVERSE_REPEATER_METHOD_
void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
int iteration) {
if (forwarding_enabled_) {
for (size_t i = 0; i < listeners_.size(); i++) {
listeners_[i]->OnTestIterationStart(unit_test, iteration);
}
}
}
void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
int iteration) {
if (forwarding_enabled_) {
for (size_t i = listeners_.size(); i > 0; i--) {
listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
}
}
}
// End TestEventRepeater
// This class generates an XML output file.
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
public:
explicit XmlUnitTestResultPrinter(const char* output_file);
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
// Prints an XML summary of all unit tests.
static void PrintXmlTestsList(std::ostream* stream,
const std::vector<TestSuite*>& test_suites);
private:
// Is c a whitespace character that is normalized to a space character
// when it appears in an XML attribute value?
static bool IsNormalizableWhitespace(char c) {
return c == 0x9 || c == 0xA || c == 0xD;
}
// May c appear in a well-formed XML document?
static bool IsValidXmlCharacter(char c) {
return IsNormalizableWhitespace(c) || c >= 0x20;
}
// Returns an XML-escaped copy of the input string str. If
// is_attribute is true, the text is meant to appear as an attribute
// value, and normalizable whitespace is preserved by replacing it
// with character references.
static std::string EscapeXml(const std::string& str, bool is_attribute);
// Returns the given string with all characters invalid in XML removed.
static std::string RemoveInvalidXmlCharacters(const std::string& str);
// Convenience wrapper around EscapeXml when str is an attribute value.
static std::string EscapeXmlAttribute(const std::string& str) {
return EscapeXml(str, true);
}
// Convenience wrapper around EscapeXml when str is not an attribute value.
static std::string EscapeXmlText(const char* str) {
return EscapeXml(str, false);
}
// Verifies that the given attribute belongs to the given element and
// streams the attribute as XML.
static void OutputXmlAttribute(std::ostream* stream,
const std::string& element_name,
const std::string& name,
const std::string& value);
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
// Streams an XML representation of a TestInfo object.
static void OutputXmlTestInfo(::std::ostream* stream,
const char* test_suite_name,
const TestInfo& test_info);
// Prints an XML representation of a TestSuite object
static void PrintXmlTestSuite(::std::ostream* stream,
const TestSuite& test_suite);
// Prints an XML summary of unit_test to output stream out.
static void PrintXmlUnitTest(::std::ostream* stream,
const UnitTest& unit_test);
// Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs.
// When the std::string is not empty, it includes a space at the beginning,
// to delimit this attribute from prior attributes.
static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
// Streams an XML representation of the test properties of a TestResult
// object.
static void OutputXmlTestProperties(std::ostream* stream,
const TestResult& result);
// The output file.
const std::string output_file_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
};
// Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
: output_file_(output_file) {
if (output_file_.empty()) {
GTEST_LOG_(FATAL) << "XML output file may not be null";
}
}
// Called after the unit test ends.
void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
FILE* xmlout = OpenFileForWriting(output_file_);
std::stringstream stream;
PrintXmlUnitTest(&stream, unit_test);
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
fclose(xmlout);
}
void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
const std::vector<TestSuite*>& test_suites) {
FILE* xmlout = OpenFileForWriting(output_file_);
std::stringstream stream;
PrintXmlTestsList(&stream, test_suites);
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
fclose(xmlout);
}
// Returns an XML-escaped copy of the input string str. If is_attribute
// is true, the text is meant to appear as an attribute value, and
// normalizable whitespace is preserved by replacing it with character
// references.
//
// Invalid XML characters in str, if any, are stripped from the output.
// It is expected that most, if not all, of the text processed by this
// module will consist of ordinary English text.
// If this module is ever modified to produce version 1.1 XML output,
// most invalid characters can be retained using character references.
std::string XmlUnitTestResultPrinter::EscapeXml(
const std::string& str, bool is_attribute) {
Message m;
for (size_t i = 0; i < str.size(); ++i) {
const char ch = str[i];
switch (ch) {
case '<':
m << "<";
break;
case '>':
m << ">";
break;
case '&':
m << "&";
break;
case '\'':
if (is_attribute)
m << "'";
else
m << '\'';
break;
case '"':
if (is_attribute)
m << """;
else
m << '"';
break;
default:
if (IsValidXmlCharacter(ch)) {
if (is_attribute && IsNormalizableWhitespace(ch))
m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
<< ";";
else
m << ch;
}
break;
}
}
return m.GetString();
}
// Returns the given string with all characters invalid in XML removed.
// Currently invalid characters are dropped from the string. An
// alternative is to replace them with certain characters such as . or ?.
std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
const std::string& str) {
std::string output;
output.reserve(str.size());
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
if (IsValidXmlCharacter(*it))
output.push_back(*it);
return output;
}
// The following routines generate an XML representation of a UnitTest
// object.
// GOOGLETEST_CM0009 DO NOT DELETE
//
// This is how Google Test concepts map to the DTD:
//
// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
// <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
// <testcase name="test-name"> <-- corresponds to a TestInfo object
// <failure message="...">...</failure>
// <failure message="...">...</failure>
// <failure message="...">...</failure>
// <-- individual assertion failures
// </testcase>
// </testsuite>
// </testsuites>
// Formats the given time in milliseconds as seconds.
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
::std::stringstream ss;
ss << (static_cast<double>(ms) * 1e-3);
return ss.str();
}
static bool PortableLocaltime(time_t seconds, struct tm* out) {
#if defined(_MSC_VER)
return localtime_s(out, &seconds) == 0;
#elif defined(__MINGW32__) || defined(__MINGW64__)
// MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
// Windows' localtime(), which has a thread-local tm buffer.
struct tm* tm_ptr = localtime(&seconds); // NOLINT
if (tm_ptr == nullptr) return false;
*out = *tm_ptr;
return true;
#else
return localtime_r(&seconds, out) != nullptr;
#endif
}
// Converts the given epoch time in milliseconds to a date string in the ISO
// 8601 format, without the timezone information.
std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
struct tm time_struct;
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
return "";
// YYYY-MM-DDThh:mm:ss
return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" +
String::FormatIntWidth2(time_struct.tm_sec);
}
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
const char* data) {
const char* segment = data;
*stream << "<![CDATA[";
for (;;) {
const char* const next_segment = strstr(segment, "]]>");
if (next_segment != nullptr) {
stream->write(
segment, static_cast<std::streamsize>(next_segment - segment));
*stream << "]]>]]><![CDATA[";
segment = next_segment + strlen("]]>");
} else {
*stream << segment;
break;
}
}
*stream << "]]>";
}
void XmlUnitTestResultPrinter::OutputXmlAttribute(
std::ostream* stream,
const std::string& element_name,
const std::string& name,
const std::string& value) {
const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end())
<< "Attribute " << name << " is not allowed for element <" << element_name
<< ">.";
*stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
}
// Prints an XML representation of a TestInfo object.
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
const char* test_suite_name,
const TestInfo& test_info) {
const TestResult& result = *test_info.result();
const std::string kTestsuite = "testcase";
if (test_info.is_in_another_shard()) {
return;
}
*stream << " <testcase";
OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
if (test_info.value_param() != nullptr) {
OutputXmlAttribute(stream, kTestsuite, "value_param",
test_info.value_param());
}
if (test_info.type_param() != nullptr) {
OutputXmlAttribute(stream, kTestsuite, "type_param",
test_info.type_param());
}
if (GTEST_FLAG(list_tests)) {
OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
OutputXmlAttribute(stream, kTestsuite, "line",
StreamableToString(test_info.line()));
*stream << " />\n";
return;
}
OutputXmlAttribute(stream, kTestsuite, "status",
test_info.should_run() ? "run" : "notrun");
OutputXmlAttribute(stream, kTestsuite, "result",
test_info.should_run()
? (result.Skipped() ? "skipped" : "completed")
: "suppressed");
OutputXmlAttribute(stream, kTestsuite, "time",
FormatTimeInMillisAsSeconds(result.elapsed_time()));
OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
int failures = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
if (part.failed()) {
if (++failures == 1) {
*stream << ">\n";
}
const std::string location =
internal::FormatCompilerIndependentFileLocation(part.file_name(),
part.line_number());
const std::string summary = location + "\n" + part.summary();
*stream << " <failure message=\""
<< EscapeXmlAttribute(summary.c_str())
<< "\" type=\"\">";
const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</failure>\n";
}
}
if (failures == 0 && result.test_property_count() == 0) {
*stream << " />\n";
} else {
if (failures == 0) {
*stream << ">\n";
}
OutputXmlTestProperties(stream, result);
*stream << " </testcase>\n";
}
}
// Prints an XML representation of a TestSuite object
void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
const TestSuite& test_suite) {
const std::string kTestsuite = "testsuite";
*stream << " <" << kTestsuite;
OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
OutputXmlAttribute(stream, kTestsuite, "tests",
StreamableToString(test_suite.reportable_test_count()));
if (!GTEST_FLAG(list_tests)) {
OutputXmlAttribute(stream, kTestsuite, "failures",
StreamableToString(test_suite.failed_test_count()));
OutputXmlAttribute(
stream, kTestsuite, "disabled",
StreamableToString(test_suite.reportable_disabled_test_count()));
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
OutputXmlAttribute(stream, kTestsuite, "time",
FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
*stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
}
*stream << ">\n";
for (int i = 0; i < test_suite.total_test_count(); ++i) {
if (test_suite.GetTestInfo(i)->is_reportable())
OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
}
*stream << " </" << kTestsuite << ">\n";
}
// Prints an XML summary of unit_test to output stream out.
void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
const UnitTest& unit_test) {
const std::string kTestsuites = "testsuites";
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
*stream << "<" << kTestsuites;
OutputXmlAttribute(stream, kTestsuites, "tests",
StreamableToString(unit_test.reportable_test_count()));
OutputXmlAttribute(stream, kTestsuites, "failures",
StreamableToString(unit_test.failed_test_count()));
OutputXmlAttribute(
stream, kTestsuites, "disabled",
StreamableToString(unit_test.reportable_disabled_test_count()));
OutputXmlAttribute(stream, kTestsuites, "errors", "0");
OutputXmlAttribute(
stream, kTestsuites, "timestamp",
FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
OutputXmlAttribute(stream, kTestsuites, "time",
FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
if (GTEST_FLAG(shuffle)) {
OutputXmlAttribute(stream, kTestsuites, "random_seed",
StreamableToString(unit_test.random_seed()));
}
*stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
*stream << ">\n";
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
}
*stream << "</" << kTestsuites << ">\n";
}
void XmlUnitTestResultPrinter::PrintXmlTestsList(
std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
const std::string kTestsuites = "testsuites";
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
*stream << "<" << kTestsuites;
int total_tests = 0;
for (auto test_suite : test_suites) {
total_tests += test_suite->total_test_count();
}
OutputXmlAttribute(stream, kTestsuites, "tests",
StreamableToString(total_tests));
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
*stream << ">\n";
for (auto test_suite : test_suites) {
PrintXmlTestSuite(stream, *test_suite);
}
*stream << "</" << kTestsuites << ">\n";
}
// Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs.
std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
const TestResult& result) {
Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
attributes << " " << property.key() << "="
<< "\"" << EscapeXmlAttribute(property.value()) << "\"";
}
return attributes.GetString();
}
void XmlUnitTestResultPrinter::OutputXmlTestProperties(
std::ostream* stream, const TestResult& result) {
const std::string kProperties = "properties";
const std::string kProperty = "property";
if (result.test_property_count() <= 0) {
return;
}
*stream << "<" << kProperties << ">\n";
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
*stream << "<" << kProperty;
*stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
*stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
*stream << "/>\n";
}
*stream << "</" << kProperties << ">\n";
}
// End XmlUnitTestResultPrinter
// This class generates an JSON output file.
class JsonUnitTestResultPrinter : public EmptyTestEventListener {
public:
explicit JsonUnitTestResultPrinter(const char* output_file);
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
// Prints an JSON summary of all unit tests.
static void PrintJsonTestList(::std::ostream* stream,
const std::vector<TestSuite*>& test_suites);
private:
// Returns an JSON-escaped copy of the input string str.
static std::string EscapeJson(const std::string& str);
//// Verifies that the given attribute belongs to the given element and
//// streams the attribute as JSON.
static void OutputJsonKey(std::ostream* stream,
const std::string& element_name,
const std::string& name,
const std::string& value,
const std::string& indent,
bool comma = true);
static void OutputJsonKey(std::ostream* stream,
const std::string& element_name,
const std::string& name,
int value,
const std::string& indent,
bool comma = true);
// Streams a JSON representation of a TestInfo object.
static void OutputJsonTestInfo(::std::ostream* stream,
const char* test_suite_name,
const TestInfo& test_info);
// Prints a JSON representation of a TestSuite object
static void PrintJsonTestSuite(::std::ostream* stream,
const TestSuite& test_suite);
// Prints a JSON summary of unit_test to output stream out.
static void PrintJsonUnitTest(::std::ostream* stream,
const UnitTest& unit_test);
// Produces a string representing the test properties in a result as
// a JSON dictionary.
static std::string TestPropertiesAsJson(const TestResult& result,
const std::string& indent);
// The output file.
const std::string output_file_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
};
// Creates a new JsonUnitTestResultPrinter.
JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
: output_file_(output_file) {
if (output_file_.empty()) {
GTEST_LOG_(FATAL) << "JSON output file may not be null";
}
}
void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
FILE* jsonout = OpenFileForWriting(output_file_);
std::stringstream stream;
PrintJsonUnitTest(&stream, unit_test);
fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
fclose(jsonout);
}
// Returns an JSON-escaped copy of the input string str.
std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
Message m;
for (size_t i = 0; i < str.size(); ++i) {
const char ch = str[i];
switch (ch) {
case '\\':
case '"':
case '/':
m << '\\' << ch;
break;
case '\b':
m << "\\b";
break;
case '\t':
m << "\\t";
break;
case '\n':
m << "\\n";
break;
case '\f':
m << "\\f";
break;
case '\r':
m << "\\r";
break;
default:
if (ch < ' ') {
m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
} else {
m << ch;
}
break;
}
}
return m.GetString();
}
// The following routines generate an JSON representation of a UnitTest
// object.
// Formats the given time in milliseconds as seconds.
static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
::std::stringstream ss;
ss << (static_cast<double>(ms) * 1e-3) << "s";
return ss.str();
}
// Converts the given epoch time in milliseconds to a date string in the
// RFC3339 format, without the timezone information.
static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
struct tm time_struct;
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
return "";
// YYYY-MM-DDThh:mm:ss
return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" +
String::FormatIntWidth2(time_struct.tm_sec) + "Z";
}
static inline std::string Indent(size_t width) {
return std::string(width, ' ');
}
void JsonUnitTestResultPrinter::OutputJsonKey(
std::ostream* stream,
const std::string& element_name,
const std::string& name,
const std::string& value,
const std::string& indent,
bool comma) {
const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end())
<< "Key \"" << name << "\" is not allowed for value \"" << element_name
<< "\".";
*stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
if (comma)
*stream << ",\n";
}
void JsonUnitTestResultPrinter::OutputJsonKey(
std::ostream* stream,
const std::string& element_name,
const std::string& name,
int value,
const std::string& indent,
bool comma) {
const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end())
<< "Key \"" << name << "\" is not allowed for value \"" << element_name
<< "\".";
*stream << indent << "\"" << name << "\": " << StreamableToString(value);
if (comma)
*stream << ",\n";
}
// Prints a JSON representation of a TestInfo object.
void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
const char* test_suite_name,
const TestInfo& test_info) {
const TestResult& result = *test_info.result();
const std::string kTestsuite = "testcase";
const std::string kIndent = Indent(10);
*stream << Indent(8) << "{\n";
OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
if (test_info.value_param() != nullptr) {
OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
kIndent);
}
if (test_info.type_param() != nullptr) {
OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
kIndent);
}
if (GTEST_FLAG(list_tests)) {
OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
*stream << "\n" << Indent(8) << "}";
return;
}
OutputJsonKey(stream, kTestsuite, "status",
test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
OutputJsonKey(stream, kTestsuite, "result",
test_info.should_run()
? (result.Skipped() ? "SKIPPED" : "COMPLETED")
: "SUPPRESSED",
kIndent);
OutputJsonKey(stream, kTestsuite, "time",
FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
false);
*stream << TestPropertiesAsJson(result, kIndent);
int failures = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
if (part.failed()) {
*stream << ",\n";
if (++failures == 1) {
*stream << kIndent << "\"" << "failures" << "\": [\n";
}
const std::string location =
internal::FormatCompilerIndependentFileLocation(part.file_name(),
part.line_number());
const std::string message = EscapeJson(location + "\n" + part.message());
*stream << kIndent << " {\n"
<< kIndent << " \"failure\": \"" << message << "\",\n"
<< kIndent << " \"type\": \"\"\n"
<< kIndent << " }";
}
}
if (failures > 0)
*stream << "\n" << kIndent << "]";
*stream << "\n" << Indent(8) << "}";
}
// Prints an JSON representation of a TestSuite object
void JsonUnitTestResultPrinter::PrintJsonTestSuite(
std::ostream* stream, const TestSuite& test_suite) {
const std::string kTestsuite = "testsuite";
const std::string kIndent = Indent(6);
*stream << Indent(4) << "{\n";
OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
kIndent);
if (!GTEST_FLAG(list_tests)) {
OutputJsonKey(stream, kTestsuite, "failures",
test_suite.failed_test_count(), kIndent);
OutputJsonKey(stream, kTestsuite, "disabled",
test_suite.reportable_disabled_test_count(), kIndent);
OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
OutputJsonKey(stream, kTestsuite, "time",
FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
kIndent, false);
*stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
<< ",\n";
}
*stream << kIndent << "\"" << kTestsuite << "\": [\n";
bool comma = false;
for (int i = 0; i < test_suite.total_test_count(); ++i) {
if (test_suite.GetTestInfo(i)->is_reportable()) {
if (comma) {
*stream << ",\n";
} else {
comma = true;
}
OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
}
}
*stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
}
// Prints a JSON summary of unit_test to output stream out.
void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
const UnitTest& unit_test) {
const std::string kTestsuites = "testsuites";
const std::string kIndent = Indent(2);
*stream << "{\n";
OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
kIndent);
OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
kIndent);
OutputJsonKey(stream, kTestsuites, "disabled",
unit_test.reportable_disabled_test_count(), kIndent);
OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
if (GTEST_FLAG(shuffle)) {
OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
kIndent);
}
OutputJsonKey(stream, kTestsuites, "timestamp",
FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
kIndent);
OutputJsonKey(stream, kTestsuites, "time",
FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
false);
*stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
<< ",\n";
OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
*stream << kIndent << "\"" << kTestsuites << "\": [\n";
bool comma = false;
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
if (comma) {
*stream << ",\n";
} else {
comma = true;
}
PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
}
}
*stream << "\n" << kIndent << "]\n" << "}\n";
}
void JsonUnitTestResultPrinter::PrintJsonTestList(
std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
const std::string kTestsuites = "testsuites";
const std::string kIndent = Indent(2);
*stream << "{\n";
int total_tests = 0;
for (auto test_suite : test_suites) {
total_tests += test_suite->total_test_count();
}
OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
*stream << kIndent << "\"" << kTestsuites << "\": [\n";
for (size_t i = 0; i < test_suites.size(); ++i) {
if (i != 0) {
*stream << ",\n";
}
PrintJsonTestSuite(stream, *test_suites[i]);
}
*stream << "\n"
<< kIndent << "]\n"
<< "}\n";
}
// Produces a string representing the test properties in a result as
// a JSON dictionary.
std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
const TestResult& result, const std::string& indent) {
Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
attributes << ",\n" << indent << "\"" << property.key() << "\": "
<< "\"" << EscapeJson(property.value()) << "\"";
}
return attributes.GetString();
}
// End JsonUnitTestResultPrinter
#if GTEST_CAN_STREAM_RESULTS_
// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
// replaces them by "%xx" where xx is their hexadecimal value. For
// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
// in both time and space -- important as the input str may contain an
// arbitrarily long test failure message and stack trace.
std::string StreamingListener::UrlEncode(const char* str) {
std::string result;
result.reserve(strlen(str) + 1);
for (char ch = *str; ch != '\0'; ch = *++str) {
switch (ch) {
case '%':
case '=':
case '&':
case '\n':
result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
break;
default:
result.push_back(ch);
break;
}
}
return result;
}
void StreamingListener::SocketWriter::MakeConnection() {
GTEST_CHECK_(sockfd_ == -1)
<< "MakeConnection() can't be called when there is already a connection.";
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
hints.ai_socktype = SOCK_STREAM;
addrinfo* servinfo = nullptr;
// Use the getaddrinfo() to get a linked list of IP addresses for
// the given host name.
const int error_num = getaddrinfo(
host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
if (error_num != 0) {
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
<< gai_strerror(error_num);
}
// Loop through all the results and connect to the first we can.
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
cur_addr = cur_addr->ai_next) {
sockfd_ = socket(
cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
if (sockfd_ != -1) {
// Connect the client socket to the server socket.
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
close(sockfd_);
sockfd_ = -1;
}
}
}
freeaddrinfo(servinfo); // all done with this structure
if (sockfd_ == -1) {
GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
<< host_name_ << ":" << port_num_;
}
}
// End of class Streaming Listener
#endif // GTEST_CAN_STREAM_RESULTS__
// class OsStackTraceGetter
const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
"... " GTEST_NAME_ " internal frames ...";
std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_) {
#if GTEST_HAS_ABSL
std::string result;
if (max_depth <= 0) {
return result;
}
max_depth = std::min(max_depth, kMaxStackTraceDepth);
std::vector<void*> raw_stack(max_depth);
// Skips the frames requested by the caller, plus this function.
const int raw_stack_size =
absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
void* caller_frame = nullptr;
{
MutexLock lock(&mutex_);
caller_frame = caller_frame_;
}
for (int i = 0; i < raw_stack_size; ++i) {
if (raw_stack[i] == caller_frame &&
!GTEST_FLAG(show_internal_stack_frames)) {
// Add a marker to the trace and stop adding frames.
absl::StrAppend(&result, kElidedFramesMarker, "\n");
break;
}
char tmp[1024];
const char* symbol = "(unknown)";
if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
symbol = tmp;
}
char line[1024];
snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
result += line;
}
return result;
#else // !GTEST_HAS_ABSL
static_cast<void>(max_depth);
static_cast<void>(skip_count);
return "";
#endif // GTEST_HAS_ABSL
}
void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
#if GTEST_HAS_ABSL
void* caller_frame = nullptr;
if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
caller_frame = nullptr;
}
MutexLock lock(&mutex_);
caller_frame_ = caller_frame;
#endif // GTEST_HAS_ABSL
}
// A helper class that creates the premature-exit file in its
// constructor and deletes the file in its destructor.
class ScopedPrematureExitFile {
public:
explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
: premature_exit_filepath_(premature_exit_filepath ?
premature_exit_filepath : "") {
// If a path to the premature-exit file is specified...
if (!premature_exit_filepath_.empty()) {
// create the file with a single "0" character in it. I/O
// errors are ignored as there's nothing better we can do and we
// don't want to fail the test because of this.
FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
fwrite("0", 1, 1, pfile);
fclose(pfile);
}
}
~ScopedPrematureExitFile() {
if (!premature_exit_filepath_.empty()) {
int retval = remove(premature_exit_filepath_.c_str());
if (retval) {
GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
<< premature_exit_filepath_ << "\" with error "
<< retval;
}
}
}
private:
const std::string premature_exit_filepath_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
};
} // namespace internal
// class TestEventListeners
TestEventListeners::TestEventListeners()
: repeater_(new internal::TestEventRepeater()),
default_result_printer_(nullptr),
default_xml_generator_(nullptr) {}
TestEventListeners::~TestEventListeners() { delete repeater_; }
// Returns the standard listener responsible for the default console
// output. Can be removed from the listeners list to shut down default
// console output. Note that removing this object from the listener list
// with Release transfers its ownership to the user.
void TestEventListeners::Append(TestEventListener* listener) {
repeater_->Append(listener);
}
// Removes the given event listener from the list and returns it. It then
// becomes the caller's responsibility to delete the listener. Returns
// NULL if the listener is not found in the list.
TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
if (listener == default_result_printer_)
default_result_printer_ = nullptr;
else if (listener == default_xml_generator_)
default_xml_generator_ = nullptr;
return repeater_->Release(listener);
}
// Returns repeater that broadcasts the TestEventListener events to all
// subscribers.
TestEventListener* TestEventListeners::repeater() { return repeater_; }
// Sets the default_result_printer attribute to the provided listener.
// The listener is also added to the listener list and previous
// default_result_printer is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
if (default_result_printer_ != listener) {
// It is an error to pass this method a listener that is already in the
// list.
delete Release(default_result_printer_);
default_result_printer_ = listener;
if (listener != nullptr) Append(listener);
}
}
// Sets the default_xml_generator attribute to the provided listener. The
// listener is also added to the listener list and previous
// default_xml_generator is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
if (default_xml_generator_ != listener) {
// It is an error to pass this method a listener that is already in the
// list.
delete Release(default_xml_generator_);
default_xml_generator_ = listener;
if (listener != nullptr) Append(listener);
}
}
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool TestEventListeners::EventForwardingEnabled() const {
return repeater_->forwarding_enabled();
}
void TestEventListeners::SuppressEventForwarding() {
repeater_->set_forwarding_enabled(false);
}
// class UnitTest
// Gets the singleton UnitTest object. The first time this method is
// called, a UnitTest object is constructed and returned. Consecutive
// calls will return the same object.
//
// We don't protect this under mutex_ as a user is not supposed to
// call this before main() starts, from which point on the return
// value will never change.
UnitTest* UnitTest::GetInstance() {
// CodeGear C++Builder insists on a public destructor for the
// default implementation. Use this implementation to keep good OO
// design with private destructor.
#if defined(__BORLANDC__)
static UnitTest* const instance = new UnitTest;
return instance;
#else
static UnitTest instance;
return &instance;
#endif // defined(__BORLANDC__)
}
// Gets the number of successful test suites.
int UnitTest::successful_test_suite_count() const {
return impl()->successful_test_suite_count();
}
// Gets the number of failed test suites.
int UnitTest::failed_test_suite_count() const {
return impl()->failed_test_suite_count();
}
// Gets the number of all test suites.
int UnitTest::total_test_suite_count() const {
return impl()->total_test_suite_count();
}
// Gets the number of all test suites that contain at least one test
// that should run.
int UnitTest::test_suite_to_run_count() const {
return impl()->test_suite_to_run_count();
}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
int UnitTest::successful_test_case_count() const {
return impl()->successful_test_suite_count();
}
int UnitTest::failed_test_case_count() const {
return impl()->failed_test_suite_count();
}
int UnitTest::total_test_case_count() const {
return impl()->total_test_suite_count();
}
int UnitTest::test_case_to_run_count() const {
return impl()->test_suite_to_run_count();
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Gets the number of successful tests.
int UnitTest::successful_test_count() const {
return impl()->successful_test_count();
}
// Gets the number of skipped tests.
int UnitTest::skipped_test_count() const {
return impl()->skipped_test_count();
}
// Gets the number of failed tests.
int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
// Gets the number of disabled tests that will be reported in the XML report.
int UnitTest::reportable_disabled_test_count() const {
return impl()->reportable_disabled_test_count();
}
// Gets the number of disabled tests.
int UnitTest::disabled_test_count() const {
return impl()->disabled_test_count();
}
// Gets the number of tests to be printed in the XML report.
int UnitTest::reportable_test_count() const {
return impl()->reportable_test_count();
}
// Gets the number of all tests.
int UnitTest::total_test_count() const { return impl()->total_test_count(); }
// Gets the number of tests that should run.
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
internal::TimeInMillis UnitTest::start_timestamp() const {
return impl()->start_timestamp();
}
// Gets the elapsed time, in milliseconds.
internal::TimeInMillis UnitTest::elapsed_time() const {
return impl()->elapsed_time();
}
// Returns true iff the unit test passed (i.e. all test suites passed).
bool UnitTest::Passed() const { return impl()->Passed(); }
// Returns true iff the unit test failed (i.e. some test suite failed
// or something outside of all tests failed).
bool UnitTest::Failed() const { return impl()->Failed(); }
// Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
const TestSuite* UnitTest::GetTestSuite(int i) const {
return impl()->GetTestSuite(i);
}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* UnitTest::GetTestCase(int i) const {
return impl()->GetTestCase(i);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Returns the TestResult containing information on test failures and
// properties logged outside of individual test suites.
const TestResult& UnitTest::ad_hoc_test_result() const {
return *impl()->ad_hoc_test_result();
}
// Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
TestSuite* UnitTest::GetMutableTestSuite(int i) {
return impl()->GetMutableSuiteCase(i);
}
// Returns the list of event listeners that can be used to track events
// inside Google Test.
TestEventListeners& UnitTest::listeners() {
return *impl()->listeners();
}
// Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in the
// order they were registered. After all tests in the program have
// finished, all global test environments will be torn-down in the
// *reverse* order they were registered.
//
// The UnitTest object takes ownership of the given environment.
//
// We don't protect this under mutex_, as we only support calling it
// from the main thread.
Environment* UnitTest::AddEnvironment(Environment* env) {
if (env == nullptr) {
return nullptr;
}
impl_->environments().push_back(env);
return env;
}
// Adds a TestPartResult to the current TestResult object. All Google Test
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
// this to report their results. The user code should use the
// assertion macros instead of calling this directly.
void UnitTest::AddTestPartResult(
TestPartResult::Type result_type,
const char* file_name,
int line_number,
const std::string& message,
const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
Message msg;
msg << message;
internal::MutexLock lock(&mutex_);
if (impl_->gtest_trace_stack().size() > 0) {
msg << "\n" << GTEST_NAME_ << " trace:";
for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
<< " " << trace.message;
}
}
if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
msg << internal::kStackTraceMarker << os_stack_trace;
}
const TestPartResult result = TestPartResult(
result_type, file_name, line_number, msg.GetString().c_str());
impl_->GetTestPartResultReporterForCurrentThread()->
ReportTestPartResult(result);
if (result_type != TestPartResult::kSuccess &&
result_type != TestPartResult::kSkip) {
// gtest_break_on_failure takes precedence over
// gtest_throw_on_failure. This allows a user to set the latter
// in the code (perhaps in order to use Google Test assertions
// with another testing framework) and specify the former on the
// command line for debugging.
if (GTEST_FLAG(break_on_failure)) {
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
// Using DebugBreak on Windows allows gtest to still break into a debugger
// when a failure happens and both the --gtest_break_on_failure and
// the --gtest_catch_exceptions flags are specified.
DebugBreak();
#elif (!defined(__native_client__)) && \
((defined(__clang__) || defined(__GNUC__)) && \
(defined(__x86_64__) || defined(__i386__)))
// with clang/gcc we can achieve the same effect on x86 by invoking int3
asm("int3");
#else
// Dereference nullptr through a volatile pointer to prevent the compiler
// from removing. We use this rather than abort() or __builtin_trap() for
// portability: some debuggers don't correctly trap abort().
*static_cast<volatile int*>(nullptr) = 1;
#endif // GTEST_OS_WINDOWS
} else if (GTEST_FLAG(throw_on_failure)) {
#if GTEST_HAS_EXCEPTIONS
throw internal::GoogleTestFailureException(result);
#else
// We cannot call abort() as it generates a pop-up in debug mode
// that cannot be suppressed in VC 7.1 or below.
exit(1);
#endif
}
}
}
// Adds a TestProperty to the current TestResult object when invoked from
// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
// from SetUpTestSuite or TearDownTestSuite, or to the global property set
// when invoked elsewhere. If the result already contains a property with
// the same key, the value will be updated.
void UnitTest::RecordProperty(const std::string& key,
const std::string& value) {
impl_->RecordProperty(TestProperty(key, value));
}
// Runs all tests in this UnitTest object and prints the result.
// Returns 0 if successful, or 1 otherwise.
//
// We don't protect this under mutex_, as we only support calling it
// from the main thread.
int UnitTest::Run() {
const bool in_death_test_child_process =
internal::GTEST_FLAG(internal_run_death_test).length() > 0;
// Google Test implements this protocol for catching that a test
// program exits before returning control to Google Test:
//
// 1. Upon start, Google Test creates a file whose absolute path
// is specified by the environment variable
// TEST_PREMATURE_EXIT_FILE.
// 2. When Google Test has finished its work, it deletes the file.
//
// This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
// running a Google-Test-based test program and check the existence
// of the file at the end of the test execution to see if it has
// exited prematurely.
// If we are in the child process of a death test, don't
// create/delete the premature exit file, as doing so is unnecessary
// and will confuse the parent process. Otherwise, create/delete
// the file upon entering/leaving this function. If the program
// somehow exits before this function has a chance to return, the
// premature-exit file will be left undeleted, causing a test runner
// that understands the premature-exit-file protocol to report the
// test as having failed.
const internal::ScopedPrematureExitFile premature_exit_file(
in_death_test_child_process
? nullptr
: internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
// used for the duration of the program.
impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
#if GTEST_OS_WINDOWS
// Either the user wants Google Test to catch exceptions thrown by the
// tests or this is executing in the context of death test child
// process. In either case the user does not want to see pop-up dialogs
// about crashes - they are expected.
if (impl()->catch_exceptions() || in_death_test_child_process) {
# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
// SetErrorMode doesn't exist on CE.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
# endif // !GTEST_OS_WINDOWS_MOBILE
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
// Death test children can be terminated with _abort(). On Windows,
// _abort() can show a dialog with a warning message. This forces the
// abort message to go to stderr instead.
_set_error_mode(_OUT_TO_STDERR);
# endif
# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
// In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
// executed. Google Test will notify the user of any unexpected
// failure via stderr.
if (!GTEST_FLAG(break_on_failure))
_set_abort_behavior(
0x0, // Clear the following flags:
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
# endif
}
#endif // GTEST_OS_WINDOWS
return internal::HandleExceptionsInMethodIfSupported(
impl(),
&internal::UnitTestImpl::RunAllTests,
"auxiliary test code (environments or event listeners)") ? 0 : 1;
}
// Returns the working directory when the first TEST() or TEST_F() was
// executed.
const char* UnitTest::original_working_dir() const {
return impl_->original_working_dir_.c_str();
}
// Returns the TestSuite object for the test that's currently running,
// or NULL if no test is running.
const TestSuite* UnitTest::current_test_suite() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
return impl_->current_test_suite();
}
// Legacy API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* UnitTest::current_test_case() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
return impl_->current_test_suite();
}
#endif
// Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running.
const TestInfo* UnitTest::current_test_info() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
return impl_->current_test_info();
}
// Returns the random seed used at the start of the current test run.
int UnitTest::random_seed() const { return impl_->random_seed(); }
// Returns ParameterizedTestSuiteRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
internal::ParameterizedTestSuiteRegistry&
UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
return impl_->parameterized_test_registry();
}
// Creates an empty UnitTest.
UnitTest::UnitTest() {
impl_ = new internal::UnitTestImpl(this);
}
// Destructor of UnitTest.
UnitTest::~UnitTest() {
delete impl_;
}
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack.
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().push_back(trace);
}
// Pops a trace from the per-thread Google Test trace stack.
void UnitTest::PopGTestTrace()
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().pop_back();
}
namespace internal {
UnitTestImpl::UnitTestImpl(UnitTest* parent)
: parent_(parent),
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
default_global_test_part_result_reporter_(this),
default_per_thread_test_part_result_reporter_(this),
GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
&default_global_test_part_result_reporter_),
per_thread_test_part_result_reporter_(
&default_per_thread_test_part_result_reporter_),
parameterized_test_registry_(),
parameterized_tests_registered_(false),
last_death_test_suite_(-1),
current_test_suite_(nullptr),
current_test_info_(nullptr),
ad_hoc_test_result_(),
os_stack_trace_getter_(nullptr),
post_flag_parse_init_performed_(false),
random_seed_(0), // Will be overridden by the flag before first use.
random_(0), // Will be reseeded before first use.
start_timestamp_(0),
elapsed_time_(0),
#if GTEST_HAS_DEATH_TEST
death_test_factory_(new DefaultDeathTestFactory),
#endif
// Will be overridden by the flag before first use.
catch_exceptions_(false) {
listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
}
UnitTestImpl::~UnitTestImpl() {
// Deletes every TestSuite.
ForEach(test_suites_, internal::Delete<TestSuite>);
// Deletes every Environment.
ForEach(environments_, internal::Delete<Environment>);
delete os_stack_trace_getter_;
}
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test, to current test suite's ad_hoc_test_result when invoke
// from SetUpTestSuite/TearDownTestSuite, or to the global property set
// otherwise. If the result already contains a property with the same key,
// the value will be updated.
void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
std::string xml_element;
TestResult* test_result; // TestResult appropriate for property recording.
if (current_test_info_ != nullptr) {
xml_element = "testcase";
test_result = &(current_test_info_->result_);
} else if (current_test_suite_ != nullptr) {
xml_element = "testsuite";
test_result = &(current_test_suite_->ad_hoc_test_result_);
} else {
xml_element = "testsuites";
test_result = &ad_hoc_test_result_;
}
test_result->RecordProperty(xml_element, test_property);
}
#if GTEST_HAS_DEATH_TEST
// Disables event forwarding if the control is currently in a death test
// subprocess. Must not be called before InitGoogleTest.
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
if (internal_run_death_test_flag_.get() != nullptr)
listeners()->SuppressEventForwarding();
}
#endif // GTEST_HAS_DEATH_TEST
// Initializes event listeners performing XML output as specified by
// UnitTestOptions. Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureXmlOutput() {
const std::string& output_format = UnitTestOptions::GetOutputFormat();
if (output_format == "xml") {
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
} else if (output_format == "json") {
listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
} else if (output_format != "") {
GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
<< output_format << "\" ignored.";
}
}
#if GTEST_CAN_STREAM_RESULTS_
// Initializes event listeners for streaming test results in string form.
// Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureStreamingOutput() {
const std::string& target = GTEST_FLAG(stream_result_to);
if (!target.empty()) {
const size_t pos = target.find(':');
if (pos != std::string::npos) {
listeners()->Append(new StreamingListener(target.substr(0, pos),
target.substr(pos+1)));
} else {
GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
<< "\" ignored.";
}
}
}
#endif // GTEST_CAN_STREAM_RESULTS_
// Performs initialization dependent upon flag values obtained in
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
// this function is also called from RunAllTests. Since this function can be
// called more than once, it has to be idempotent.
void UnitTestImpl::PostFlagParsingInit() {
// Ensures that this function does not execute more than once.
if (!post_flag_parse_init_performed_) {
post_flag_parse_init_performed_ = true;
#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
// Register to send notifications about key process state changes.
listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
#if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo();
SuppressTestEventsIfInSubprocess();
#endif // GTEST_HAS_DEATH_TEST
// Registers parameterized tests. This makes parameterized tests
// available to the UnitTest reflection API without running
// RUN_ALL_TESTS.
RegisterParameterizedTests();
// Configures listeners for XML output. This makes it possible for users
// to shut down the default XML output before invoking RUN_ALL_TESTS.
ConfigureXmlOutput();
#if GTEST_CAN_STREAM_RESULTS_
// Configures listeners for streaming test results to the specified server.
ConfigureStreamingOutput();
#endif // GTEST_CAN_STREAM_RESULTS_
#if GTEST_HAS_ABSL
if (GTEST_FLAG(install_failure_signal_handler)) {
absl::FailureSignalHandlerOptions options;
absl::InstallFailureSignalHandler(options);
}
#endif // GTEST_HAS_ABSL
}
}
// A predicate that checks the name of a TestSuite against a known
// value.
//
// This is used for implementation of the UnitTest class only. We put
// it in the anonymous namespace to prevent polluting the outer
// namespace.
//
// TestSuiteNameIs is copyable.
class TestSuiteNameIs {
public:
// Constructor.
explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
// Returns true iff the name of test_suite matches name_.
bool operator()(const TestSuite* test_suite) const {
return test_suite != nullptr &&
strcmp(test_suite->name(), name_.c_str()) == 0;
}
private:
std::string name_;
};
// Finds and returns a TestSuite with the given name. If one doesn't
// exist, creates one and returns it. It's the CALLER'S
// RESPONSIBILITY to ensure that this function is only called WHEN THE
// TESTS ARE NOT SHUFFLED.
//
// Arguments:
//
// test_suite_name: name of the test suite
// type_param: the name of the test suite's type parameter, or NULL if
// this is not a typed or a type-parameterized test suite.
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
TestSuite* UnitTestImpl::GetTestSuite(
const char* test_suite_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc) {
// Can we find a TestSuite with the given name?
const auto test_suite =
std::find_if(test_suites_.rbegin(), test_suites_.rend(),
TestSuiteNameIs(test_suite_name));
if (test_suite != test_suites_.rend()) return *test_suite;
// No. Let's create one.
auto* const new_test_suite =
new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
// Is this a death test suite?
if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
kDeathTestSuiteFilter)) {
// Yes. Inserts the test suite after the last death test suite
// defined so far. This only works when the test suites haven't
// been shuffled. Otherwise we may end up running a death test
// after a non-death test.
++last_death_test_suite_;
test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
new_test_suite);
} else {
// No. Appends to the end of the list.
test_suites_.push_back(new_test_suite);
}
test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
return new_test_suite;
}
// Helpers for setting up / tearing down the given environment. They
// are for use in the ForEach() function.
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
// Runs all tests in this UnitTest object, prints the result, and
// returns true if all tests are successful. If any exception is
// thrown during a test, the test is considered to be failed, but the
// rest of the tests will still be run.
//
// When parameterized tests are enabled, it expands and registers
// parameterized tests first in RegisterParameterizedTests().
// All other functions called from RunAllTests() may safely assume that
// parameterized tests are ready to be counted and run.
bool UnitTestImpl::RunAllTests() {
// True iff Google Test is initialized before RUN_ALL_TESTS() is called.
const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
// Do not run any test if the --help flag was specified.
if (g_help_flag)
return true;
// Repeats the call to the post-flag parsing initialization in case the
// user didn't call InitGoogleTest.
PostFlagParsingInit();
// Even if sharding is not on, test runners may want to use the
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
// protocol.
internal::WriteToShardStatusFileIfNeeded();
// True iff we are in a subprocess for running a thread-safe-style
// death test.
bool in_subprocess_for_death_test = false;
#if GTEST_HAS_DEATH_TEST
in_subprocess_for_death_test =
(internal_run_death_test_flag_.get() != nullptr);
# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
if (in_subprocess_for_death_test) {
GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
}
# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
#endif // GTEST_HAS_DEATH_TEST
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
in_subprocess_for_death_test);
// Compares the full test names with the filter to decide which
// tests to run.
const bool has_tests_to_run = FilterTests(should_shard
? HONOR_SHARDING_PROTOCOL
: IGNORE_SHARDING_PROTOCOL) > 0;
// Lists the tests and exits if the --gtest_list_tests flag was specified.
if (GTEST_FLAG(list_tests)) {
// This must be called *after* FilterTests() has been called.
ListTestsMatchingFilter();
return true;
}
random_seed_ = GTEST_FLAG(shuffle) ?
GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
// True iff at least one test has failed.
bool failed = false;
TestEventListener* repeater = listeners()->repeater();
start_timestamp_ = GetTimeInMillis();
repeater->OnTestProgramStart(*parent_);
// How many times to repeat the tests? We don't want to repeat them
// when we are inside the subprocess of a death test.
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
// Repeats forever if the repeat count is negative.
const bool gtest_repeat_forever = repeat < 0;
for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
// We want to preserve failures generated by ad-hoc test
// assertions executed before RUN_ALL_TESTS().
ClearNonAdHocTestResult();
const TimeInMillis start = GetTimeInMillis();
// Shuffles test suites and tests if requested.
if (has_tests_to_run && GTEST_FLAG(shuffle)) {
random()->Reseed(static_cast<UInt32>(random_seed_));
// This should be done before calling OnTestIterationStart(),
// such that a test event listener can see the actual test order
// in the event.
ShuffleTests();
}
// Tells the unit test event listeners that the tests are about to start.
repeater->OnTestIterationStart(*parent_, i);
// Runs each test suite if there is at least one test to run.
if (has_tests_to_run) {
// Sets up all environments beforehand.
repeater->OnEnvironmentsSetUpStart(*parent_);
ForEach(environments_, SetUpEnvironment);
repeater->OnEnvironmentsSetUpEnd(*parent_);
// Runs the tests only if there was no fatal failure or skip triggered
// during global set-up.
if (Test::IsSkipped()) {
// Emit diagnostics when global set-up calls skip, as it will not be
// emitted by default.
TestResult& test_result =
*internal::GetUnitTestImpl()->current_test_result();
for (int j = 0; j < test_result.total_part_count(); ++j) {
const TestPartResult& test_part_result =
test_result.GetTestPartResult(j);
if (test_part_result.type() == TestPartResult::kSkip) {
const std::string& result = test_part_result.message();
printf("%s\n", result.c_str());
}
}
fflush(stdout);
} else if (!Test::HasFatalFailure()) {
for (int test_index = 0; test_index < total_test_suite_count();
test_index++) {
GetMutableSuiteCase(test_index)->Run();
}
}
// Tears down all environments in reverse order afterwards.
repeater->OnEnvironmentsTearDownStart(*parent_);
std::for_each(environments_.rbegin(), environments_.rend(),
TearDownEnvironment);
repeater->OnEnvironmentsTearDownEnd(*parent_);
}
elapsed_time_ = GetTimeInMillis() - start;
// Tells the unit test event listener that the tests have just finished.
repeater->OnTestIterationEnd(*parent_, i);
// Gets the result and clears it.
if (!Passed()) {
failed = true;
}
// Restores the original test order after the iteration. This
// allows the user to quickly repro a failure that happens in the
// N-th iteration without repeating the first (N - 1) iterations.
// This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
// case the user somehow changes the value of the flag somewhere
// (it's always safe to unshuffle the tests).
UnshuffleTests();
if (GTEST_FLAG(shuffle)) {
// Picks a new random seed for each iteration.
random_seed_ = GetNextRandomSeed(random_seed_);
}
}
repeater->OnTestProgramEnd(*parent_);
if (!gtest_is_initialized_before_run_all_tests) {
ColoredPrintf(
COLOR_RED,
"\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
"This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
" will start to enforce the valid usage. "
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
#if GTEST_FOR_GOOGLE_
ColoredPrintf(COLOR_RED,
"For more details, see http://wiki/Main/ValidGUnitMain.\n");
#endif // GTEST_FOR_GOOGLE_
}
return !failed;
}
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this
// function will write over it. If the variable is present, but the file cannot
// be created, prints an error and exits.
void WriteToShardStatusFileIfNeeded() {
const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
if (test_shard_file != nullptr) {
FILE* const file = posix::FOpen(test_shard_file, "w");
if (file == nullptr) {
ColoredPrintf(COLOR_RED,
"Could not write to the test shard status file \"%s\" "
"specified by the %s environment variable.\n",
test_shard_file, kTestShardStatusFile);
fflush(stdout);
exit(EXIT_FAILURE);
}
fclose(file);
}
}
// Checks whether sharding is enabled by examining the relevant
// environment variable values. If the variables are present,
// but inconsistent (i.e., shard_index >= total_shards), prints
// an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute.
bool ShouldShard(const char* total_shards_env,
const char* shard_index_env,
bool in_subprocess_for_death_test) {
if (in_subprocess_for_death_test) {
return false;
}
const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
if (total_shards == -1 && shard_index == -1) {
return false;
} else if (total_shards == -1 && shard_index != -1) {
const Message msg = Message()
<< "Invalid environment variables: you have "
<< kTestShardIndex << " = " << shard_index
<< ", but have left " << kTestTotalShards << " unset.\n";
ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) {
const Message msg = Message()
<< "Invalid environment variables: you have "
<< kTestTotalShards << " = " << total_shards
<< ", but have left " << kTestShardIndex << " unset.\n";
ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) {
const Message msg = Message()
<< "Invalid environment variables: we require 0 <= "
<< kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
}
return total_shards > 1;
}
// Parses the environment variable var as an Int32. If it is unset,
// returns default_val. If it is not an Int32, prints an error
// and aborts.
Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
const char* str_val = posix::GetEnv(var);
if (str_val == nullptr) {
return default_val;
}
Int32 result;
if (!ParseInt32(Message() << "The value of environment variable " << var,
str_val, &result)) {
exit(EXIT_FAILURE);
}
return result;
}
// Given the total number of shards, the shard index, and the test id,
// returns true iff the test should be run on this shard. The test id is
// some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards.
bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
return (test_id % total_shards) == shard_index;
}
// Compares the name of each test with the user-specified filter to
// decide whether the test should be run, then records the result in
// each TestSuite and TestInfo object.
// If shard_tests == true, further filters tests based on sharding
// variables in the environment - see
// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
// . Returns the number of tests that should run.
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
// num_runnable_tests are the number of tests that will
// run across all shards (i.e., match filter and are not disabled).
// num_selected_tests are the number of tests to be run on
// this shard.
int num_runnable_tests = 0;
int num_selected_tests = 0;
for (auto* test_suite : test_suites_) {
const std::string& test_suite_name = test_suite->name();
test_suite->set_should_run(false);
for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
TestInfo* const test_info = test_suite->test_info_list()[j];
const std::string test_name(test_info->name());
// A test is disabled if test suite name or test name matches
// kDisableTestFilter.
const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
test_suite_name, kDisableTestFilter) ||
internal::UnitTestOptions::MatchesFilter(
test_name, kDisableTestFilter);
test_info->is_disabled_ = is_disabled;
const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
test_suite_name, test_name);
test_info->matches_filter_ = matches_filter;
const bool is_runnable =
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
matches_filter;
const bool is_in_another_shard =
shard_tests != IGNORE_SHARDING_PROTOCOL &&
!ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
test_info->is_in_another_shard_ = is_in_another_shard;
const bool is_selected = is_runnable && !is_in_another_shard;
num_runnable_tests += is_runnable;
num_selected_tests += is_selected;
test_info->should_run_ = is_selected;
test_suite->set_should_run(test_suite->should_run() || is_selected);
}
}
return num_selected_tests;
}
// Prints the given C-string on a single line by replacing all '\n'
// characters with string "\\n". If the output takes more than
// max_length characters, only prints the first max_length characters
// and "...".
static void PrintOnOneLine(const char* str, int max_length) {
if (str != nullptr) {
for (int i = 0; *str != '\0'; ++str) {
if (i >= max_length) {
printf("...");
break;
}
if (*str == '\n') {
printf("\\n");
i += 2;
} else {
printf("%c", *str);
++i;
}
}
}
}
// Prints the names of the tests matching the user-specified filter flag.
void UnitTestImpl::ListTestsMatchingFilter() {
// Print at most this many characters for each type/value parameter.
const int kMaxParamLength = 250;
for (auto* test_suite : test_suites_) {
bool printed_test_suite_name = false;
for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
const TestInfo* const test_info = test_suite->test_info_list()[j];
if (test_info->matches_filter_) {
if (!printed_test_suite_name) {
printed_test_suite_name = true;
printf("%s.", test_suite->name());
if (test_suite->type_param() != nullptr) {
printf(" # %s = ", kTypeParamLabel);
// We print the type parameter on a single line to make
// the output easy to parse by a program.
PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
}
printf("\n");
}
printf(" %s", test_info->name());
if (test_info->value_param() != nullptr) {
printf(" # %s = ", kValueParamLabel);
// We print the value parameter on a single line to make the
// output easy to parse by a program.
PrintOnOneLine(test_info->value_param(), kMaxParamLength);
}
printf("\n");
}
}
}
fflush(stdout);
const std::string& output_format = UnitTestOptions::GetOutputFormat();
if (output_format == "xml" || output_format == "json") {
FILE* fileout = OpenFileForWriting(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
std::stringstream stream;
if (output_format == "xml") {
XmlUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
.PrintXmlTestsList(&stream, test_suites_);
} else if (output_format == "json") {
JsonUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
.PrintJsonTestList(&stream, test_suites_);
}
fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
fclose(fileout);
}
}
// Sets the OS stack trace getter.
//
// Does nothing if the input and the current OS stack trace getter are
// the same; otherwise, deletes the old getter and makes the input the
// current getter.
void UnitTestImpl::set_os_stack_trace_getter(
OsStackTraceGetterInterface* getter) {
if (os_stack_trace_getter_ != getter) {
delete os_stack_trace_getter_;
os_stack_trace_getter_ = getter;
}
}
// Returns the current OS stack trace getter if it is not NULL;
// otherwise, creates an OsStackTraceGetter, makes it the current
// getter, and returns it.
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
if (os_stack_trace_getter_ == nullptr) {
#ifdef GTEST_OS_STACK_TRACE_GETTER_
os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
#else
os_stack_trace_getter_ = new OsStackTraceGetter;
#endif // GTEST_OS_STACK_TRACE_GETTER_
}
return os_stack_trace_getter_;
}
// Returns the most specific TestResult currently running.
TestResult* UnitTestImpl::current_test_result() {
if (current_test_info_ != nullptr) {
return ¤t_test_info_->result_;
}
if (current_test_suite_ != nullptr) {
return ¤t_test_suite_->ad_hoc_test_result_;
}
return &ad_hoc_test_result_;
}
// Shuffles all test suites, and the tests within each test suite,
// making sure that death tests are still run first.
void UnitTestImpl::ShuffleTests() {
// Shuffles the death test suites.
ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
// Shuffles the non-death test suites.
ShuffleRange(random(), last_death_test_suite_ + 1,
static_cast<int>(test_suites_.size()), &test_suite_indices_);
// Shuffles the tests inside each test suite.
for (auto& test_suite : test_suites_) {
test_suite->ShuffleTests(random());
}
}
// Restores the test suites and tests to their order before the first shuffle.
void UnitTestImpl::UnshuffleTests() {
for (size_t i = 0; i < test_suites_.size(); i++) {
// Unshuffles the tests in each test suite.
test_suites_[i]->UnshuffleTests();
// Resets the index of each test suite.
test_suite_indices_[i] = static_cast<int>(i);
}
}
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter
// specifies the number of top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
int skip_count) {
// We pass skip_count + 1 to skip this wrapper function in addition
// to what the user really wants to skip.
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
}
// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
// suppress unreachable code warnings.
namespace {
class ClassUniqueToAlwaysTrue {};
}
bool IsTrue(bool condition) { return condition; }
bool AlwaysTrue() {
#if GTEST_HAS_EXCEPTIONS
// This condition is always false so AlwaysTrue() never actually throws,
// but it makes the compiler think that it may throw.
if (IsTrue(false))
throw ClassUniqueToAlwaysTrue();
#endif // GTEST_HAS_EXCEPTIONS
return true;
}
// If *pstr starts with the given prefix, modifies *pstr to be right
// past the prefix and returns true; otherwise leaves *pstr unchanged
// and returns false. None of pstr, *pstr, and prefix can be NULL.
bool SkipPrefix(const char* prefix, const char** pstr) {
const size_t prefix_len = strlen(prefix);
if (strncmp(*pstr, prefix, prefix_len) == 0) {
*pstr += prefix_len;
return true;
}
return false;
}
// Parses a string as a command line flag. The string should have
// the format "--flag=value". When def_optional is true, the "=value"
// part can be omitted.
//
// Returns the value of the flag, or NULL if the parsing failed.
static const char* ParseFlagValue(const char* str, const char* flag,
bool def_optional) {
// str and flag must not be NULL.
if (str == nullptr || flag == nullptr) return nullptr;
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
const size_t flag_len = flag_str.length();
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
// Skips the flag name.
const char* flag_end = str + flag_len;
// When def_optional is true, it's OK to not have a "=value" part.
if (def_optional && (flag_end[0] == '\0')) {
return flag_end;
}
// If def_optional is true and there are more characters after the
// flag name, or if def_optional is false, there must be a '=' after
// the flag name.
if (flag_end[0] != '=') return nullptr;
// Returns the string after "=".
return flag_end + 1;
}
// Parses a string for a bool flag, in the form of either
// "--flag=value" or "--flag".
//
// In the former case, the value is taken as true as long as it does
// not start with '0', 'f', or 'F'.
//
// In the latter case, the value is taken as true.
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, true);
// Aborts if the parsing failed.
if (value_str == nullptr) return false;
// Converts the string value to a bool.
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
return true;
}
// Parses a string for an Int32 flag, in the form of
// "--flag=value".
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, false);
// Aborts if the parsing failed.
if (value_str == nullptr) return false;
// Sets *value to the value of the flag.
return ParseInt32(Message() << "The value of flag --" << flag,
value_str, value);
}
// Parses a string for a string flag, in the form of
// "--flag=value".
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
template <typename String>
static bool ParseStringFlag(const char* str, const char* flag, String* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, false);
// Aborts if the parsing failed.
if (value_str == nullptr) return false;
// Sets *value to the value of the flag.
*value = value_str;
return true;
}
// Determines whether a string has a prefix that Google Test uses for its
// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
// If Google Test detects that a command line flag has its prefix but is not
// recognized, it will print its help message. Flags starting with
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
// internal flags and do not trigger the help message.
static bool HasGoogleTestFlagPrefix(const char* str) {
return (SkipPrefix("--", &str) ||
SkipPrefix("-", &str) ||
SkipPrefix("/", &str)) &&
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
}
// Prints a string containing code-encoded text. The following escape
// sequences can be used in the string to control the text color:
//
// @@ prints a single '@' character.
// @R changes the color to red.
// @G changes the color to green.
// @Y changes the color to yellow.
// @D changes to the default terminal text color.
//
static void PrintColorEncoded(const char* str) {
GTestColor color = COLOR_DEFAULT; // The current color.
// Conceptually, we split the string into segments divided by escape
// sequences. Then we print one segment at a time. At the end of
// each iteration, the str pointer advances to the beginning of the
// next segment.
for (;;) {
const char* p = strchr(str, '@');
if (p == nullptr) {
ColoredPrintf(color, "%s", str);
return;
}
ColoredPrintf(color, "%s", std::string(str, p).c_str());
const char ch = p[1];
str = p + 2;
if (ch == '@') {
ColoredPrintf(color, "@");
} else if (ch == 'D') {
color = COLOR_DEFAULT;
} else if (ch == 'R') {
color = COLOR_RED;
} else if (ch == 'G') {
color = COLOR_GREEN;
} else if (ch == 'Y') {
color = COLOR_YELLOW;
} else {
--str;
}
}
}
static const char kColorEncodedHelpMessage[] =
"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
"following command line flags to control its behavior:\n"
"\n"
"Test Selection:\n"
" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
" List the names of all tests instead of running them. The name of\n"
" TEST(Foo, Bar) is \"Foo.Bar\".\n"
" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
"[@G-@YNEGATIVE_PATTERNS]@D\n"
" Run only the tests whose name matches one of the positive patterns but\n"
" none of the negative patterns. '?' matches any single character; '*'\n"
" matches any substring; ':' separates two patterns.\n"
" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
" Run all disabled tests too.\n"
"\n"
"Test Execution:\n"
" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
" Run the tests repeatedly; use a negative count to repeat forever.\n"
" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
" Randomize tests' orders on every iteration.\n"
" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
" Random number seed to use for shuffling test orders (between 1 and\n"
" 99999, or 0 to use a seed based on the current time).\n"
"\n"
"Test Output:\n"
" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
" Enable/disable colored output. The default is @Gauto@D.\n"
" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
" Don't print the elapsed time of each test.\n"
" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
" Generate a JSON or XML report in the given directory or with the given\n"
" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
# if GTEST_CAN_STREAM_RESULTS_
" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
" Stream test results to the given server.\n"
# endif // GTEST_CAN_STREAM_RESULTS_
"\n"
"Assertion Behavior:\n"
# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
" Set the default death test style.\n"
# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
" Turn assertion failures into debugger break-points.\n"
" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
" Turn assertion failures into C++ exceptions for use by an external\n"
" test framework.\n"
" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
" Do not report exceptions as test failures. Instead, allow them\n"
" to crash the program or throw a pop-up (on Windows).\n"
"\n"
"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
"the corresponding\n"
"environment variable of a flag (all letters in upper-case). For example, to\n"
"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
"color=no@D or set\n"
"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
"\n"
"For more information, please read the " GTEST_NAME_ " documentation at\n"
"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
"(not one in your own code or tests), please report it to\n"
"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
static bool ParseGoogleTestFlag(const char* const arg) {
return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
>EST_FLAG(also_run_disabled_tests)) ||
ParseBoolFlag(arg, kBreakOnFailureFlag,
>EST_FLAG(break_on_failure)) ||
ParseBoolFlag(arg, kCatchExceptionsFlag,
>EST_FLAG(catch_exceptions)) ||
ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
ParseStringFlag(arg, kDeathTestStyleFlag,
>EST_FLAG(death_test_style)) ||
ParseBoolFlag(arg, kDeathTestUseFork,
>EST_FLAG(death_test_use_fork)) ||
ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
ParseStringFlag(arg, kInternalRunDeathTestFlag,
>EST_FLAG(internal_run_death_test)) ||
ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) ||
ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
ParseInt32Flag(arg, kStackTraceDepthFlag,
>EST_FLAG(stack_trace_depth)) ||
ParseStringFlag(arg, kStreamResultToFlag,
>EST_FLAG(stream_result_to)) ||
ParseBoolFlag(arg, kThrowOnFailureFlag,
>EST_FLAG(throw_on_failure));
}
#if GTEST_USE_OWN_FLAGFILE_FLAG_
static void LoadFlagsFromFile(const std::string& path) {
FILE* flagfile = posix::FOpen(path.c_str(), "r");
if (!flagfile) {
GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
<< "\"";
}
std::string contents(ReadEntireFile(flagfile));
posix::FClose(flagfile);
std::vector<std::string> lines;
SplitString(contents, '\n', &lines);
for (size_t i = 0; i < lines.size(); ++i) {
if (lines[i].empty())
continue;
if (!ParseGoogleTestFlag(lines[i].c_str()))
g_help_flag = true;
}
}
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test. The type parameter CharType can be
// instantiated to either char or wchar_t.
template <typename CharType>
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
for (int i = 1; i < *argc; i++) {
const std::string arg_string = StreamableToString(argv[i]);
const char* const arg = arg_string.c_str();
using internal::ParseBoolFlag;
using internal::ParseInt32Flag;
using internal::ParseStringFlag;
bool remove_flag = false;
if (ParseGoogleTestFlag(arg)) {
remove_flag = true;
#if GTEST_USE_OWN_FLAGFILE_FLAG_
} else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) {
LoadFlagsFromFile(GTEST_FLAG(flagfile));
remove_flag = true;
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
} else if (arg_string == "--help" || arg_string == "-h" ||
arg_string == "-?" || arg_string == "/?" ||
HasGoogleTestFlagPrefix(arg)) {
// Both help flag and unrecognized Google Test flags (excluding
// internal ones) trigger help display.
g_help_flag = true;
}
if (remove_flag) {
// Shift the remainder of the argv list left by one. Note
// that argv has (*argc + 1) elements, the last one always being
// NULL. The following loop moves the trailing NULL element as
// well.
for (int j = i; j != *argc; j++) {
argv[j] = argv[j + 1];
}
// Decrements the argument count.
(*argc)--;
// We also need to decrement the iterator as we just removed
// an element.
i--;
}
}
if (g_help_flag) {
// We print the help here instead of in RUN_ALL_TESTS(), as the
// latter may not be called at all if the user is using Google
// Test with another testing framework.
PrintColorEncoded(kColorEncodedHelpMessage);
}
}
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test.
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
ParseGoogleTestFlagsOnlyImpl(argc, argv);
// Fix the value of *_NSGetArgc() on macOS, but iff
// *_NSGetArgv() == argv
// Only applicable to char** version of argv
#if GTEST_OS_MAC
#ifndef GTEST_OS_IOS
if (*_NSGetArgv() == argv) {
*_NSGetArgc() = *argc;
}
#endif
#endif
}
void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
ParseGoogleTestFlagsOnlyImpl(argc, argv);
}
// The internal implementation of InitGoogleTest().
//
// The type parameter CharType can be instantiated to either char or
// wchar_t.
template <typename CharType>
void InitGoogleTestImpl(int* argc, CharType** argv) {
// We don't want to run the initialization code twice.
if (GTestIsInitialized()) return;
if (*argc <= 0) return;
g_argvs.clear();
for (int i = 0; i != *argc; i++) {
g_argvs.push_back(StreamableToString(argv[i]));
}
#if GTEST_HAS_ABSL
absl::InitializeSymbolizer(g_argvs[0].c_str());
#endif // GTEST_HAS_ABSL
ParseGoogleTestFlagsOnly(argc, argv);
GetUnitTestImpl()->PostFlagParsingInit();
}
} // namespace internal
// Initializes Google Test. This must be called before calling
// RUN_ALL_TESTS(). In particular, it parses a command line for the
// flags that Google Test recognizes. Whenever a Google Test flag is
// seen, it is removed from argv, and *argc is decremented.
//
// No value is returned. Instead, the Google Test flag variables are
// updated.
//
// Calling the function for the second time has no user-visible effect.
void InitGoogleTest(int* argc, char** argv) {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
}
// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
void InitGoogleTest(int* argc, wchar_t** argv) {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
}
// This overloaded version can be used on Arduino/embedded platforms where
// there is no argc/argv.
void InitGoogleTest() {
// Since Arduino doesn't have a command line, fake out the argc/argv arguments
int argc = 1;
const auto arg0 = "dummy";
char* argv0 = const_cast<char*>(arg0);
char** argv = &argv0;
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(&argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
}
std::string TempDir() {
#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
#endif
#if GTEST_OS_WINDOWS_MOBILE
return "\\temp\\";
#elif GTEST_OS_WINDOWS
const char* temp_dir = internal::posix::GetEnv("TEMP");
if (temp_dir == nullptr || temp_dir[0] == '\0')
return "\\temp\\";
else if (temp_dir[strlen(temp_dir) - 1] == '\\')
return temp_dir;
else
return std::string(temp_dir) + "\\";
#elif GTEST_OS_LINUX_ANDROID
return "/sdcard/";
#else
return "/tmp/";
#endif // GTEST_OS_WINDOWS_MOBILE
}
// Class ScopedTrace
// Pushes the given source file location and message onto a per-thread
// trace stack maintained by Google Test.
void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
internal::TraceInfo trace;
trace.file = file;
trace.line = line;
trace.message.swap(message);
UnitTest::GetInstance()->PushGTestTrace(trace);
}
// Pops the info pushed by the c'tor.
ScopedTrace::~ScopedTrace()
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace();
}
} // namespace testing
|
#include "basic.hpp"
#include <string>
#include <iostream>
using namespace std;
static inline void printTestSeparator(const string& title = "", bool isfirstTest = false) {
printf("%s------ %s ------\n", !isfirstTest ? "\n\n" : "", title.c_str());
}
void runAllTests() {
printTestSeparator("ROLL 1 <Die>", true);
testDieRoll();
printTestSeparator("COPY & ASIGN <Die>");
testCopyAssignDie();
printTestSeparator("ROLL 1 <Roll> FEW TIMES");
testRollObj();
printTestSeparator("TEST ERRORS");
testRollObjCtorError();
puts("\n\nDone.\nAll tests succeeded!");
}
|
/******************************************************************************
*
* Project: TIGER/Line Translator
* Purpose: Implements TigerPoint class.
* Author: Mark Phillips, mbp@geomtech.com
*
******************************************************************************
* Copyright (c) 2002, Mark Phillips
*
* 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 "ogr_tiger.h"
#include "cpl_conv.h"
CPL_CVSID("$Id$");
/************************************************************************/
/* TigerPoint() */
/************************************************************************/
TigerPoint::TigerPoint( int bRequireGeomIn, const TigerRecordInfo *psRTInfoIn,
const char *m_pszFileCodeIn ) :
TigerFileBase(psRTInfoIn, m_pszFileCodeIn),
bRequireGeom(bRequireGeomIn)
{}
/************************************************************************/
/* GetFeature() */
/************************************************************************/
OGRFeature *TigerPoint::GetFeature( int nRecordId,
int nX0, int nX1,
int nY0, int nY1 )
{
char achRecord[OGR_TIGER_RECBUF_LEN];
if( nRecordId < 0 || nRecordId >= nFeatures ) {
CPLError( CE_Failure, CPLE_FileIO,
"Request for out-of-range feature %d of %sP",
nRecordId, pszModule );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Read the raw record data from the file. */
/* -------------------------------------------------------------------- */
if( fpPrimary == NULL )
return NULL;
if( VSIFSeekL( fpPrimary, nRecordId * nRecordLength, SEEK_SET ) != 0 ) {
CPLError( CE_Failure, CPLE_FileIO,
"Failed to seek to %d of %sP",
nRecordId * nRecordLength, pszModule );
return NULL;
}
// Overflow cannot happen since psRTInfo->nRecordLength is unsigned
// char and sizeof(achRecord) == OGR_TIGER_RECBUF_LEN > 255
if( VSIFReadL( achRecord, psRTInfo->nRecordLength, 1, fpPrimary ) != 1 ) {
CPLError( CE_Failure, CPLE_FileIO,
"Failed to read record %d of %sP",
nRecordId, pszModule );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Set fields. */
/* -------------------------------------------------------------------- */
OGRFeature *poFeature = new OGRFeature( poFeatureDefn );
SetFields( psRTInfo, poFeature, achRecord);
/* -------------------------------------------------------------------- */
/* Set geometry */
/* -------------------------------------------------------------------- */
const double dfX = atoi(GetField(achRecord, nX0, nX1)) / 1000000.0;
const double dfY = atoi(GetField(achRecord, nY0, nY1)) / 1000000.0;
if( dfX != 0.0 || dfY != 0.0 ) {
poFeature->SetGeometryDirectly( new OGRPoint( dfX, dfY ) );
}
return poFeature;
}
/************************************************************************/
/* CreateFeature() */
/************************************************************************/
OGRErr TigerPoint::CreateFeature( OGRFeature *poFeature,
int pointIndex)
{
char szRecord[OGR_TIGER_RECBUF_LEN];
OGRPoint *poPoint = (OGRPoint *) poFeature->GetGeometryRef();
if( !SetWriteModule( m_pszFileCode, psRTInfo->nRecordLength+2, poFeature ) )
return OGRERR_FAILURE;
memset( szRecord, ' ', psRTInfo->nRecordLength );
WriteFields( psRTInfo, poFeature, szRecord );
if( poPoint != NULL
&& (poPoint->getGeometryType() == wkbPoint
|| poPoint->getGeometryType() == wkbPoint25D) ) {
WritePoint( szRecord, pointIndex, poPoint->getX(), poPoint->getY() );
} else {
if (bRequireGeom) {
return OGRERR_FAILURE;
}
}
WriteRecord( szRecord, psRTInfo->nRecordLength, m_pszFileCode );
return OGRERR_NONE;
}
|
#include "PluginProcessor.h"
#include "PluginEditor.h"
#include "util/util.h"
const double SpeedOfSound = 340.0; // m/s at 15C, normal pressure
const auto bgColor = Colour{48, 48, 48}, textColor = Colour{200, 200, 200};
inline double msToCm(double ms)
{
static const double cmPerMs = SpeedOfSound * 100.0 /* cm in 1 m */ / 1000.0 /* ms in 1 s*/;
return ms * cmPerMs;
}
inline double cmToMs(double cm)
{
static const double msPerOneCm = 1.0 / msToCm(1.0);
return cm * msPerOneCm;
}
DelayEditor::DelayEditor(AudioProcessorWithDelays& processor, int channelId) : _processor(processor), _channelId(channelId)
{
_onOffSwitch.setButtonText("On");
_onOffSwitch.addListener(this);
_onOffSwitch.setToggleState(_processor.isEnabled(channelId), juce::sendNotificationSync);
_onOffSwitch.setColour(ToggleButton::textColourId, textColor);
_onOffSwitch.setColour(ToggleButton::tickColourId, Colour(239, 51, 64));
addAndMakeVisible(_onOffSwitch);
_delaySlider.setSliderStyle(Slider::LinearBar);
_delaySlider.setRange(0.0, 200, 0.1);
_delaySlider.setTextBoxStyle(Slider::NoTextBox, false, 90, 0);
_delaySlider.setPopupDisplayEnabled(true, this);
_delaySlider.setTextValueSuffix(" cm");
_delaySlider.setValue(msToCm(_processor.delay(channelId)));
_delaySlider.addListener(this);
addAndMakeVisible(_delaySlider);
_editor.setMultiLine(false);
_editor.addListener(this);
_editor.setText(String(_delaySlider.getValue()));
_editor.setColour(TextEditor::backgroundColourId, bgColor);
_editor.setColour(TextEditor::textColourId, textColor);
_editor.setColour(TextEditor::highlightColourId, _editor.findColour(TextEditor::focusedOutlineColourId));
_editor.setColour(TextEditor::highlightColourId, _editor.findColour(TextEditor::focusedOutlineColourId));
_editor.setColour(TextEditor::highlightedTextColourId, Colour(255, 255, 255));
addAndMakeVisible(_editor);
}
void DelayEditor::sliderValueChanged(Slider* slider)
{
const double currentDelayMs = _processor.delay(_channelId);
const double newDelayMs = cmToMs(_delaySlider.getValue());
if (slider == &_delaySlider && fabs(newDelayMs - currentDelayMs) >= cmToMs(0.1))
{
_editor.setText(String(_delaySlider.getValue()));
_processor.setDelay(newDelayMs, _channelId);
}
}
void DelayEditor::textEditorReturnKeyPressed(TextEditor & editor)
{
_delaySlider.setValue(editor.getText().getDoubleValue());
}
void DelayEditor::buttonClicked(Button* button)
{
const bool enabled = button->getToggleState();
if (enabled != _processor.isEnabled(_channelId))
_processor.setEnabled(enabled, _channelId);
}
void DelayEditor::resized()
{
auto lBounds = getLocalBounds();
lBounds.removeFromLeft(10);
lBounds.removeFromTop(20);
_onOffSwitch.setBounds(Rectangle<int>(lBounds.getX(), lBounds.getY(), 50, 20));
lBounds.removeFromLeft(50);
const int textEditWidth = 50;
_delaySlider.setBounds(Rectangle<int>(lBounds.getX(), lBounds.getY(), lBounds.getWidth() - 10 - textEditWidth, 20));
lBounds.removeFromLeft(lBounds.getWidth() - 10 - textEditWidth);
_editor.setBounds(Rectangle<int>(lBounds.getX(), lBounds.getY(), lBounds.getWidth(), 20));
}
//==============================================================================
AudioProcessorAudioProcessorEditor::AudioProcessorAudioProcessorEditor(AudioProcessorWithDelays& p)
: AudioProcessorEditor(&p), processor(p)
{
// Make sure that before the constructor has finished, you've set the
// editor's size to whatever you need it to be.
setSize(400, 200);
for (int i = 0; i < processor.getTotalNumOutputChannels(); ++i)
createEditor(i);
}
AudioProcessorAudioProcessorEditor::~AudioProcessorAudioProcessorEditor()
{
}
void AudioProcessorAudioProcessorEditor::createEditor(const int channelId)
{
_editors.emplace_back(processor, channelId);
addAndMakeVisible(_editors.back());
resized();
}
//==============================================================================
void AudioProcessorAudioProcessorEditor::paint(Graphics& g)
{
g.fillAll(bgColor);
}
void AudioProcessorAudioProcessorEditor::resized()
{
auto lBounds = getLocalBounds();
for (size_t i = 0; i < _editors.size(); ++i)
{
if (i > 0)
lBounds.removeFromTop(20 + 2*20);
_editors[i].setBounds(lBounds);
_editors[i].resized();
}
}
|
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BOOST_BEAST_BUFFER_TRAITS_HPP
#define BOOST_BEAST_BUFFER_TRAITS_HPP
#include <boost/asio/buffer.hpp>
#include <boost/beast/core/detail/buffer_traits.hpp>
#include <boost/beast/core/detail/config.hpp>
#include <boost/beast/core/detail/static_const.hpp>
#include <boost/config/workaround.hpp>
#include <boost/mp11/function.hpp>
#include <type_traits>
namespace boost {
namespace beast {
/** Determine if a list of types satisfy the <em>ConstBufferSequence</em>
requirements.
This metafunction is used to determine if all of the specified types
meet the requirements for constant buffer sequences. This type alias
will be `std::true_type` if each specified type meets the requirements,
otherwise, this type alias will be `std::false_type`.
@tparam BufferSequence A list of zero or more types to check. If this
list is empty, the resulting type alias will be `std::true_type`.
*/
template <class... BufferSequence>
#if BOOST_BEAST_DOXYGEN
using is_const_buffer_sequence = __see_below__;
#else
using is_const_buffer_sequence = mp11::mp_all<net::is_const_buffer_sequence<
typename std::decay<BufferSequence>::type>...>;
#endif
/** Determine if a list of types satisfy the <em>MutableBufferSequence</em>
requirements.
This metafunction is used to determine if all of the specified types
meet the requirements for mutable buffer sequences. This type alias
will be `std::true_type` if each specified type meets the requirements,
otherwise, this type alias will be `std::false_type`.
@tparam BufferSequence A list of zero or more types to check. If this
list is empty, the resulting type alias will be `std::true_type`.
*/
template <class... BufferSequence>
#if BOOST_BEAST_DOXYGEN
using is_mutable_buffer_sequence = __see_below__;
#else
using is_mutable_buffer_sequence = mp11::mp_all<net::is_mutable_buffer_sequence<
typename std::decay<BufferSequence>::type>...>;
#endif
/** Type alias for the underlying buffer type of a list of buffer sequence
types.
This metafunction is used to determine the underlying buffer type for
a list of buffer sequence. The equivalent type of the alias will vary
depending on the template type argument:
@li If every type in the list is a <em>MutableBufferSequence</em>,
the resulting type alias will be `net::mutable_buffer`, otherwise
@li The resulting type alias will be `net::const_buffer`.
@par Example
The following code returns the first buffer in a buffer sequence,
or generates a compilation error if the argument is not a buffer
sequence:
@code
template <class BufferSequence>
buffers_type <BufferSequence>
buffers_front (BufferSequence const& buffers)
{
static_assert(
net::is_const_buffer_sequence<BufferSequence>::value,
"BufferSequence type requirements not met");
auto const first = net::buffer_sequence_begin (buffers);
if (first == net::buffer_sequence_end (buffers))
return {};
return *first;
}
@endcode
@tparam BufferSequence A list of zero or more types to check. If this
list is empty, the resulting type alias will be `net::mutable_buffer`.
*/
template <class... BufferSequence>
#if BOOST_BEAST_DOXYGEN
using buffers_type = __see_below__;
#else
using buffers_type = typename std::conditional<
is_mutable_buffer_sequence<BufferSequence...>::value, net::mutable_buffer,
net::const_buffer>::type;
#endif
/** Type alias for the iterator type of a buffer sequence type.
This metafunction is used to determine the type of iterator
used by a particular buffer sequence.
@tparam T The buffer sequence type to use. The resulting
type alias will be equal to the iterator type used by
the buffer sequence.
*/
template <class BufferSequence>
#if BOOST_BEAST_DOXYGEN
using buffers_iterator_type = __see_below__;
#elif BOOST_WORKAROUND(BOOST_MSVC, < 1910)
using buffers_iterator_type = typename detail::buffers_iterator_type_helper<
typename std::decay<BufferSequence>::type>::type;
#else
using buffers_iterator_type = decltype(
net::buffer_sequence_begin(std::declval<BufferSequence const &>()));
#endif
/** Return the total number of bytes in a buffer or buffer sequence
This function returns the total number of bytes in a buffer,
buffer sequence, or object convertible to a buffer. Specifically
it may be passed:
@li A <em>ConstBufferSequence</em> or <em>MutableBufferSequence</em>
@li A `net::const_buffer` or `net::mutable_buffer`
@li An object convertible to `net::const_buffer`
This function is designed as an easier-to-use replacement for
`net::buffer_size`. It recognizes customization points found through
argument-dependent lookup. The call `beast::buffer_bytes(b)` is
equivalent to performing:
@code
using namespace net;
buffer_bytes(b);
@endcode
In addition this handles types which are convertible to
`net::const_buffer`; these are not handled by `net::buffer_size`.
@param buffers The buffer or buffer sequence to calculate the size of.
@return The total number of bytes in the buffer or sequence.
*/
#if BOOST_BEAST_DOXYGEN
template <class BufferSequence>
std::size_t buffer_bytes(BufferSequence const &buffers);
#else
BOOST_BEAST_INLINE_VARIABLE(buffer_bytes, detail::buffer_bytes_impl)
#endif
} // namespace beast
} // namespace boost
#endif
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_connect_socket_open_34.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-34.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Full path and file name
* Sinks: open
* BadSink : Open the file named in data using open()
* Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function)
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#ifdef _WIN32
#define OPEN _open
#define CLOSE _close
#else
#define OPEN open
#define CLOSE close
#endif
namespace CWE36_Absolute_Path_Traversal__char_connect_socket_open_34
{
typedef union
{
char * unionFirst;
char * unionSecond;
} unionType;
#ifndef OMITBAD
void bad()
{
char * data;
unionType myUnion;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
myUnion.unionFirst = data;
{
char * data = myUnion.unionSecond;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
unionType myUnion;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
myUnion.unionFirst = data;
{
char * data = myUnion.unionSecond;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__char_connect_socket_open_34; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Levitate address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
|
/****************************************************************************
** Meta object code from reading C++ file 'charitydialog.h'
**
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "qt/charitydialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'charitydialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_StakeForCharityDialog_t {
QByteArrayData data[8];
char stringdata0[170];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_StakeForCharityDialog_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_StakeForCharityDialog_t qt_meta_stringdata_StakeForCharityDialog = {
{
QT_MOC_LITERAL(0, 0, 21), // "StakeForCharityDialog"
QT_MOC_LITERAL(1, 22, 21), // "on_viewButton_clicked"
QT_MOC_LITERAL(2, 44, 0), // ""
QT_MOC_LITERAL(3, 45, 20), // "on_addButton_clicked"
QT_MOC_LITERAL(4, 66, 23), // "on_deleteButton_clicked"
QT_MOC_LITERAL(5, 90, 25), // "on_activateButton_clicked"
QT_MOC_LITERAL(6, 116, 24), // "on_disableButton_clicked"
QT_MOC_LITERAL(7, 141, 28) // "on_addressBookButton_clicked"
},
"StakeForCharityDialog\0on_viewButton_clicked\0"
"\0on_addButton_clicked\0on_deleteButton_clicked\0"
"on_activateButton_clicked\0"
"on_disableButton_clicked\0"
"on_addressBookButton_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_StakeForCharityDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 44, 2, 0x08 /* Private */,
3, 0, 45, 2, 0x08 /* Private */,
4, 0, 46, 2, 0x08 /* Private */,
5, 0, 47, 2, 0x08 /* Private */,
6, 0, 48, 2, 0x08 /* Private */,
7, 0, 49, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void StakeForCharityDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
StakeForCharityDialog *_t = static_cast<StakeForCharityDialog *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_viewButton_clicked(); break;
case 1: _t->on_addButton_clicked(); break;
case 2: _t->on_deleteButton_clicked(); break;
case 3: _t->on_activateButton_clicked(); break;
case 4: _t->on_disableButton_clicked(); break;
case 5: _t->on_addressBookButton_clicked(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject StakeForCharityDialog::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_StakeForCharityDialog.data,
qt_meta_data_StakeForCharityDialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *StakeForCharityDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *StakeForCharityDialog::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_StakeForCharityDialog.stringdata0))
return static_cast<void*>(const_cast< StakeForCharityDialog*>(this));
return QWidget::qt_metacast(_clname);
}
int StakeForCharityDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 6;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
#include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 1e18+10;
const long long mod = 1e9+7;
const long long hashmod = 100003;
const int MAXN = 100000;
const int MAXM = 1000000;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
int n,L,k;
int a[100005];
bool isok(int x) {
int la = 0,cnt = 0;
for(int i = 1;i <= n;i++) {
if(a[i]-la >= x) {
cnt++;
la = a[i];
}
}
return cnt > k;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> L >> k;
for(int i = 1;i <= n;i++) {
cin >> a[i];
}
a[++n] = L;
int l = 1, r = INF;
while(l < r) {
int mid = (l + r + 1) >> 1;
if(isok(mid)) l = mid;
else r = mid-1;
}
cout << l;
}
|
#include "pseudo_barrier.h"
#include "thread.h"
#include <chrono>
#include <cinttypes>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <unistd.h>
#include <vector>
pseudo_barrier_t barrier;
static void sigusr1_handler(int signo) {
char buf[100];
std::snprintf(buf, sizeof(buf),
"received SIGUSR1 on thread id: %" PRIx64 "\n",
get_thread_id());
write(STDOUT_FILENO, buf, strlen(buf));
}
static void thread_func() {
pseudo_barrier_wait(barrier);
std::this_thread::sleep_for(std::chrono::minutes(1));
}
int main(int argc, char **argv) {
int num = atoi(argv[1]);
pseudo_barrier_init(barrier, num + 1);
signal(SIGUSR1, sigusr1_handler);
std::vector<std::thread> threads;
for(int i = 0; i < num; ++i)
threads.emplace_back(thread_func);
pseudo_barrier_wait(barrier);
std::puts("@started");
for (std::thread &thread : threads)
thread.join();
return 0;
}
|
//*********************************************************
// Factor_Service.cpp - modify the number of runs
//*********************************************************
#include "Reschedule.hpp"
//---------------------------------------------------------
// Factor_Service
//---------------------------------------------------------
void Reschedule::Factor_Service (void)
{
int stop, stops, run, runs, route, tod, count;
int num_in, num_out, shift, period, num_period;
int duration [25], start [25], time0 [25], increment [25], num_runs [25], num_new [25], num [25];
bool skip, flag, change;
Line_Data *line_ptr;
Range_Data *range_ptr;
Schedule_File *new_schedule = (Schedule_File *) Network_Db_File (NEW_TRANSIT_SCHEDULE);
Show_Message ("Writing %s -- Route", new_schedule->File_Type ());
Set_Progress (100);
count = num_in = num_out = 0;
num_period = select_periods.Num_Ranges () + 1;
if (period_flag) {
for (range_ptr = select_periods.First (); range_ptr; range_ptr = select_periods.Next ()) {
period = select_periods.Record_Index ();
time0 [period] = range_ptr->Low ();
duration [period] = range_ptr->High () - range_ptr->Low () + 1;
}
} else {
duration [1] = MIDNIGHT;
time0 [1] = 0;
}
//---- read each route ----
for (line_ptr = line_data.First_Key (); line_ptr; line_ptr = line_data.Next_Key ()) {
Show_Progress ();
route = line_ptr->Route ();
new_schedule->Route (route);
stops = line_ptr->Stops ();
runs = line_ptr->Runs ();
//---- check the selection criteria ----
change = false;
flag = ((!route_flag || select_routes.In_Range (route)) &&
select_modes [line_ptr->Mode ()]);
memset (num_runs, '\0', sizeof (num_runs));
memset (num_new, '\0', sizeof (num_new));
memset (num, '\0', sizeof (num));
memcpy (start, time0, sizeof (start));
//---- count the runs in the period ----
if (flag) {
for (run=1; run <= runs; run++) {
if (method == RUN_START) {
tod = Resolve (line_ptr->Schedule (run, 1));
} else if (method == RUN_END) {
tod = Resolve (line_ptr->Schedule (run, stops));
} else {
tod = Resolve ((line_ptr->Schedule (run, stops) + line_ptr->Schedule (run, 1)) / 2);
}
if (period_flag) {
period = select_periods.Period (tod);
} else {
period = 1;
}
if (period > 0) {
num_runs [period]++;
}
}
for (period=1; period <= num_period; period++) {
if (num_runs [period] > 0) {
num_new [period] = (int) (num_runs [period] * service_factor + random.Probability ());
if (num_new [period] < 1) num_new [period] = 1;
if (num_new [period] != num_runs [period]) {
increment [period] = (duration [period] + num_new [period] / 2) / num_new [period];
start [period] += increment [period] / 2;
change = true;
}
}
}
}
//---- save each run and stop ----
for (run=1; run <= runs; run++) {
if (method == RUN_START) {
tod = Resolve (line_ptr->Schedule (run, 1));
} else if (method == RUN_END) {
tod = Resolve (line_ptr->Schedule (run, stops));
} else {
tod = Resolve ((line_ptr->Schedule (run, stops) + line_ptr->Schedule (run, 1)) / 2);
}
shift = period = 0;
num_in++;
skip = !flag && !change;
if (!skip) {
if (period_flag) {
period = select_periods.Period (tod);
} else {
period = 1;
}
if (period > 0 && num_runs [period] != num_new [period]) {
if (num [period] >= num_new [period]) continue;
shift = start [period] - tod;
start [period] += increment [period];
num [period]++;
} else {
skip = true;
}
}
for (stop=1; stop <= stops; stop++) {
new_schedule->Stop (line_ptr->Stop (stop));
new_schedule->Time (Resolve (line_ptr->Schedule (run, stop)) + shift);
if (!new_schedule->Write ()) {
Error ("Writing %s", new_schedule->File_Type ());
}
count++;
}
num_out++;
if (!skip && num [period] == num_runs [period] && num_new [period] > num_runs [period]) {
for (; num [period] < num_new [period]; num [period]++) {
shift += increment [period];
for (stop=1; stop <= stops; stop++) {
new_schedule->Stop (line_ptr->Stop (stop));
new_schedule->Time (Resolve (line_ptr->Schedule (run, stop)) + shift);
if (!new_schedule->Write ()) {
Error ("Writing %s", new_schedule->File_Type ());
}
count++;
}
num_out++;
}
}
}
}
End_Progress ();
Write (2, "Number of %s Records = %d", new_schedule->File_Type (), count);
Write (1, "Number of Input Transit Runs = %d", num_in);
Write (1, "Number of Output Transit Runs = %d", num_out);
}
|
//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for initializers.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/Initialization.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/Designator.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/SemaHLSL.h" // HLSL Change
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace clang;
//===----------------------------------------------------------------------===//
// Sema Initialization Checking
//===----------------------------------------------------------------------===//
/// \brief Check whether T is compatible with a wide character type (wchar_t,
/// char16_t or char32_t).
static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
if (Context.typesAreCompatible(Context.getWideCharType(), T))
return true;
if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
return Context.typesAreCompatible(Context.Char16Ty, T) ||
Context.typesAreCompatible(Context.Char32Ty, T);
}
return false;
}
enum StringInitFailureKind {
SIF_None,
SIF_NarrowStringIntoWideChar,
SIF_WideStringIntoChar,
SIF_IncompatWideStringIntoWideChar,
SIF_Other
};
/// \brief Check whether the array of type AT can be initialized by the Init
/// expression by means of string initialization. Returns SIF_None if so,
/// otherwise returns a StringInitFailureKind that describes why the
/// initialization would not work.
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
ASTContext &Context) {
if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
return SIF_Other;
// See if this is a string literal or @encode.
Init = Init->IgnoreParens();
// Handle @encode, which is a narrow string.
if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
return SIF_None;
// Otherwise we can only handle string literals.
StringLiteral *SL = dyn_cast<StringLiteral>(Init);
if (!SL)
return SIF_Other;
const QualType ElemTy =
Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
switch (SL->getKind()) {
case StringLiteral::Ascii:
case StringLiteral::UTF8:
// char array can be initialized with a narrow string.
// Only allow char x[] = "foo"; not char x[] = L"foo";
if (ElemTy->isCharType())
return SIF_None;
if (IsWideCharCompatible(ElemTy, Context))
return SIF_NarrowStringIntoWideChar;
return SIF_Other;
// C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
// "An array with element type compatible with a qualified or unqualified
// version of wchar_t, char16_t, or char32_t may be initialized by a wide
// string literal with the corresponding encoding prefix (L, u, or U,
// respectively), optionally enclosed in braces.
case StringLiteral::UTF16:
if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
return SIF_None;
if (ElemTy->isCharType())
return SIF_WideStringIntoChar;
if (IsWideCharCompatible(ElemTy, Context))
return SIF_IncompatWideStringIntoWideChar;
return SIF_Other;
case StringLiteral::UTF32:
if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
return SIF_None;
if (ElemTy->isCharType())
return SIF_WideStringIntoChar;
if (IsWideCharCompatible(ElemTy, Context))
return SIF_IncompatWideStringIntoWideChar;
return SIF_Other;
case StringLiteral::Wide:
if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
return SIF_None;
if (ElemTy->isCharType())
return SIF_WideStringIntoChar;
if (IsWideCharCompatible(ElemTy, Context))
return SIF_IncompatWideStringIntoWideChar;
return SIF_Other;
}
llvm_unreachable("missed a StringLiteral kind?");
}
static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
ASTContext &Context) {
const ArrayType *arrayType = Context.getAsArrayType(declType);
if (!arrayType)
return SIF_Other;
return IsStringInit(init, arrayType, Context);
}
/// Update the type of a string literal, including any surrounding parentheses,
/// to match the type of the object which it is initializing.
static void updateStringLiteralType(Expr *E, QualType Ty) {
while (true) {
E->setType(Ty);
if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
break;
else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
E = PE->getSubExpr();
else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
E = UO->getSubExpr();
else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
E = GSE->getResultExpr();
else
llvm_unreachable("unexpected expr in string literal init");
}
}
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
Sema &S) {
// Get the length of the string as parsed.
auto *ConstantArrayTy =
cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
// C99 6.7.8p14. We have an array of character type with unknown size
// being initialized to a string literal.
llvm::APInt ConstVal(32, StrLength);
// Return a new array type (C99 6.7.8p22).
DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
ConstVal,
ArrayType::Normal, 0);
updateStringLiteralType(Str, DeclT);
return;
}
const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
// We have an array of character type with known size. However,
// the size may be smaller or larger than the string we are initializing.
// FIXME: Avoid truncation for 64-bit length strings.
if (S.getLangOpts().CPlusPlus) {
if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
// For Pascal strings it's OK to strip off the terminating null character,
// so the example below is valid:
//
// unsigned char a[2] = "\pa";
if (SL->isPascal())
StrLength--;
}
// [dcl.init.string]p2
if (StrLength > CAT->getSize().getZExtValue())
S.Diag(Str->getLocStart(),
diag::err_initializer_string_for_char_array_too_long)
<< Str->getSourceRange();
} else {
// C99 6.7.8p14.
if (StrLength-1 > CAT->getSize().getZExtValue())
S.Diag(Str->getLocStart(),
diag::ext_initializer_string_for_char_array_too_long)
<< Str->getSourceRange();
}
// Set the type to the actual size that we are initializing. If we have
// something like:
// char x[1] = "foo";
// then this will set the string literal's type to char[1].
updateStringLiteralType(Str, DeclT);
}
//===----------------------------------------------------------------------===//
// Semantic checking for initializer lists.
//===----------------------------------------------------------------------===//
/// @brief Semantic checking for initializer lists.
///
/// The InitListChecker class contains a set of routines that each
/// handle the initialization of a certain kind of entity, e.g.,
/// arrays, vectors, struct/union types, scalars, etc. The
/// InitListChecker itself performs a recursive walk of the subobject
/// structure of the type to be initialized, while stepping through
/// the initializer list one element at a time. The IList and Index
/// parameters to each of the Check* routines contain the active
/// (syntactic) initializer list and the index into that initializer
/// list that represents the current initializer. Each routine is
/// responsible for moving that Index forward as it consumes elements.
///
/// Each Check* routine also has a StructuredList/StructuredIndex
/// arguments, which contains the current "structured" (semantic)
/// initializer list and the index into that initializer list where we
/// are copying initializers as we map them over to the semantic
/// list. Once we have completed our recursive walk of the subobject
/// structure, we will have constructed a full semantic initializer
/// list.
///
/// C99 designators cause changes in the initializer list traversal,
/// because they make the initialization "jump" into a specific
/// subobject and then continue the initialization from that
/// point. CheckDesignatedInitializer() recursively steps into the
/// designated subobject and manages backing out the recursion to
/// initialize the subobjects after the one designated.
namespace {
class InitListChecker {
Sema &SemaRef;
const InitializationKind &Kind; // HLSL Change: provide access to the initialization kind
bool hadError;
bool VerifyOnly; // no diagnostics, no structure building
llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
InitListExpr *FullyStructuredList;
void CheckImplicitInitList(const InitializedEntity &Entity,
InitListExpr *ParentIList, QualType T,
unsigned &Index, InitListExpr *StructuredList,
unsigned &StructuredIndex);
void CheckExplicitInitList(const InitializedEntity &Entity,
InitListExpr *IList, QualType &T,
InitListExpr *StructuredList,
bool TopLevelObject = false);
void CheckListElementTypes(const InitializedEntity &Entity,
InitListExpr *IList, QualType &DeclType,
bool SubobjectIsDesignatorContext,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex,
bool TopLevelObject = false);
void CheckSubElementType(const InitializedEntity &Entity,
InitListExpr *IList, QualType ElemType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex);
void CheckComplexType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex);
void CheckScalarType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex);
void CheckReferenceType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex);
void CheckVectorType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType, unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex);
void CheckStructUnionTypes(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
RecordDecl::field_iterator Field,
bool SubobjectIsDesignatorContext, unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex,
bool TopLevelObject = false);
void CheckArrayType(const InitializedEntity &Entity,
InitListExpr *IList, QualType &DeclType,
llvm::APSInt elementIndex,
bool SubobjectIsDesignatorContext, unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex);
bool CheckDesignatedInitializer(const InitializedEntity &Entity,
InitListExpr *IList, DesignatedInitExpr *DIE,
unsigned DesigIdx,
QualType &CurrentObjectType,
RecordDecl::field_iterator *NextField,
llvm::APSInt *NextElementIndex,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex,
bool FinishSubobjectInit,
bool TopLevelObject);
InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
QualType CurrentObjectType,
InitListExpr *StructuredList,
unsigned StructuredIndex,
SourceRange InitRange,
bool IsFullyOverwritten = false);
void UpdateStructuredListElement(InitListExpr *StructuredList,
unsigned &StructuredIndex,
Expr *expr);
int numArrayElements(QualType DeclType);
int numStructUnionElements(QualType DeclType);
static ExprResult PerformEmptyInit(Sema &SemaRef,
SourceLocation Loc,
const InitializedEntity &Entity,
bool VerifyOnly);
// Explanation on the "FillWithNoInit" mode:
//
// Assume we have the following definitions (Case#1):
// struct P { char x[6][6]; } xp = { .x[1] = "bar" };
// struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
//
// l.lp.x[1][0..1] should not be filled with implicit initializers because the
// "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
//
// But if we have (Case#2):
// struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
//
// l.lp.x[1][0..1] are implicitly initialized and do not use values from the
// "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
//
// To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
// in the InitListExpr, the "holes" in Case#1 are filled not with empty
// initializers but with special "NoInitExpr" place holders, which tells the
// CodeGen not to generate any initializers for these parts.
void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
const InitializedEntity &ParentEntity,
InitListExpr *ILE, bool &RequiresSecondPass,
bool FillWithNoInit = false);
void FillInEmptyInitializations(const InitializedEntity &Entity,
InitListExpr *ILE, bool &RequiresSecondPass,
bool FillWithNoInit = false);
bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
Expr *InitExpr, FieldDecl *Field,
bool TopLevelObject);
void CheckEmptyInitializable(const InitializedEntity &Entity,
SourceLocation Loc);
public:
InitListChecker(Sema &S, const InitializedEntity &Entity, const InitializationKind &K, // HLSL Change - add Kind
InitListExpr *IL, QualType &T, bool VerifyOnly);
bool HadError() { return hadError; }
// @brief Retrieves the fully-structured initializer list used for
// semantic analysis and code generation.
InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
};
} // end anonymous namespace
ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
SourceLocation Loc,
const InitializedEntity &Entity,
bool VerifyOnly) {
InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
true);
MultiExprArg SubInit;
Expr *InitExpr;
InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
// C++ [dcl.init.aggr]p7:
// If there are fewer initializer-clauses in the list than there are
// members in the aggregate, then each member not explicitly initialized
// ...
bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
if (EmptyInitList) {
// C++1y / DR1070:
// shall be initialized [...] from an empty initializer list.
//
// We apply the resolution of this DR to C++11 but not C++98, since C++98
// does not have useful semantics for initialization from an init list.
// We treat this as copy-initialization, because aggregate initialization
// always performs copy-initialization on its elements.
//
// Only do this if we're initializing a class type, to avoid filling in
// the initializer list where possible.
InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
InitListExpr(SemaRef.Context, Loc, None, Loc);
InitExpr->setType(SemaRef.Context.VoidTy);
SubInit = InitExpr;
Kind = InitializationKind::CreateCopy(Loc, Loc);
} else {
// C++03:
// shall be value-initialized.
}
InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
// libstdc++4.6 marks the vector default constructor as explicit in
// _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
// stlport does so too. Look for std::__debug for libstdc++, and for
// std:: for stlport. This is effectively a compiler-side implementation of
// LWG2193.
if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
InitializationSequence::FK_ExplicitConstructor) {
OverloadCandidateSet::iterator Best;
OverloadingResult O =
InitSeq.getFailedCandidateSet()
.BestViableFunction(SemaRef, Kind.getLocation(), Best);
(void)O;
assert(O == OR_Success && "Inconsistent overload resolution");
CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
CXXRecordDecl *R = CtorDecl->getParent();
if (CtorDecl->getMinRequiredArguments() == 0 &&
CtorDecl->isExplicit() && R->getDeclName() &&
SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
bool IsInStd = false;
for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
IsInStd = true;
}
if (IsInStd && llvm::StringSwitch<bool>(R->getName())
.Cases("basic_string", "deque", "forward_list", true)
.Cases("list", "map", "multimap", "multiset", true)
.Cases("priority_queue", "queue", "set", "stack", true)
.Cases("unordered_map", "unordered_set", "vector", true)
.Default(false)) {
InitSeq.InitializeFrom(
SemaRef, Entity,
InitializationKind::CreateValue(Loc, Loc, Loc, true),
MultiExprArg(), /*TopLevelOfInitList=*/false);
// Emit a warning for this. System header warnings aren't shown
// by default, but people working on system headers should see it.
if (!VerifyOnly) {
SemaRef.Diag(CtorDecl->getLocation(),
diag::warn_invalid_initializer_from_system_header);
SemaRef.Diag(Entity.getDecl()->getLocation(),
diag::note_used_in_initialization_here);
}
}
}
}
if (!InitSeq) {
if (!VerifyOnly) {
InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
if (Entity.getKind() == InitializedEntity::EK_Member)
SemaRef.Diag(Entity.getDecl()->getLocation(),
diag::note_in_omitted_aggregate_initializer)
<< /*field*/1 << Entity.getDecl();
else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
<< /*array element*/0 << Entity.getElementIndex();
}
return ExprError();
}
return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
: InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
}
void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
SourceLocation Loc) {
assert(VerifyOnly &&
"CheckEmptyInitializable is only inteded for verification mode.");
if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
hadError = true;
}
void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
const InitializedEntity &ParentEntity,
InitListExpr *ILE,
bool &RequiresSecondPass,
bool FillWithNoInit) {
SourceLocation Loc = ILE->getLocEnd();
unsigned NumInits = ILE->getNumInits();
InitializedEntity MemberEntity
= InitializedEntity::InitializeMember(Field, &ParentEntity);
if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
if (!RType->getDecl()->isUnion())
assert(Init < NumInits && "This ILE should have been expanded");
if (Init >= NumInits || !ILE->getInit(Init)) {
if (FillWithNoInit) {
Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
if (Init < NumInits)
ILE->setInit(Init, Filler);
else
ILE->updateInit(SemaRef.Context, Init, Filler);
return;
}
// C++1y [dcl.init.aggr]p7:
// If there are fewer initializer-clauses in the list than there are
// members in the aggregate, then each member not explicitly initialized
// shall be initialized from its brace-or-equal-initializer [...]
if (Field->hasInClassInitializer()) {
ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
if (DIE.isInvalid()) {
hadError = true;
return;
}
if (Init < NumInits)
ILE->setInit(Init, DIE.get());
else {
ILE->updateInit(SemaRef.Context, Init, DIE.get());
RequiresSecondPass = true;
}
return;
}
if (Field->getType()->isReferenceType()) {
// C++ [dcl.init.aggr]p9:
// If an incomplete or empty initializer-list leaves a
// member of reference type uninitialized, the program is
// ill-formed.
SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
<< Field->getType()
<< ILE->getSyntacticForm()->getSourceRange();
SemaRef.Diag(Field->getLocation(),
diag::note_uninit_reference_member);
hadError = true;
return;
}
ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
/*VerifyOnly*/false);
if (MemberInit.isInvalid()) {
hadError = true;
return;
}
if (hadError) {
// Do nothing
} else if (Init < NumInits) {
ILE->setInit(Init, MemberInit.getAs<Expr>());
} else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
// Empty initialization requires a constructor call, so
// extend the initializer list to include the constructor
// call and make a note that we'll need to take another pass
// through the initializer list.
ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
RequiresSecondPass = true;
}
} else if (InitListExpr *InnerILE
= dyn_cast<InitListExpr>(ILE->getInit(Init)))
FillInEmptyInitializations(MemberEntity, InnerILE,
RequiresSecondPass, FillWithNoInit);
else if (DesignatedInitUpdateExpr *InnerDIUE
= dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
RequiresSecondPass, /*FillWithNoInit =*/ true);
}
/// Recursively replaces NULL values within the given initializer list
/// with expressions that perform value-initialization of the
/// appropriate type.
void
InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
InitListExpr *ILE,
bool &RequiresSecondPass,
bool FillWithNoInit) {
assert((ILE->getType() != SemaRef.Context.VoidTy) &&
"Should not have void type");
if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
const RecordDecl *RDecl = RType->getDecl();
if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Entity, ILE, RequiresSecondPass, FillWithNoInit);
else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
for (auto *Field : RDecl->fields()) {
if (Field->hasInClassInitializer()) {
FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
FillWithNoInit);
break;
}
}
} else {
// The fields beyond ILE->getNumInits() are default initialized, so in
// order to leave them uninitialized, the ILE is expanded and the extra
// fields are then filled with NoInitExpr.
unsigned NumFields = 0;
for (auto *Field : RDecl->fields())
if (!Field->isUnnamedBitfield())
++NumFields;
if (ILE->getNumInits() < NumFields)
ILE->resizeInits(SemaRef.Context, NumFields);
unsigned Init = 0;
for (auto *Field : RDecl->fields()) {
if (Field->isUnnamedBitfield())
continue;
if (hadError)
return;
FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
FillWithNoInit);
if (hadError)
return;
++Init;
// Only look at the first initialization of a union.
if (RDecl->isUnion())
break;
}
}
return;
}
QualType ElementType;
InitializedEntity ElementEntity = Entity;
unsigned NumInits = ILE->getNumInits();
unsigned NumElements = NumInits;
if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
ElementType = AType->getElementType();
if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
NumElements = CAType->getSize().getZExtValue();
ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
0, Entity);
} else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
ElementType = VType->getElementType();
NumElements = VType->getNumElements();
ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
0, Entity);
} else
ElementType = ILE->getType();
for (unsigned Init = 0; Init != NumElements; ++Init) {
if (hadError)
return;
if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
ElementEntity.setElementIndex(Init);
Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
ILE->setInit(Init, ILE->getArrayFiller());
else if (!InitExpr && !ILE->hasArrayFiller()) {
Expr *Filler = nullptr;
if (FillWithNoInit)
Filler = new (SemaRef.Context) NoInitExpr(ElementType);
else {
ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
ElementEntity,
/*VerifyOnly*/false);
if (ElementInit.isInvalid()) {
hadError = true;
return;
}
Filler = ElementInit.getAs<Expr>();
}
if (hadError) {
// Do nothing
} else if (Init < NumInits) {
// For arrays, just set the expression used for value-initialization
// of the "holes" in the array.
if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
ILE->setArrayFiller(Filler);
else
ILE->setInit(Init, Filler);
} else {
// For arrays, just set the expression used for value-initialization
// of the rest of elements and exit.
if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
ILE->setArrayFiller(Filler);
return;
}
if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
// Empty initialization requires a constructor call, so
// extend the initializer list to include the constructor
// call and make a note that we'll need to take another pass
// through the initializer list.
ILE->updateInit(SemaRef.Context, Init, Filler);
RequiresSecondPass = true;
}
}
} else if (InitListExpr *InnerILE
= dyn_cast_or_null<InitListExpr>(InitExpr))
FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
FillWithNoInit);
else if (DesignatedInitUpdateExpr *InnerDIUE
= dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
RequiresSecondPass, /*FillWithNoInit =*/ true);
}
}
InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
const InitializationKind &K, // HLSL Change - add K
InitListExpr *IL, QualType &T,
bool VerifyOnly)
: SemaRef(S), Kind(K), VerifyOnly(VerifyOnly) { // HLSL Change - add Kind
// FIXME: Check that IL isn't already the semantic form of some other
// InitListExpr. If it is, we'd create a broken AST.
hadError = false;
FullyStructuredList =
getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
/*TopLevelObject=*/true);
if (!hadError && !VerifyOnly) {
bool RequiresSecondPass = false;
FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
if (RequiresSecondPass && !hadError)
FillInEmptyInitializations(Entity, FullyStructuredList,
RequiresSecondPass);
}
}
int InitListChecker::numArrayElements(QualType DeclType) {
// FIXME: use a proper constant
int maxElements = 0x7FFFFFFF;
if (const ConstantArrayType *CAT =
SemaRef.Context.getAsConstantArrayType(DeclType)) {
maxElements = static_cast<int>(CAT->getSize().getZExtValue());
}
return maxElements;
}
int InitListChecker::numStructUnionElements(QualType DeclType) {
RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
int InitializableMembers = 0;
for (const auto *Field : structDecl->fields())
if (!Field->isUnnamedBitfield())
++InitializableMembers;
if (structDecl->isUnion())
return std::min(InitializableMembers, 1);
return InitializableMembers - structDecl->hasFlexibleArrayMember();
}
/// Check whether the range of the initializer \p ParentIList from element
/// \p Index onwards can be used to initialize an object of type \p T. Update
/// \p Index to indicate how many elements of the list were consumed.
///
/// This also fills in \p StructuredList, from element \p StructuredIndex
/// onwards, with the fully-braced, desugared form of the initialization.
void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
InitListExpr *ParentIList,
QualType T, unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
int maxElements = 0;
if (T->isArrayType())
maxElements = numArrayElements(T);
else if (T->isRecordType())
maxElements = numStructUnionElements(T);
else if (T->isVectorType())
maxElements = T->getAs<VectorType>()->getNumElements();
else
llvm_unreachable("CheckImplicitInitList(): Illegal type");
if (maxElements == 0) {
if (!VerifyOnly)
SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
diag::err_implicit_empty_initializer);
++Index;
hadError = true;
return;
}
// Build a structured initializer list corresponding to this subobject.
InitListExpr *StructuredSubobjectInitList
= getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
StructuredIndex,
SourceRange(ParentIList->getInit(Index)->getLocStart(),
ParentIList->getSourceRange().getEnd()));
unsigned StructuredSubobjectInitIndex = 0;
// Check the element types and build the structural subobject.
unsigned StartIndex = Index;
CheckListElementTypes(Entity, ParentIList, T,
/*SubobjectIsDesignatorContext=*/false, Index,
StructuredSubobjectInitList,
StructuredSubobjectInitIndex);
if (!VerifyOnly) {
StructuredSubobjectInitList->setType(T);
unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
// Update the structured sub-object initializer so that it's ending
// range corresponds with the end of the last initializer it used.
if (EndIndex < ParentIList->getNumInits()) {
SourceLocation EndLoc
= ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
StructuredSubobjectInitList->setRBraceLoc(EndLoc);
}
// Complain about missing braces.
if (T->isArrayType() || T->isRecordType()) {
SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
diag::warn_missing_braces)
<< StructuredSubobjectInitList->getSourceRange()
<< FixItHint::CreateInsertion(
StructuredSubobjectInitList->getLocStart(), "{")
<< FixItHint::CreateInsertion(
SemaRef.getLocForEndOfToken(
StructuredSubobjectInitList->getLocEnd()),
"}");
}
}
}
/// Warn that \p Entity was of scalar type and was initialized by a
/// single-element braced initializer list.
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
SourceRange Braces) {
// Don't warn during template instantiation. If the initialization was
// non-dependent, we warned during the initial parse; otherwise, the
// type might not be scalar in some uses of the template.
if (!S.ActiveTemplateInstantiations.empty())
return;
unsigned DiagID = 0;
switch (Entity.getKind()) {
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_ComplexElement:
case InitializedEntity::EK_ArrayElement:
case InitializedEntity::EK_Parameter:
case InitializedEntity::EK_Parameter_CF_Audited:
case InitializedEntity::EK_Result:
// Extra braces here are suspicious.
DiagID = diag::warn_braces_around_scalar_init;
break;
case InitializedEntity::EK_Member:
// Warn on aggregate initialization but not on ctor init list or
// default member initializer.
if (Entity.getParent())
DiagID = diag::warn_braces_around_scalar_init;
break;
case InitializedEntity::EK_Variable:
case InitializedEntity::EK_LambdaCapture:
// No warning, might be direct-list-initialization.
// FIXME: Should we warn for copy-list-initialization in these cases?
break;
case InitializedEntity::EK_New:
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_CompoundLiteralInit:
// No warning, braces are part of the syntax of the underlying construct.
break;
case InitializedEntity::EK_RelatedResult:
// No warning, we already warned when initializing the result.
break;
case InitializedEntity::EK_Exception:
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
case InitializedEntity::EK_BlockElement:
llvm_unreachable("unexpected braced scalar init");
}
if (DiagID) {
S.Diag(Braces.getBegin(), DiagID)
<< Braces
<< FixItHint::CreateRemoval(Braces.getBegin())
<< FixItHint::CreateRemoval(Braces.getEnd());
}
}
/// Check whether the initializer \p IList (that was written with explicit
/// braces) can be used to initialize an object of type \p T.
///
/// This also fills in \p StructuredList with the fully-braced, desugared
/// form of the initialization.
void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
InitListExpr *IList, QualType &T,
InitListExpr *StructuredList,
bool TopLevelObject) {
assert((IList->isExplicit() || SemaRef.getLangOpts().HLSL) && "Illegal Implicit InitListExpr"); // HLSL Change: reuse in context of constructors for vectors
if (!VerifyOnly) {
SyntacticToSemantic[IList] = StructuredList;
StructuredList->setSyntacticForm(IList);
}
unsigned Index = 0, StructuredIndex = 0;
CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Index, StructuredList, StructuredIndex, TopLevelObject);
if (!VerifyOnly) {
QualType ExprTy = T;
if (!ExprTy->isArrayType())
ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
IList->setType(ExprTy);
StructuredList->setType(ExprTy);
}
if (hadError)
return;
if (Index < IList->getNumInits()) {
// We have leftover initializers
if (VerifyOnly) {
if (SemaRef.getLangOpts().CPlusPlus ||
(SemaRef.getLangOpts().OpenCL &&
IList->getType()->isVectorType())) {
hadError = true;
}
return;
}
if (StructuredIndex == 1 &&
IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
SIF_None) {
unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
if (SemaRef.getLangOpts().CPlusPlus) {
DK = diag::err_excess_initializers_in_char_array_initializer;
hadError = true;
}
// Special-case
SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
<< IList->getInit(Index)->getSourceRange();
} else if (!T->isIncompleteType()) {
// Don't complain for incomplete types, since we'll get an error
// elsewhere
QualType CurrentObjectType = StructuredList->getType();
int initKind =
CurrentObjectType->isArrayType()? 0 :
CurrentObjectType->isVectorType()? 1 :
CurrentObjectType->isScalarType()? 2 :
CurrentObjectType->isUnionType()? 3 :
4;
unsigned DK = diag::ext_excess_initializers;
if (SemaRef.getLangOpts().CPlusPlus) {
DK = diag::err_excess_initializers;
hadError = true;
}
if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
DK = diag::err_excess_initializers;
hadError = true;
}
SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
<< initKind << IList->getInit(Index)->getSourceRange();
}
}
if (!VerifyOnly && T->isScalarType() &&
IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
}
void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
InitListExpr *IList,
QualType &DeclType,
bool SubobjectIsDesignatorContext,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex,
bool TopLevelObject) {
if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
// Explicitly braced initializer for complex type can be real+imaginary
// parts.
CheckComplexType(Entity, IList, DeclType, Index,
StructuredList, StructuredIndex);
} else if (DeclType->isScalarType()) {
CheckScalarType(Entity, IList, DeclType, Index,
StructuredList, StructuredIndex);
} else if (DeclType->isVectorType()) {
CheckVectorType(Entity, IList, DeclType, Index,
StructuredList, StructuredIndex);
} else if (DeclType->isRecordType()) {
assert(DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType");
RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
SubobjectIsDesignatorContext, Index,
StructuredList, StructuredIndex,
TopLevelObject);
} else if (DeclType->isArrayType()) {
llvm::APSInt Zero(
SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
false);
CheckArrayType(Entity, IList, DeclType, Zero,
SubobjectIsDesignatorContext, Index,
StructuredList, StructuredIndex);
} else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
// This type is invalid, issue a diagnostic.
++Index;
if (!VerifyOnly)
SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
<< DeclType;
hadError = true;
} else if (DeclType->isReferenceType()) {
CheckReferenceType(Entity, IList, DeclType, Index,
StructuredList, StructuredIndex);
} else if (DeclType->isObjCObjectType()) {
if (!VerifyOnly)
SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
<< DeclType;
hadError = true;
} else {
if (!VerifyOnly)
SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
<< DeclType;
hadError = true;
}
}
void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
InitListExpr *IList,
QualType ElemType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
Expr *expr = IList->getInit(Index);
if (ElemType->isReferenceType())
return CheckReferenceType(Entity, IList, ElemType, Index,
StructuredList, StructuredIndex);
if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
if (SubInitList->getNumInits() == 1 &&
IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
SIF_None) {
expr = SubInitList->getInit(0);
} else if (!SemaRef.getLangOpts().CPlusPlus) {
InitListExpr *InnerStructuredList
= getStructuredSubobjectInit(IList, Index, ElemType,
StructuredList, StructuredIndex,
SubInitList->getSourceRange(), true);
CheckExplicitInitList(Entity, SubInitList, ElemType,
InnerStructuredList);
if (!hadError && !VerifyOnly) {
bool RequiresSecondPass = false;
FillInEmptyInitializations(Entity, InnerStructuredList,
RequiresSecondPass);
if (RequiresSecondPass && !hadError)
FillInEmptyInitializations(Entity, InnerStructuredList,
RequiresSecondPass);
}
++StructuredIndex;
++Index;
return;
}
// C++ initialization is handled later.
} else if (isa<ImplicitValueInitExpr>(expr)) {
// This happens during template instantiation when we see an InitListExpr
// that we've already checked once.
assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
"found implicit initialization for the wrong type");
if (!VerifyOnly)
UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
++Index;
return;
}
if (SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().HLSL) { // HLSL Change: use OpenCL-style rules
// C++ [dcl.init.aggr]p2:
// Each member is copy-initialized from the corresponding
// initializer-clause.
// FIXME: Better EqualLoc?
InitializationKind Kind =
InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
InitializationSequence Seq(SemaRef, Entity, Kind, expr,
/*TopLevelOfInitList*/ true);
// C++14 [dcl.init.aggr]p13:
// If the assignment-expression can initialize a member, the member is
// initialized. Otherwise [...] brace elision is assumed
//
// Brace elision is never performed if the element is not an
// assignment-expression.
if (Seq || isa<InitListExpr>(expr)) {
if (!VerifyOnly) {
ExprResult Result =
Seq.Perform(SemaRef, Entity, Kind, expr);
if (Result.isInvalid())
hadError = true;
UpdateStructuredListElement(StructuredList, StructuredIndex,
Result.getAs<Expr>());
} else if (!Seq)
hadError = true;
++Index;
return;
}
// Fall through for subaggregate initialization
} else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
// FIXME: Need to handle atomic aggregate types with implicit init lists.
return CheckScalarType(Entity, IList, ElemType, Index,
StructuredList, StructuredIndex);
} else if (const ArrayType *arrayType =
SemaRef.Context.getAsArrayType(ElemType)) {
// arrayType can be incomplete if we're initializing a flexible
// array member. There's nothing we can do with the completed
// type here, though.
if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
if (!VerifyOnly) {
CheckStringInit(expr, ElemType, arrayType, SemaRef);
UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
}
++Index;
return;
}
// Fall through for subaggregate initialization.
} else {
assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
"Unexpected type");
// C99 6.7.8p13:
//
// The initializer for a structure or union object that has
// automatic storage duration shall be either an initializer
// list as described below, or a single expression that has
// compatible structure or union type. In the latter case, the
// initial value of the object, including unnamed members, is
// that of the expression.
ExprResult ExprRes = expr;
if (SemaRef.CheckSingleAssignmentConstraints(
ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
if (ExprRes.isInvalid())
hadError = true;
else {
ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
if (ExprRes.isInvalid())
hadError = true;
}
UpdateStructuredListElement(StructuredList, StructuredIndex,
ExprRes.getAs<Expr>());
++Index;
return;
}
ExprRes.get();
// Fall through for subaggregate initialization
}
// C++ [dcl.init.aggr]p12:
//
// [...] Otherwise, if the member is itself a non-empty
// subaggregate, brace elision is assumed and the initializer is
// considered for the initialization of the first member of
// the subaggregate.
if (!SemaRef.getLangOpts().OpenCL &&
(ElemType->isAggregateType() || ElemType->isVectorType())) {
CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
StructuredIndex);
++StructuredIndex;
} else {
if (!VerifyOnly) {
// We cannot initialize this element, so let
// PerformCopyInitialization produce the appropriate diagnostic.
SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
/*TopLevelOfInitList=*/true);
}
hadError = true;
++Index;
++StructuredIndex;
}
}
void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
assert(Index == 0 && "Index in explicit init list must be zero");
// As an extension, clang supports complex initializers, which initialize
// a complex number component-wise. When an explicit initializer list for
// a complex number contains two two initializers, this extension kicks in:
// it exepcts the initializer list to contain two elements convertible to
// the element type of the complex type. The first element initializes
// the real part, and the second element intitializes the imaginary part.
if (IList->getNumInits() != 2)
return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
StructuredIndex);
// This is an extension in C. (The builtin _Complex type does not exist
// in the C++ standard.)
if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
<< IList->getSourceRange();
// Initialize the complex number.
QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
InitializedEntity ElementEntity =
InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
for (unsigned i = 0; i < 2; ++i) {
ElementEntity.setElementIndex(Index);
CheckSubElementType(ElementEntity, IList, elementType, Index,
StructuredList, StructuredIndex);
}
}
void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
if (Index >= IList->getNumInits()) {
if (!VerifyOnly)
SemaRef.Diag(IList->getLocStart(),
SemaRef.getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_empty_scalar_initializer :
diag::err_empty_scalar_initializer)
<< IList->getSourceRange();
hadError = !SemaRef.getLangOpts().CPlusPlus11;
++Index;
++StructuredIndex;
return;
}
Expr *expr = IList->getInit(Index);
if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
// FIXME: This is invalid, and accepting it causes overload resolution
// to pick the wrong overload in some corner cases.
if (!VerifyOnly)
SemaRef.Diag(SubIList->getLocStart(),
diag::ext_many_braces_around_scalar_init)
<< SubIList->getSourceRange();
CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
StructuredIndex);
return;
} else if (isa<DesignatedInitExpr>(expr)) {
if (!VerifyOnly)
SemaRef.Diag(expr->getLocStart(),
diag::err_designator_for_scalar_init)
<< DeclType << expr->getSourceRange();
hadError = true;
++Index;
++StructuredIndex;
return;
}
if (VerifyOnly) {
if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
hadError = true;
++Index;
return;
}
ExprResult Result =
SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
/*TopLevelOfInitList=*/true);
Expr *ResultExpr = nullptr;
if (Result.isInvalid())
hadError = true; // types weren't compatible.
else {
ResultExpr = Result.getAs<Expr>();
if (ResultExpr != expr) {
// The type was promoted, update initializer list.
IList->setInit(Index, ResultExpr);
}
}
if (hadError)
++StructuredIndex;
else
UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
++Index;
}
void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
if (Index >= IList->getNumInits()) {
// FIXME: It would be wonderful if we could point at the actual member. In
// general, it would be useful to pass location information down the stack,
// so that we know the location (or decl) of the "current object" being
// initialized.
if (!VerifyOnly)
SemaRef.Diag(IList->getLocStart(),
diag::err_init_reference_member_uninitialized)
<< DeclType
<< IList->getSourceRange();
hadError = true;
++Index;
++StructuredIndex;
return;
}
Expr *expr = IList->getInit(Index);
if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
if (!VerifyOnly)
SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
<< DeclType << IList->getSourceRange();
hadError = true;
++Index;
++StructuredIndex;
return;
}
if (VerifyOnly) {
if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
hadError = true;
++Index;
return;
}
ExprResult Result =
SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
/*TopLevelOfInitList=*/true);
if (Result.isInvalid())
hadError = true;
expr = Result.getAs<Expr>();
IList->setInit(Index, expr);
if (hadError)
++StructuredIndex;
else
UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
++Index;
}
void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
InitListExpr *IList, QualType DeclType,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
const VectorType *VT = DeclType->getAs<VectorType>();
unsigned maxElements = VT->getNumElements();
unsigned numEltsInit = 0;
QualType elementType = VT->getElementType();
if (Index >= IList->getNumInits()) {
// Make sure the element type can be value-initialized.
if (VerifyOnly)
CheckEmptyInitializable(
InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
IList->getLocEnd());
return;
}
// HLSL Change - HLSL is more similar to OpenCL than C/C++
if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL) {
// If the initializing element is a vector, try to copy-initialize
// instead of breaking it apart (which is doomed to failure anyway).
Expr *Init = IList->getInit(Index);
if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
if (VerifyOnly) {
if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
hadError = true;
++Index;
return;
}
ExprResult Result =
SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
/*TopLevelOfInitList=*/true);
Expr *ResultExpr = nullptr;
if (Result.isInvalid())
hadError = true; // types weren't compatible.
else {
ResultExpr = Result.getAs<Expr>();
if (ResultExpr != Init) {
// The type was promoted, update initializer list.
IList->setInit(Index, ResultExpr);
}
}
if (hadError)
++StructuredIndex;
else
UpdateStructuredListElement(StructuredList, StructuredIndex,
ResultExpr);
++Index;
return;
}
InitializedEntity ElementEntity =
InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
// Don't attempt to go past the end of the init list
if (Index >= IList->getNumInits()) {
if (VerifyOnly)
CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
break;
}
ElementEntity.setElementIndex(Index);
CheckSubElementType(ElementEntity, IList, elementType, Index,
StructuredList, StructuredIndex);
}
if (VerifyOnly)
return;
bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
const VectorType *T = Entity.getType()->getAs<VectorType>();
if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
T->getVectorKind() == VectorType::NeonPolyVector)) {
// The ability to use vector initializer lists is a GNU vector extension
// and is unrelated to the NEON intrinsics in arm_neon.h. On little
// endian machines it works fine, however on big endian machines it
// exhibits surprising behaviour:
//
// uint32x2_t x = {42, 64};
// return vget_lane_u32(x, 0); // Will return 64.
//
// Because of this, explicitly call out that it is non-portable.
//
SemaRef.Diag(IList->getLocStart(),
diag::warn_neon_vector_initializer_non_portable);
const char *typeCode;
unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
if (elementType->isFloatingType())
typeCode = "f";
else if (elementType->isSignedIntegerType())
typeCode = "s";
else if (elementType->isUnsignedIntegerType())
typeCode = "u";
else
llvm_unreachable("Invalid element type!");
SemaRef.Diag(IList->getLocStart(),
SemaRef.Context.getTypeSize(VT) > 64 ?
diag::note_neon_vector_initializer_non_portable_q :
diag::note_neon_vector_initializer_non_portable)
<< typeCode << typeSize;
}
return;
}
InitializedEntity ElementEntity =
InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
// OpenCL initializers allows vectors to be constructed from vectors.
for (unsigned i = 0; i < maxElements; ++i) {
// Don't attempt to go past the end of the init list
if (Index >= IList->getNumInits())
break;
ElementEntity.setElementIndex(Index);
QualType IType = IList->getInit(Index)->getType();
if (!IType->isVectorType()) {
CheckSubElementType(ElementEntity, IList, elementType, Index,
StructuredList, StructuredIndex);
++numEltsInit;
} else {
QualType VecType;
const VectorType *IVT = IType->getAs<VectorType>();
unsigned numIElts = IVT->getNumElements();
if (IType->isExtVectorType())
VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
else
VecType = SemaRef.Context.getVectorType(elementType, numIElts,
IVT->getVectorKind());
CheckSubElementType(ElementEntity, IList, VecType, Index,
StructuredList, StructuredIndex);
numEltsInit += numIElts;
}
}
// HLSL Change Starts
// For copy assignments that aren't explicit initialization lists, allow extra elements (emit a warning though).
bool extraElementsAllowed = false;
if (SemaRef.getLangOpts().HLSL && IList->getLBraceLoc().isInvalid()) {
extraElementsAllowed = numEltsInit > maxElements;
if (extraElementsAllowed && !VerifyOnly) {
SemaRef.Diag(Kind.getLocation(), diag::warn_hlsl_implicit_vector_truncation);
}
}
// HLSL Change Ends
// OpenCL requires all elements to be initialized.
if (numEltsInit != maxElements && !extraElementsAllowed) { // HLSL Change
if (!VerifyOnly) {
static const unsigned selectVectorIdx = 0;
SemaRef.Diag(IList->getLocStart(),
diag::err_incorrect_num_initializers)
<< (numEltsInit < maxElements) << selectVectorIdx << maxElements << numEltsInit;
}
hadError = true;
}
}
void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
InitListExpr *IList, QualType &DeclType,
llvm::APSInt elementIndex,
bool SubobjectIsDesignatorContext,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex) {
const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
// Check for the special-case of initializing an array with a string.
if (Index < IList->getNumInits()) {
if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
SIF_None) {
// We place the string literal directly into the resulting
// initializer list. This is the only place where the structure
// of the structured initializer list doesn't match exactly,
// because doing so would involve allocating one character
// constant for each string.
if (!VerifyOnly) {
CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
UpdateStructuredListElement(StructuredList, StructuredIndex,
IList->getInit(Index));
StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
}
++Index;
return;
}
}
if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
// Check for VLAs; in standard C it would be possible to check this
// earlier, but I don't know where clang accepts VLAs (gcc accepts
// them in all sorts of strange places).
if (!VerifyOnly)
SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
diag::err_variable_object_no_init)
<< VAT->getSizeExpr()->getSourceRange();
hadError = true;
++Index;
++StructuredIndex;
return;
}
// We might know the maximum number of elements in advance.
llvm::APSInt maxElements(elementIndex.getBitWidth(),
elementIndex.isUnsigned());
bool maxElementsKnown = false;
if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
maxElements = CAT->getSize();
elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
elementIndex.setIsUnsigned(maxElements.isUnsigned());
maxElementsKnown = true;
}
QualType elementType = arrayType->getElementType();
while (Index < IList->getNumInits()) {
Expr *Init = IList->getInit(Index);
if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
// If we're not the subobject that matches up with the '{' for
// the designator, we shouldn't be handling the
// designator. Return immediately.
if (!SubobjectIsDesignatorContext)
return;
// Handle this designated initializer. elementIndex will be
// updated to be the next array element we'll initialize.
if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
DeclType, nullptr, &elementIndex, Index,
StructuredList, StructuredIndex, true,
false)) {
hadError = true;
continue;
}
if (elementIndex.getBitWidth() > maxElements.getBitWidth())
maxElements = maxElements.extend(elementIndex.getBitWidth());
else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
elementIndex = elementIndex.extend(maxElements.getBitWidth());
elementIndex.setIsUnsigned(maxElements.isUnsigned());
// If the array is of incomplete type, keep track of the number of
// elements in the initializer.
if (!maxElementsKnown && elementIndex > maxElements)
maxElements = elementIndex;
continue;
}
// If we know the maximum number of elements, and we've already
// hit it, stop consuming elements in the initializer list.
if (maxElementsKnown && elementIndex == maxElements)
break;
InitializedEntity ElementEntity =
InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Entity);
// Check this element.
CheckSubElementType(ElementEntity, IList, elementType, Index,
StructuredList, StructuredIndex);
++elementIndex;
// If the array is of incomplete type, keep track of the number of
// elements in the initializer.
if (!maxElementsKnown && elementIndex > maxElements)
maxElements = elementIndex;
}
if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
// If this is an incomplete array type, the actual type needs to
// be calculated here.
llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
if (maxElements == Zero) {
// Sizing an array implicitly to zero is not allowed by ISO C,
// but is supported by GNU.
SemaRef.Diag(IList->getLocStart(),
diag::ext_typecheck_zero_array_size);
}
DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
ArrayType::Normal, 0);
}
if (!hadError && VerifyOnly) {
// Check if there are any members of the array that get value-initialized.
// If so, check if doing that is possible.
// FIXME: This needs to detect holes left by designated initializers too.
if (maxElementsKnown && elementIndex < maxElements)
CheckEmptyInitializable(InitializedEntity::InitializeElement(
SemaRef.Context, 0, Entity),
IList->getLocEnd());
}
}
bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
Expr *InitExpr,
FieldDecl *Field,
bool TopLevelObject) {
// Handle GNU flexible array initializers.
unsigned FlexArrayDiag;
if (isa<InitListExpr>(InitExpr) &&
cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
// Empty flexible array init always allowed as an extension
FlexArrayDiag = diag::ext_flexible_array_init;
} else if (SemaRef.getLangOpts().CPlusPlus) {
// Disallow flexible array init in C++; it is not required for gcc
// compatibility, and it needs work to IRGen correctly in general.
FlexArrayDiag = diag::err_flexible_array_init;
} else if (!TopLevelObject) {
// Disallow flexible array init on non-top-level object
FlexArrayDiag = diag::err_flexible_array_init;
} else if (Entity.getKind() != InitializedEntity::EK_Variable) {
// Disallow flexible array init on anything which is not a variable.
FlexArrayDiag = diag::err_flexible_array_init;
} else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
// Disallow flexible array init on local variables.
FlexArrayDiag = diag::err_flexible_array_init;
} else {
// Allow other cases.
FlexArrayDiag = diag::ext_flexible_array_init;
}
if (!VerifyOnly) {
SemaRef.Diag(InitExpr->getLocStart(),
FlexArrayDiag)
<< InitExpr->getLocStart();
SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
<< Field;
}
return FlexArrayDiag != diag::ext_flexible_array_init;
}
void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
InitListExpr *IList,
QualType DeclType,
RecordDecl::field_iterator Field,
bool SubobjectIsDesignatorContext,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex,
bool TopLevelObject) {
RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
// If the record is invalid, some of it's members are invalid. To avoid
// confusion, we forgo checking the intializer for the entire record.
if (structDecl->isInvalidDecl()) {
// Assume it was supposed to consume a single initializer.
++Index;
hadError = true;
return;
}
if (DeclType->isUnionType() && IList->getNumInits() == 0) {
RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
// If there's a default initializer, use it.
if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
if (VerifyOnly)
return;
for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Field != FieldEnd; ++Field) {
if (Field->hasInClassInitializer()) {
StructuredList->setInitializedFieldInUnion(*Field);
// FIXME: Actually build a CXXDefaultInitExpr?
return;
}
}
}
// Value-initialize the first member of the union that isn't an unnamed
// bitfield.
for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Field != FieldEnd; ++Field) {
if (!Field->isUnnamedBitfield()) {
if (VerifyOnly)
CheckEmptyInitializable(
InitializedEntity::InitializeMember(*Field, &Entity),
IList->getLocEnd());
else
StructuredList->setInitializedFieldInUnion(*Field);
break;
}
}
return;
}
// If structDecl is a forward declaration, this loop won't do
// anything except look at designated initializers; That's okay,
// because an error should get printed out elsewhere. It might be
// worthwhile to skip over the rest of the initializer, though.
RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
RecordDecl::field_iterator FieldEnd = RD->field_end();
bool InitializedSomething = false;
bool CheckForMissingFields = true;
while (Index < IList->getNumInits()) {
Expr *Init = IList->getInit(Index);
if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
// If we're not the subobject that matches up with the '{' for
// the designator, we shouldn't be handling the
// designator. Return immediately.
if (!SubobjectIsDesignatorContext)
return;
// Handle this designated initializer. Field will be updated to
// the next field that we'll be initializing.
if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
DeclType, &Field, nullptr, Index,
StructuredList, StructuredIndex,
true, TopLevelObject))
hadError = true;
InitializedSomething = true;
// Disable check for missing fields when designators are used.
// This matches gcc behaviour.
CheckForMissingFields = false;
continue;
}
if (Field == FieldEnd) {
// We've run out of fields. We're done.
break;
}
// We've already initialized a member of a union. We're done.
if (InitializedSomething && DeclType->isUnionType())
break;
// If we've hit the flexible array member at the end, we're done.
if (Field->getType()->isIncompleteArrayType())
break;
if (Field->isUnnamedBitfield()) {
// Don't initialize unnamed bitfields, e.g. "int : 20;"
++Field;
continue;
}
// Make sure we can use this declaration.
bool InvalidUse;
if (VerifyOnly)
InvalidUse = !SemaRef.CanUseDecl(*Field);
else
InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
IList->getInit(Index)->getLocStart());
if (InvalidUse) {
++Index;
++Field;
hadError = true;
continue;
}
InitializedEntity MemberEntity =
InitializedEntity::InitializeMember(*Field, &Entity);
CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
StructuredList, StructuredIndex);
InitializedSomething = true;
if (DeclType->isUnionType() && !VerifyOnly) {
// Initialize the first field within the union.
StructuredList->setInitializedFieldInUnion(*Field);
}
++Field;
}
// Emit warnings for missing struct field initializers.
if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
!DeclType->isUnionType()) {
// It is possible we have one or more unnamed bitfields remaining.
// Find first (if any) named field and emit warning.
for (RecordDecl::field_iterator it = Field, end = RD->field_end();
it != end; ++it) {
if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
SemaRef.Diag(IList->getSourceRange().getEnd(),
diag::warn_missing_field_initializers) << *it;
break;
}
}
}
// Check that any remaining fields can be value-initialized.
if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
!Field->getType()->isIncompleteArrayType()) {
// FIXME: Should check for holes left by designated initializers too.
for (; Field != FieldEnd && !hadError; ++Field) {
if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
CheckEmptyInitializable(
InitializedEntity::InitializeMember(*Field, &Entity),
IList->getLocEnd());
}
}
if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Index >= IList->getNumInits())
return;
if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
TopLevelObject)) {
hadError = true;
++Index;
return;
}
InitializedEntity MemberEntity =
InitializedEntity::InitializeMember(*Field, &Entity);
if (isa<InitListExpr>(IList->getInit(Index)))
CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
StructuredList, StructuredIndex);
else
CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
StructuredList, StructuredIndex);
}
/// \brief Expand a field designator that refers to a member of an
/// anonymous struct or union into a series of field designators that
/// refers to the field within the appropriate subobject.
///
static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
DesignatedInitExpr *DIE,
unsigned DesigIdx,
IndirectFieldDecl *IndirectField) {
typedef DesignatedInitExpr::Designator Designator;
// Build the replacement designators.
SmallVector<Designator, 4> Replacements;
for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
PE = IndirectField->chain_end(); PI != PE; ++PI) {
if (PI + 1 == PE)
Replacements.push_back(Designator((IdentifierInfo *)nullptr,
DIE->getDesignator(DesigIdx)->getDotLoc(),
DIE->getDesignator(DesigIdx)->getFieldLoc()));
else
Replacements.push_back(Designator((IdentifierInfo *)nullptr,
SourceLocation(), SourceLocation()));
assert(isa<FieldDecl>(*PI));
Replacements.back().setField(cast<FieldDecl>(*PI));
}
// Expand the current designator into the set of replacement
// designators, so we have a full subobject path down to where the
// member of the anonymous struct/union is actually stored.
DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
&Replacements[0] + Replacements.size());
}
static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
DesignatedInitExpr *DIE) {
unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
for (unsigned I = 0; I < NumIndexExprs; ++I)
IndexExprs[I] = DIE->getSubExpr(I + 1);
return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
DIE->size(), IndexExprs,
DIE->getEqualOrColonLoc(),
DIE->usesGNUSyntax(), DIE->getInit());
}
namespace {
// Callback to only accept typo corrections that are for field members of
// the given struct or union.
class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
public:
explicit FieldInitializerValidatorCCC(RecordDecl *RD)
: Record(RD) {}
bool ValidateCandidate(const TypoCorrection &candidate) override {
FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
}
private:
RecordDecl *Record;
};
}
/// @brief Check the well-formedness of a C99 designated initializer.
///
/// Determines whether the designated initializer @p DIE, which
/// resides at the given @p Index within the initializer list @p
/// IList, is well-formed for a current object of type @p DeclType
/// (C99 6.7.8). The actual subobject that this designator refers to
/// within the current subobject is returned in either
/// @p NextField or @p NextElementIndex (whichever is appropriate).
///
/// @param IList The initializer list in which this designated
/// initializer occurs.
///
/// @param DIE The designated initializer expression.
///
/// @param DesigIdx The index of the current designator.
///
/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
/// into which the designation in @p DIE should refer.
///
/// @param NextField If non-NULL and the first designator in @p DIE is
/// a field, this will be set to the field declaration corresponding
/// to the field named by the designator.
///
/// @param NextElementIndex If non-NULL and the first designator in @p
/// DIE is an array designator or GNU array-range designator, this
/// will be set to the last index initialized by this designator.
///
/// @param Index Index into @p IList where the designated initializer
/// @p DIE occurs.
///
/// @param StructuredList The initializer list expression that
/// describes all of the subobject initializers in the order they'll
/// actually be initialized.
///
/// @returns true if there was an error, false otherwise.
bool
InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
InitListExpr *IList,
DesignatedInitExpr *DIE,
unsigned DesigIdx,
QualType &CurrentObjectType,
RecordDecl::field_iterator *NextField,
llvm::APSInt *NextElementIndex,
unsigned &Index,
InitListExpr *StructuredList,
unsigned &StructuredIndex,
bool FinishSubobjectInit,
bool TopLevelObject) {
if (DesigIdx == DIE->size()) {
// Check the actual initialization for the designated object type.
bool prevHadError = hadError;
// Temporarily remove the designator expression from the
// initializer list that the child calls see, so that we don't try
// to re-process the designator.
unsigned OldIndex = Index;
IList->setInit(OldIndex, DIE->getInit());
CheckSubElementType(Entity, IList, CurrentObjectType, Index,
StructuredList, StructuredIndex);
// Restore the designated initializer expression in the syntactic
// form of the initializer list.
if (IList->getInit(OldIndex) != DIE->getInit())
DIE->setInit(IList->getInit(OldIndex));
IList->setInit(OldIndex, DIE);
return hadError && !prevHadError;
}
DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
bool IsFirstDesignator = (DesigIdx == 0);
if (!VerifyOnly) {
assert((IsFirstDesignator || StructuredList) &&
"Need a non-designated initializer list to start from");
// Determine the structural initializer list that corresponds to the
// current subobject.
if (IsFirstDesignator)
StructuredList = SyntacticToSemantic.lookup(IList);
else {
Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
StructuredList->getInit(StructuredIndex) : nullptr;
if (!ExistingInit && StructuredList->hasArrayFiller())
ExistingInit = StructuredList->getArrayFiller();
if (!ExistingInit)
StructuredList =
getStructuredSubobjectInit(IList, Index, CurrentObjectType,
StructuredList, StructuredIndex,
SourceRange(D->getLocStart(),
DIE->getLocEnd()));
else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
StructuredList = Result;
else {
if (DesignatedInitUpdateExpr *E =
dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
StructuredList = E->getUpdater();
else {
DesignatedInitUpdateExpr *DIUE =
new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
D->getLocStart(), ExistingInit,
DIE->getLocEnd());
StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
StructuredList = DIUE->getUpdater();
}
// We need to check on source range validity because the previous
// initializer does not have to be an explicit initializer. e.g.,
//
// struct P { int a, b; };
// struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
//
// There is an overwrite taking place because the first braced initializer
// list "{ .a = 2 }" already provides value for .p.b (which is zero).
if (ExistingInit->getSourceRange().isValid()) {
// We are creating an initializer list that initializes the
// subobjects of the current object, but there was already an
// initialization that completely initialized the current
// subobject, e.g., by a compound literal:
//
// struct X { int a, b; };
// struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
//
// Here, xs[0].a == 0 and xs[0].b == 3, since the second,
// designated initializer re-initializes the whole
// subobject [0], overwriting previous initializers.
SemaRef.Diag(D->getLocStart(),
diag::warn_subobject_initializer_overrides)
<< SourceRange(D->getLocStart(), DIE->getLocEnd());
SemaRef.Diag(ExistingInit->getLocStart(),
diag::note_previous_initializer)
<< /*FIXME:has side effects=*/0
<< ExistingInit->getSourceRange();
}
}
}
assert(StructuredList && "Expected a structured initializer list");
}
if (D->isFieldDesignator()) {
// C99 6.7.8p7:
//
// If a designator has the form
//
// . identifier
//
// then the current object (defined below) shall have
// structure or union type and the identifier shall be the
// name of a member of that type.
const RecordType *RT = CurrentObjectType->getAs<RecordType>();
if (!RT) {
SourceLocation Loc = D->getDotLoc();
if (Loc.isInvalid())
Loc = D->getFieldLoc();
if (!VerifyOnly)
SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
<< SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
++Index;
return true;
}
FieldDecl *KnownField = D->getField();
if (!KnownField) {
IdentifierInfo *FieldName = D->getFieldName();
DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
for (NamedDecl *ND : Lookup) {
if (auto *FD = dyn_cast<FieldDecl>(ND)) {
KnownField = FD;
break;
}
if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
// In verify mode, don't modify the original.
if (VerifyOnly)
DIE = CloneDesignatedInitExpr(SemaRef, DIE);
ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
D = DIE->getDesignator(DesigIdx);
KnownField = cast<FieldDecl>(*IFD->chain_begin());
break;
}
}
if (!KnownField) {
if (VerifyOnly) {
++Index;
return true; // No typo correction when just trying this out.
}
// Name lookup found something, but it wasn't a field.
if (!Lookup.empty()) {
SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
<< FieldName;
SemaRef.Diag(Lookup.front()->getLocation(),
diag::note_field_designator_found);
++Index;
return true;
}
// Name lookup didn't find anything.
// Determine whether this was a typo for another field name.
if (TypoCorrection Corrected = SemaRef.CorrectTypo(
DeclarationNameInfo(FieldName, D->getFieldLoc()),
Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
Sema::CTK_ErrorRecovery, RT->getDecl())) {
SemaRef.diagnoseTypo(
Corrected,
SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
<< FieldName << CurrentObjectType);
KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
hadError = true;
} else {
// Typo correction didn't find anything.
SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
<< FieldName << CurrentObjectType;
++Index;
return true;
}
}
}
unsigned FieldIndex = 0;
for (auto *FI : RT->getDecl()->fields()) {
if (FI->isUnnamedBitfield())
continue;
if (KnownField == FI)
break;
++FieldIndex;
}
RecordDecl::field_iterator Field =
RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
// All of the fields of a union are located at the same place in
// the initializer list.
if (RT->getDecl()->isUnion()) {
FieldIndex = 0;
if (!VerifyOnly) {
FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
if (CurrentField && CurrentField != *Field) {
assert(StructuredList->getNumInits() == 1
&& "A union should never have more than one initializer!");
// we're about to throw away an initializer, emit warning
SemaRef.Diag(D->getFieldLoc(),
diag::warn_initializer_overrides)
<< D->getSourceRange();
Expr *ExistingInit = StructuredList->getInit(0);
SemaRef.Diag(ExistingInit->getLocStart(),
diag::note_previous_initializer)
<< /*FIXME:has side effects=*/0
<< ExistingInit->getSourceRange();
// remove existing initializer
StructuredList->resizeInits(SemaRef.Context, 0);
StructuredList->setInitializedFieldInUnion(nullptr);
}
StructuredList->setInitializedFieldInUnion(*Field);
}
}
// Make sure we can use this declaration.
bool InvalidUse;
if (VerifyOnly)
InvalidUse = !SemaRef.CanUseDecl(*Field);
else
InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
if (InvalidUse) {
++Index;
return true;
}
if (!VerifyOnly) {
// Update the designator with the field declaration.
D->setField(*Field);
// Make sure that our non-designated initializer list has space
// for a subobject corresponding to this field.
if (FieldIndex >= StructuredList->getNumInits())
StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
}
// This designator names a flexible array member.
if (Field->getType()->isIncompleteArrayType()) {
bool Invalid = false;
if ((DesigIdx + 1) != DIE->size()) {
// We can't designate an object within the flexible array
// member (because GCC doesn't allow it).
if (!VerifyOnly) {
DesignatedInitExpr::Designator *NextD
= DIE->getDesignator(DesigIdx + 1);
SemaRef.Diag(NextD->getLocStart(),
diag::err_designator_into_flexible_array_member)
<< SourceRange(NextD->getLocStart(),
DIE->getLocEnd());
SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
<< *Field;
}
Invalid = true;
}
if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
!isa<StringLiteral>(DIE->getInit())) {
// The initializer is not an initializer list.
if (!VerifyOnly) {
SemaRef.Diag(DIE->getInit()->getLocStart(),
diag::err_flexible_array_init_needs_braces)
<< DIE->getInit()->getSourceRange();
SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
<< *Field;
}
Invalid = true;
}
// Check GNU flexible array initializer.
if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
TopLevelObject))
Invalid = true;
if (Invalid) {
++Index;
return true;
}
// Initialize the array.
bool prevHadError = hadError;
unsigned newStructuredIndex = FieldIndex;
unsigned OldIndex = Index;
IList->setInit(Index, DIE->getInit());
InitializedEntity MemberEntity =
InitializedEntity::InitializeMember(*Field, &Entity);
CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
StructuredList, newStructuredIndex);
IList->setInit(OldIndex, DIE);
if (hadError && !prevHadError) {
++Field;
++FieldIndex;
if (NextField)
*NextField = Field;
StructuredIndex = FieldIndex;
return true;
}
} else {
// Recurse to check later designated subobjects.
QualType FieldType = Field->getType();
unsigned newStructuredIndex = FieldIndex;
InitializedEntity MemberEntity =
InitializedEntity::InitializeMember(*Field, &Entity);
if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
FieldType, nullptr, nullptr, Index,
StructuredList, newStructuredIndex,
true, false))
return true;
}
// Find the position of the next field to be initialized in this
// subobject.
++Field;
++FieldIndex;
// If this the first designator, our caller will continue checking
// the rest of this struct/class/union subobject.
if (IsFirstDesignator) {
if (NextField)
*NextField = Field;
StructuredIndex = FieldIndex;
return false;
}
if (!FinishSubobjectInit)
return false;
// We've already initialized something in the union; we're done.
if (RT->getDecl()->isUnion())
return hadError;
// Check the remaining fields within this class/struct/union subobject.
bool prevHadError = hadError;
CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
StructuredList, FieldIndex);
return hadError && !prevHadError;
}
// C99 6.7.8p6:
//
// If a designator has the form
//
// [ constant-expression ]
//
// then the current object (defined below) shall have array
// type and the expression shall be an integer constant
// expression. If the array is of unknown size, any
// nonnegative value is valid.
//
// Additionally, cope with the GNU extension that permits
// designators of the form
//
// [ constant-expression ... constant-expression ]
const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
if (!AT) {
if (!VerifyOnly)
SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
<< CurrentObjectType;
++Index;
return true;
}
Expr *IndexExpr = nullptr;
llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
if (D->isArrayDesignator()) {
IndexExpr = DIE->getArrayIndex(*D);
DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
DesignatedEndIndex = DesignatedStartIndex;
} else {
assert(D->isArrayRangeDesignator() && "Need array-range designator");
DesignatedStartIndex =
DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
DesignatedEndIndex =
DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
IndexExpr = DIE->getArrayRangeEnd(*D);
// Codegen can't handle evaluating array range designators that have side
// effects, because we replicate the AST value for each initialized element.
// As such, set the sawArrayRangeDesignator() bit if we initialize multiple
// elements with something that has a side effect, so codegen can emit an
// "error unsupported" error instead of miscompiling the app.
if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
FullyStructuredList->sawArrayRangeDesignator();
}
if (isa<ConstantArrayType>(AT)) {
llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
DesignatedStartIndex
= DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
DesignatedEndIndex
= DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
if (DesignatedEndIndex >= MaxElements) {
if (!VerifyOnly)
SemaRef.Diag(IndexExpr->getLocStart(),
diag::err_array_designator_too_large)
<< DesignatedEndIndex.toString(10) << MaxElements.toString(10)
<< IndexExpr->getSourceRange();
++Index;
return true;
}
} else {
unsigned DesignatedIndexBitWidth =
ConstantArrayType::getMaxSizeBits(SemaRef.Context);
DesignatedStartIndex =
DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
DesignatedEndIndex =
DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
DesignatedStartIndex.setIsUnsigned(true);
DesignatedEndIndex.setIsUnsigned(true);
}
if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
// We're modifying a string literal init; we have to decompose the string
// so we can modify the individual characters.
ASTContext &Context = SemaRef.Context;
Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
// Compute the character type
QualType CharTy = AT->getElementType();
// Compute the type of the integer literals.
QualType PromotedCharTy = CharTy;
if (CharTy->isPromotableIntegerType())
PromotedCharTy = Context.getPromotedIntegerType(CharTy);
unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
// Get the length of the string.
uint64_t StrLen = SL->getLength();
if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
StructuredList->resizeInits(Context, StrLen);
// Build a literal for each character in the string, and put them into
// the init list.
for (unsigned i = 0, e = StrLen; i != e; ++i) {
llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
Expr *Init = new (Context) IntegerLiteral(
Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
if (CharTy != PromotedCharTy)
Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Init, nullptr, VK_RValue);
StructuredList->updateInit(Context, i, Init);
}
} else {
ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
std::string Str;
Context.getObjCEncodingForType(E->getEncodedType(), Str);
// Get the length of the string.
uint64_t StrLen = Str.size();
if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
StructuredList->resizeInits(Context, StrLen);
// Build a literal for each character in the string, and put them into
// the init list.
for (unsigned i = 0, e = StrLen; i != e; ++i) {
llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
Expr *Init = new (Context) IntegerLiteral(
Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
if (CharTy != PromotedCharTy)
Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Init, nullptr, VK_RValue);
StructuredList->updateInit(Context, i, Init);
}
}
}
// Make sure that our non-designated initializer list has space
// for a subobject corresponding to this array element.
if (!VerifyOnly &&
DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
StructuredList->resizeInits(SemaRef.Context,
DesignatedEndIndex.getZExtValue() + 1);
// Repeatedly perform subobject initializations in the range
// [DesignatedStartIndex, DesignatedEndIndex].
// Move to the next designator
unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
unsigned OldIndex = Index;
InitializedEntity ElementEntity =
InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
while (DesignatedStartIndex <= DesignatedEndIndex) {
// Recurse to check later designated subobjects.
QualType ElementType = AT->getElementType();
Index = OldIndex;
ElementEntity.setElementIndex(ElementIndex);
if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
ElementType, nullptr, nullptr, Index,
StructuredList, ElementIndex,
(DesignatedStartIndex == DesignatedEndIndex),
false))
return true;
// Move to the next index in the array that we'll be initializing.
++DesignatedStartIndex;
ElementIndex = DesignatedStartIndex.getZExtValue();
}
// If this the first designator, our caller will continue checking
// the rest of this array subobject.
if (IsFirstDesignator) {
if (NextElementIndex)
*NextElementIndex = DesignatedStartIndex;
StructuredIndex = ElementIndex;
return false;
}
if (!FinishSubobjectInit)
return false;
// Check the remaining elements within this array subobject.
bool prevHadError = hadError;
CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
/*SubobjectIsDesignatorContext=*/false, Index,
StructuredList, ElementIndex);
return hadError && !prevHadError;
}
// Get the structured initializer list for a subobject of type
// @p CurrentObjectType.
InitListExpr *
InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
QualType CurrentObjectType,
InitListExpr *StructuredList,
unsigned StructuredIndex,
SourceRange InitRange,
bool IsFullyOverwritten) {
if (VerifyOnly)
return nullptr; // No structured list in verification-only mode.
Expr *ExistingInit = nullptr;
if (!StructuredList)
ExistingInit = SyntacticToSemantic.lookup(IList);
else if (StructuredIndex < StructuredList->getNumInits())
ExistingInit = StructuredList->getInit(StructuredIndex);
if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
// There might have already been initializers for subobjects of the current
// object, but a subsequent initializer list will overwrite the entirety
// of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
//
// struct P { char x[6]; };
// struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
//
// The first designated initializer is ignored, and l.x is just "f".
if (!IsFullyOverwritten)
return Result;
if (ExistingInit) {
// We are creating an initializer list that initializes the
// subobjects of the current object, but there was already an
// initialization that completely initialized the current
// subobject, e.g., by a compound literal:
//
// struct X { int a, b; };
// struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
//
// Here, xs[0].a == 0 and xs[0].b == 3, since the second,
// designated initializer re-initializes the whole
// subobject [0], overwriting previous initializers.
SemaRef.Diag(InitRange.getBegin(),
diag::warn_subobject_initializer_overrides)
<< InitRange;
SemaRef.Diag(ExistingInit->getLocStart(),
diag::note_previous_initializer)
<< /*FIXME:has side effects=*/0
<< ExistingInit->getSourceRange();
}
InitListExpr *Result
= new (SemaRef.Context) InitListExpr(SemaRef.Context,
InitRange.getBegin(), None,
InitRange.getEnd());
QualType ResultType = CurrentObjectType;
if (!ResultType->isArrayType())
ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
Result->setType(ResultType);
// Pre-allocate storage for the structured initializer list.
unsigned NumElements = 0;
unsigned NumInits = 0;
bool GotNumInits = false;
if (!StructuredList) {
NumInits = IList->getNumInits();
GotNumInits = true;
} else if (Index < IList->getNumInits()) {
if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
NumInits = SubList->getNumInits();
GotNumInits = true;
}
}
if (const ArrayType *AType
= SemaRef.Context.getAsArrayType(CurrentObjectType)) {
if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
NumElements = CAType->getSize().getZExtValue();
// Simple heuristic so that we don't allocate a very large
// initializer with many empty entries at the end.
if (GotNumInits && NumElements > NumInits)
NumElements = 0;
}
} else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
NumElements = VType->getNumElements();
else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
RecordDecl *RDecl = RType->getDecl();
if (RDecl->isUnion())
NumElements = 1;
else
NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
}
Result->reserveInits(SemaRef.Context, NumElements);
// Link this new initializer list into the structured initializer
// lists.
if (StructuredList)
StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
else {
Result->setSyntacticForm(IList);
SyntacticToSemantic[IList] = Result;
}
return Result;
}
/// Update the initializer at index @p StructuredIndex within the
/// structured initializer list to the value @p expr.
void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
unsigned &StructuredIndex,
Expr *expr) {
// No structured initializer list to update
if (!StructuredList)
return;
if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
StructuredIndex, expr)) {
// This initializer overwrites a previous initializer. Warn.
// We need to check on source range validity because the previous
// initializer does not have to be an explicit initializer.
// struct P { int a, b; };
// struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
// There is an overwrite taking place because the first braced initializer
// list "{ .a = 2 }' already provides value for .p.b (which is zero).
if (PrevInit->getSourceRange().isValid()) {
SemaRef.Diag(expr->getLocStart(),
diag::warn_initializer_overrides)
<< expr->getSourceRange();
SemaRef.Diag(PrevInit->getLocStart(),
diag::note_previous_initializer)
<< /*FIXME:has side effects=*/0
<< PrevInit->getSourceRange();
}
}
++StructuredIndex;
}
/// Check that the given Index expression is a valid array designator
/// value. This is essentially just a wrapper around
/// VerifyIntegerConstantExpression that also checks for negative values
/// and produces a reasonable diagnostic if there is a
/// failure. Returns the index expression, possibly with an implicit cast
/// added, on success. If everything went okay, Value will receive the
/// value of the constant expression.
static ExprResult
CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
SourceLocation Loc = Index->getLocStart();
// Make sure this is an integer constant expression.
ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
if (Result.isInvalid())
return Result;
if (Value.isSigned() && Value.isNegative())
return S.Diag(Loc, diag::err_array_designator_negative)
<< Value.toString(10) << Index->getSourceRange();
Value.setIsUnsigned(true);
return Result;
}
ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
SourceLocation Loc,
bool GNUSyntax,
ExprResult Init) {
typedef DesignatedInitExpr::Designator ASTDesignator;
bool Invalid = false;
SmallVector<ASTDesignator, 32> Designators;
SmallVector<Expr *, 32> InitExpressions;
// Build designators and check array designator expressions.
for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
const Designator &D = Desig.getDesignator(Idx);
switch (D.getKind()) {
case Designator::FieldDesignator:
Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
D.getFieldLoc()));
break;
case Designator::ArrayDesignator: {
Expr *Index = static_cast<Expr *>(D.getArrayIndex());
llvm::APSInt IndexValue;
if (!Index->isTypeDependent() && !Index->isValueDependent())
Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
if (!Index)
Invalid = true;
else {
Designators.push_back(ASTDesignator(InitExpressions.size(),
D.getLBracketLoc(),
D.getRBracketLoc()));
InitExpressions.push_back(Index);
}
break;
}
case Designator::ArrayRangeDesignator: {
Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
llvm::APSInt StartValue;
llvm::APSInt EndValue;
bool StartDependent = StartIndex->isTypeDependent() ||
StartIndex->isValueDependent();
bool EndDependent = EndIndex->isTypeDependent() ||
EndIndex->isValueDependent();
if (!StartDependent)
StartIndex =
CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
if (!EndDependent)
EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
if (!StartIndex || !EndIndex)
Invalid = true;
else {
// Make sure we're comparing values with the same bit width.
if (StartDependent || EndDependent) {
// Nothing to compute.
} else if (StartValue.getBitWidth() > EndValue.getBitWidth())
EndValue = EndValue.extend(StartValue.getBitWidth());
else if (StartValue.getBitWidth() < EndValue.getBitWidth())
StartValue = StartValue.extend(EndValue.getBitWidth());
if (!StartDependent && !EndDependent && EndValue < StartValue) {
Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
<< StartValue.toString(10) << EndValue.toString(10)
<< StartIndex->getSourceRange() << EndIndex->getSourceRange();
Invalid = true;
} else {
Designators.push_back(ASTDesignator(InitExpressions.size(),
D.getLBracketLoc(),
D.getEllipsisLoc(),
D.getRBracketLoc()));
InitExpressions.push_back(StartIndex);
InitExpressions.push_back(EndIndex);
}
}
break;
}
}
}
if (Invalid || Init.isInvalid())
return ExprError();
// Clear out the expressions within the designation.
Desig.ClearExprs(*this);
DesignatedInitExpr *DIE
= DesignatedInitExpr::Create(Context,
Designators.data(), Designators.size(),
InitExpressions, Loc, GNUSyntax,
Init.getAs<Expr>());
if (!getLangOpts().C99)
Diag(DIE->getLocStart(), diag::ext_designated_init)
<< DIE->getSourceRange();
return DIE;
}
//===----------------------------------------------------------------------===//
// Initialization entity
//===----------------------------------------------------------------------===//
InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
const InitializedEntity &Parent)
: Parent(&Parent), Index(Index)
{
if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
Kind = EK_ArrayElement;
Type = AT->getElementType();
} else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Kind = EK_VectorElement;
Type = VT->getElementType();
} else {
const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
assert(CT && "Unexpected type");
Kind = EK_ComplexElement;
Type = CT->getElementType();
}
}
InitializedEntity
InitializedEntity::InitializeBase(ASTContext &Context,
const CXXBaseSpecifier *Base,
bool IsInheritedVirtualBase) {
InitializedEntity Result;
Result.Kind = EK_Base;
Result.Parent = nullptr;
Result.Base = reinterpret_cast<uintptr_t>(Base);
if (IsInheritedVirtualBase)
Result.Base |= 0x01;
Result.Type = Base->getType();
return Result;
}
DeclarationName InitializedEntity::getName() const {
switch (getKind()) {
case EK_Parameter:
case EK_Parameter_CF_Audited: {
ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
return (D ? D->getDeclName() : DeclarationName());
}
case EK_Variable:
case EK_Member:
return VariableOrMember->getDeclName();
case EK_LambdaCapture:
return DeclarationName(Capture.VarID);
case EK_Result:
case EK_Exception:
case EK_New:
case EK_Temporary:
case EK_Base:
case EK_Delegating:
case EK_ArrayElement:
case EK_VectorElement:
case EK_ComplexElement:
case EK_BlockElement:
case EK_CompoundLiteralInit:
case EK_RelatedResult:
return DeclarationName();
}
llvm_unreachable("Invalid EntityKind!");
}
DeclaratorDecl *InitializedEntity::getDecl() const {
switch (getKind()) {
case EK_Variable:
case EK_Member:
return VariableOrMember;
case EK_Parameter:
case EK_Parameter_CF_Audited:
return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
case EK_Result:
case EK_Exception:
case EK_New:
case EK_Temporary:
case EK_Base:
case EK_Delegating:
case EK_ArrayElement:
case EK_VectorElement:
case EK_ComplexElement:
case EK_BlockElement:
case EK_LambdaCapture:
case EK_CompoundLiteralInit:
case EK_RelatedResult:
return nullptr;
}
llvm_unreachable("Invalid EntityKind!");
}
bool InitializedEntity::allowsNRVO() const {
switch (getKind()) {
case EK_Result:
case EK_Exception:
return LocAndNRVO.NRVO;
case EK_Variable:
case EK_Parameter:
case EK_Parameter_CF_Audited:
case EK_Member:
case EK_New:
case EK_Temporary:
case EK_CompoundLiteralInit:
case EK_Base:
case EK_Delegating:
case EK_ArrayElement:
case EK_VectorElement:
case EK_ComplexElement:
case EK_BlockElement:
case EK_LambdaCapture:
case EK_RelatedResult:
break;
}
return false;
}
unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
assert(getParent() != this);
unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
for (unsigned I = 0; I != Depth; ++I)
OS << "`-";
switch (getKind()) {
case EK_Variable: OS << "Variable"; break;
case EK_Parameter: OS << "Parameter"; break;
case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
break;
case EK_Result: OS << "Result"; break;
case EK_Exception: OS << "Exception"; break;
case EK_Member: OS << "Member"; break;
case EK_New: OS << "New"; break;
case EK_Temporary: OS << "Temporary"; break;
case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
case EK_RelatedResult: OS << "RelatedResult"; break;
case EK_Base: OS << "Base"; break;
case EK_Delegating: OS << "Delegating"; break;
case EK_ArrayElement: OS << "ArrayElement " << Index; break;
case EK_VectorElement: OS << "VectorElement " << Index; break;
case EK_ComplexElement: OS << "ComplexElement " << Index; break;
case EK_BlockElement: OS << "Block"; break;
case EK_LambdaCapture:
OS << "LambdaCapture ";
OS << DeclarationName(Capture.VarID);
break;
}
if (Decl *D = getDecl()) {
OS << " ";
cast<NamedDecl>(D)->printQualifiedName(OS);
}
OS << " '" << getType().getAsString() << "'\n";
return Depth + 1;
}
void InitializedEntity::dump() const {
dumpImpl(llvm::errs());
}
//===----------------------------------------------------------------------===//
// Initialization sequence
//===----------------------------------------------------------------------===//
void InitializationSequence::Step::Destroy() {
switch (Kind) {
case SK_ResolveAddressOfOverloadedFunction:
case SK_CastDerivedToBaseRValue:
case SK_CastDerivedToBaseXValue:
case SK_CastDerivedToBaseLValue:
case SK_BindReference:
case SK_BindReferenceToTemporary:
case SK_ExtraneousCopyToTemporary:
case SK_UserConversion:
case SK_QualificationConversionRValue:
case SK_QualificationConversionXValue:
case SK_QualificationConversionLValue:
case SK_AtomicConversion:
case SK_LValueToRValue:
case SK_ListInitialization:
case SK_UnwrapInitList:
case SK_RewrapInitList:
case SK_ConstructorInitialization:
case SK_ConstructorInitializationFromList:
case SK_ZeroInitialization:
case SK_CAssignment:
case SK_StringInit:
case SK_ObjCObjectConversion:
case SK_ArrayInit:
case SK_ParenthesizedArrayInit:
case SK_PassByIndirectCopyRestore:
case SK_PassByIndirectRestore:
case SK_ProduceObjCObject:
case SK_StdInitializerList:
case SK_StdInitializerListConstructorCall:
case SK_OCLSamplerInit:
case SK_OCLZeroEvent:
break;
case SK_ConversionSequence:
case SK_ConversionSequenceNoNarrowing:
delete ICS;
}
}
bool InitializationSequence::isDirectReferenceBinding() const {
return !Steps.empty() && Steps.back().Kind == SK_BindReference;
}
bool InitializationSequence::isAmbiguous() const {
if (!Failed())
return false;
switch (getFailureKind()) {
case FK_TooManyInitsForReference:
case FK_ArrayNeedsInitList:
case FK_ArrayNeedsInitListOrStringLiteral:
case FK_ArrayNeedsInitListOrWideStringLiteral:
case FK_NarrowStringIntoWideCharArray:
case FK_WideStringIntoCharArray:
case FK_IncompatWideStringIntoWideChar:
case FK_AddressOfOverloadFailed: // FIXME: Could do better
case FK_NonConstLValueReferenceBindingToTemporary:
case FK_NonConstLValueReferenceBindingToUnrelated:
case FK_RValueReferenceBindingToLValue:
case FK_ReferenceInitDropsQualifiers:
case FK_ReferenceInitFailed:
case FK_ConversionFailed:
case FK_ConversionFromPropertyFailed:
case FK_TooManyInitsForScalar:
case FK_ReferenceBindingToInitList:
case FK_InitListBadDestinationType:
case FK_DefaultInitOfConst:
case FK_Incomplete:
case FK_ArrayTypeMismatch:
case FK_NonConstantArrayInit:
case FK_ListInitializationFailed:
case FK_VariableLengthArrayHasInitializer:
case FK_PlaceholderType:
case FK_ExplicitConstructor:
return false;
case FK_ReferenceInitOverloadFailed:
case FK_UserConversionOverloadFailed:
case FK_ConstructorOverloadFailed:
case FK_ListConstructorOverloadFailed:
return FailedOverloadResult == OR_Ambiguous;
}
llvm_unreachable("Invalid EntityKind!");
}
bool InitializationSequence::isConstructorInitialization() const {
return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
}
void
InitializationSequence
::AddAddressOverloadResolutionStep(FunctionDecl *Function,
DeclAccessPair Found,
bool HadMultipleCandidates) {
Step S;
S.Kind = SK_ResolveAddressOfOverloadedFunction;
S.Type = Function->getType();
S.Function.HadMultipleCandidates = HadMultipleCandidates;
S.Function.Function = Function;
S.Function.FoundDecl = Found;
Steps.push_back(S);
}
void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
ExprValueKind VK) {
Step S;
switch (VK) {
case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
}
S.Type = BaseType;
Steps.push_back(S);
}
void InitializationSequence::AddReferenceBindingStep(QualType T,
bool BindingTemporary) {
Step S;
S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
Step S;
S.Kind = SK_ExtraneousCopyToTemporary;
S.Type = T;
Steps.push_back(S);
}
void
InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
DeclAccessPair FoundDecl,
QualType T,
bool HadMultipleCandidates) {
Step S;
S.Kind = SK_UserConversion;
S.Type = T;
S.Function.HadMultipleCandidates = HadMultipleCandidates;
S.Function.Function = Function;
S.Function.FoundDecl = FoundDecl;
Steps.push_back(S);
}
void InitializationSequence::AddQualificationConversionStep(QualType Ty,
ExprValueKind VK) {
Step S;
S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
switch (VK) {
case VK_RValue:
S.Kind = SK_QualificationConversionRValue;
break;
case VK_XValue:
S.Kind = SK_QualificationConversionXValue;
break;
case VK_LValue:
S.Kind = SK_QualificationConversionLValue;
break;
}
S.Type = Ty;
Steps.push_back(S);
}
void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
Step S;
S.Kind = SK_AtomicConversion;
S.Type = Ty;
Steps.push_back(S);
}
void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
Step S;
S.Kind = SK_LValueToRValue;
S.Type = Ty;
Steps.push_back(S);
}
void InitializationSequence::AddConversionSequenceStep(
const ImplicitConversionSequence &ICS, QualType T,
bool TopLevelOfInitList) {
Step S;
S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
: SK_ConversionSequence;
S.Type = T;
S.ICS = new ImplicitConversionSequence(ICS);
Steps.push_back(S);
}
void InitializationSequence::AddListInitializationStep(QualType T) {
Step S;
S.Kind = SK_ListInitialization;
S.Type = T;
Steps.push_back(S);
}
void
InitializationSequence
::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
AccessSpecifier Access,
QualType T,
bool HadMultipleCandidates,
bool FromInitList, bool AsInitList) {
Step S;
S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
: SK_ConstructorInitializationFromList
: SK_ConstructorInitialization;
S.Type = T;
S.Function.HadMultipleCandidates = HadMultipleCandidates;
S.Function.Function = Constructor;
S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Steps.push_back(S);
}
void InitializationSequence::AddZeroInitializationStep(QualType T) {
Step S;
S.Kind = SK_ZeroInitialization;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddCAssignmentStep(QualType T) {
Step S;
S.Kind = SK_CAssignment;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddStringInitStep(QualType T) {
Step S;
S.Kind = SK_StringInit;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
Step S;
S.Kind = SK_ObjCObjectConversion;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddArrayInitStep(QualType T) {
Step S;
S.Kind = SK_ArrayInit;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
Step S;
S.Kind = SK_ParenthesizedArrayInit;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
bool shouldCopy) {
Step s;
s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
: SK_PassByIndirectRestore);
s.Type = type;
Steps.push_back(s);
}
void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
Step S;
S.Kind = SK_ProduceObjCObject;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
Step S;
S.Kind = SK_StdInitializerList;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
Step S;
S.Kind = SK_OCLSamplerInit;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::AddOCLZeroEventStep(QualType T) {
Step S;
S.Kind = SK_OCLZeroEvent;
S.Type = T;
Steps.push_back(S);
}
void InitializationSequence::RewrapReferenceInitList(QualType T,
InitListExpr *Syntactic) {
assert(Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.");
Step S;
S.Kind = SK_UnwrapInitList;
S.Type = Syntactic->getInit(0)->getType();
Steps.insert(Steps.begin(), S);
S.Kind = SK_RewrapInitList;
S.Type = T;
S.WrappingSyntacticList = Syntactic;
Steps.push_back(S);
}
void InitializationSequence::SetOverloadFailure(FailureKind Failure,
OverloadingResult Result) {
setSequenceKind(FailedSequence);
this->Failure = Failure;
this->FailedOverloadResult = Result;
}
//===----------------------------------------------------------------------===//
// Attempt initialization
//===----------------------------------------------------------------------===//
/// Tries to add a zero initializer. Returns true if that worked.
static bool
maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
const InitializedEntity &Entity) {
if (Entity.getKind() != InitializedEntity::EK_Variable)
return false;
VarDecl *VD = cast<VarDecl>(Entity.getDecl());
if (VD->getInit() || VD->getLocEnd().isMacroID())
return false;
QualType VariableTy = VD->getType().getCanonicalType();
SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
if (!Init.empty()) {
Sequence.AddZeroInitializationStep(Entity.getType());
Sequence.SetZeroInitializationFixit(Init, Loc);
return true;
}
return false;
}
static void MaybeProduceObjCObject(Sema &S,
InitializationSequence &Sequence,
const InitializedEntity &Entity) {
if (!S.getLangOpts().ObjCAutoRefCount) return;
/// When initializing a parameter, produce the value if it's marked
/// __attribute__((ns_consumed)).
if (Entity.isParameterKind()) {
if (!Entity.isParameterConsumed())
return;
assert(Entity.getType()->isObjCRetainableType() &&
"consuming an object of unretainable type?");
Sequence.AddProduceObjCObjectStep(Entity.getType());
/// When initializing a return value, if the return type is a
/// retainable type, then returns need to immediately retain the
/// object. If an autorelease is required, it will be done at the
/// last instant.
} else if (Entity.getKind() == InitializedEntity::EK_Result) {
if (!Entity.getType()->isObjCRetainableType())
return;
Sequence.AddProduceObjCObjectStep(Entity.getType());
}
}
static void TryListInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
InitListExpr *InitList,
InitializationSequence &Sequence);
/// \brief When initializing from init list via constructor, handle
/// initialization of an object of type std::initializer_list<T>.
///
/// \return true if we have handled initialization of an object of type
/// std::initializer_list<T>, false otherwise.
static bool TryInitializerListConstruction(Sema &S,
InitListExpr *List,
QualType DestType,
InitializationSequence &Sequence) {
QualType E;
if (!S.isStdInitializerList(DestType, &E))
return false;
if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
Sequence.setIncompleteTypeFailure(E);
return true;
}
// Try initializing a temporary array from the init list.
QualType ArrayType = S.Context.getConstantArrayType(
E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
List->getNumInits()),
clang::ArrayType::Normal, 0);
InitializedEntity HiddenArray =
InitializedEntity::InitializeTemporary(ArrayType);
InitializationKind Kind =
InitializationKind::CreateDirectList(List->getExprLoc());
TryListInitialization(S, HiddenArray, Kind, List, Sequence);
if (Sequence)
Sequence.AddStdInitializerListConstructionStep(DestType);
return true;
}
static OverloadingResult
ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
MultiExprArg Args,
OverloadCandidateSet &CandidateSet,
DeclContext::lookup_result Ctors,
OverloadCandidateSet::iterator &Best,
bool CopyInitializing, bool AllowExplicit,
bool OnlyListConstructors, bool IsListInit) {
CandidateSet.clear();
for (NamedDecl *D : Ctors) {
DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
bool SuppressUserConversions = false;
// Find the constructor (which may be a template).
CXXConstructorDecl *Constructor = nullptr;
FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
if (ConstructorTmpl)
Constructor = cast<CXXConstructorDecl>(
ConstructorTmpl->getTemplatedDecl());
else {
Constructor = cast<CXXConstructorDecl>(D);
// C++11 [over.best.ics]p4:
// ... and the constructor or user-defined conversion function is a
// candidate by
// - 13.3.1.3, when the argument is the temporary in the second step
// of a class copy-initialization, or
// - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
// user-defined conversion sequences are not considered.
// FIXME: This breaks backward compatibility, e.g. PR12117. As a
// temporary fix, let's re-instate the third bullet above until
// there is a resolution in the standard, i.e.,
// - 13.3.1.7 when the initializer list has exactly one element that is
// itself an initializer list and a conversion to some class X or
// reference to (possibly cv-qualified) X is considered for the first
// parameter of a constructor of X.
if ((CopyInitializing ||
(IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Constructor->isCopyOrMoveConstructor())
SuppressUserConversions = true;
}
if (!Constructor->isInvalidDecl() &&
(AllowExplicit || !Constructor->isExplicit()) &&
(!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
if (ConstructorTmpl)
S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
/*ExplicitArgs*/ nullptr, Args,
CandidateSet, SuppressUserConversions);
else {
// C++ [over.match.copy]p1:
// - When initializing a temporary to be bound to the first parameter
// of a constructor that takes a reference to possibly cv-qualified
// T as its first argument, called with a single argument in the
// context of direct-initialization, explicit conversion functions
// are also considered.
bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Args.size() == 1 &&
Constructor->isCopyOrMoveConstructor();
S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
SuppressUserConversions,
/*PartialOverloading=*/false,
/*AllowExplicit=*/AllowExplicitConv);
}
}
}
// Perform overload resolution and return the result.
return CandidateSet.BestViableFunction(S, DeclLoc, Best);
}
/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
/// enumerates the constructors of the initialized entity and performs overload
/// resolution to select the best.
/// \param IsListInit Is this list-initialization?
/// \param IsInitListCopy Is this non-list-initialization resulting from a
/// list-initialization from {x} where x is the same
/// type as the entity?
static void TryConstructorInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args, QualType DestType,
InitializationSequence &Sequence,
bool IsListInit = false,
bool IsInitListCopy = false) {
assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
"IsListInit must come with a single initializer list argument.");
// The type we're constructing needs to be complete.
if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Sequence.setIncompleteTypeFailure(DestType);
return;
}
const RecordType *DestRecordType = DestType->getAs<RecordType>();
assert(DestRecordType && "Constructor initialization requires record type");
CXXRecordDecl *DestRecordDecl
= cast<CXXRecordDecl>(DestRecordType->getDecl());
// Build the candidate set directly in the initialization sequence
// structure, so that it will persist if we fail.
OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
// Determine whether we are allowed to call explicit constructors or
// explicit conversion operators.
bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
// - Otherwise, if T is a class type, constructors are considered. The
// applicable constructors are enumerated, and the best one is chosen
// through overload resolution.
DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
OverloadingResult Result = OR_No_Viable_Function;
OverloadCandidateSet::iterator Best;
bool AsInitializerList = false;
// C++11 [over.match.list]p1, per DR1467:
// When objects of non-aggregate type T are list-initialized, such that
// 8.5.4 [dcl.init.list] specifies that overload resolution is performed
// according to the rules in this section, overload resolution selects
// the constructor in two phases:
//
// - Initially, the candidate functions are the initializer-list
// constructors of the class T and the argument list consists of the
// initializer list as a single argument.
if (IsListInit) {
InitListExpr *ILE = cast<InitListExpr>(Args[0]);
AsInitializerList = true;
// If the initializer list has no elements and T has a default constructor,
// the first phase is omitted.
if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
CandidateSet, Ctors, Best,
CopyInitialization, AllowExplicit,
/*OnlyListConstructor=*/true,
IsListInit);
// Time to unwrap the init list.
Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
}
// C++11 [over.match.list]p1:
// - If no viable initializer-list constructor is found, overload resolution
// is performed again, where the candidate functions are all the
// constructors of the class T and the argument list consists of the
// elements of the initializer list.
if (Result == OR_No_Viable_Function) {
AsInitializerList = false;
Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
CandidateSet, Ctors, Best,
CopyInitialization, AllowExplicit,
/*OnlyListConstructors=*/false,
IsListInit);
}
if (Result) {
Sequence.SetOverloadFailure(IsListInit ?
InitializationSequence::FK_ListConstructorOverloadFailed :
InitializationSequence::FK_ConstructorOverloadFailed,
Result);
return;
}
// C++11 [dcl.init]p6:
// If a program calls for the default initialization of an object
// of a const-qualified type T, T shall be a class type with a
// user-provided default constructor.
if (Kind.getKind() == InitializationKind::IK_Default &&
Entity.getType().isConstQualified() &&
!cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
return;
}
// C++11 [over.match.list]p1:
// In copy-list-initialization, if an explicit constructor is chosen, the
// initializer is ill-formed.
CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
return;
}
// Add the constructor initialization step. Any cv-qualification conversion is
// subsumed by the initialization.
bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sequence.AddConstructorInitializationStep(
CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
IsListInit | IsInitListCopy, AsInitializerList);
}
static bool
ResolveOverloadedFunctionForReferenceBinding(Sema &S,
Expr *Initializer,
QualType &SourceType,
QualType &UnqualifiedSourceType,
QualType UnqualifiedTargetType,
InitializationSequence &Sequence) {
if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
S.Context.OverloadTy) {
DeclAccessPair Found;
bool HadMultipleCandidates = false;
if (FunctionDecl *Fn
= S.ResolveAddressOfOverloadedFunction(Initializer,
UnqualifiedTargetType,
false, Found,
&HadMultipleCandidates)) {
Sequence.AddAddressOverloadResolutionStep(Fn, Found,
HadMultipleCandidates);
SourceType = Fn->getType();
UnqualifiedSourceType = SourceType.getUnqualifiedType();
} else if (!UnqualifiedTargetType->isRecordType()) {
Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
return true;
}
}
return false;
}
static void TryReferenceInitializationCore(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
Expr *Initializer,
QualType cv1T1, QualType T1,
Qualifiers T1Quals,
QualType cv2T2, QualType T2,
Qualifiers T2Quals,
InitializationSequence &Sequence);
static void TryValueInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
InitializationSequence &Sequence,
InitListExpr *InitList = nullptr);
/// \brief Attempt list initialization of a reference.
static void TryReferenceListInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
InitListExpr *InitList,
InitializationSequence &Sequence) {
// First, catch C++03 where this isn't possible.
if (!S.getLangOpts().CPlusPlus11) {
Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
return;
}
// Can't reference initialize a compound literal.
if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
return;
}
QualType DestType = Entity.getType();
QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Qualifiers T1Quals;
QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
// Reference initialization via an initializer list works thus:
// If the initializer list consists of a single element that is
// reference-related to the referenced type, bind directly to that element
// (possibly creating temporaries).
// Otherwise, initialize a temporary with the initializer list and
// bind to that.
if (InitList->getNumInits() == 1) {
Expr *Initializer = InitList->getInit(0);
QualType cv2T2 = Initializer->getType();
Qualifiers T2Quals;
QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
// If this fails, creating a temporary wouldn't work either.
if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
T1, Sequence))
return;
SourceLocation DeclLoc = Initializer->getLocStart();
bool dummy1, dummy2, dummy3;
Sema::ReferenceCompareResult RefRelationship
= S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
dummy2, dummy3);
if (RefRelationship >= Sema::Ref_Related) {
// Try to bind the reference here.
TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
T1Quals, cv2T2, T2, T2Quals, Sequence);
if (Sequence)
Sequence.RewrapReferenceInitList(cv1T1, InitList);
return;
}
// Update the initializer if we've resolved an overloaded function.
if (Sequence.step_begin() != Sequence.step_end())
Sequence.RewrapReferenceInitList(cv1T1, InitList);
}
// Not reference-related. Create a temporary and bind to that.
InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
if (Sequence) {
if (DestType->isRValueReferenceType() ||
(T1Quals.hasConst() && !T1Quals.hasVolatile()))
Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
else
Sequence.SetFailed(
InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
}
}
/// \brief Attempt list initialization (C++0x [dcl.init.list])
static void TryListInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
InitListExpr *InitList,
InitializationSequence &Sequence) {
QualType DestType = Entity.getType();
// C++ doesn't allow scalar initialization with more than one argument.
// But C99 complex numbers are scalars and it makes sense there.
if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
!DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
return;
}
if (DestType->isReferenceType()) {
TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
return;
}
if (DestType->isRecordType() &&
S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Sequence.setIncompleteTypeFailure(DestType);
return;
}
// C++11 [dcl.init.list]p3, per DR1467:
// - If T is a class type and the initializer list has a single element of
// type cv U, where U is T or a class derived from T, the object is
// initialized from that element (by copy-initialization for
// copy-list-initialization, or by direct-initialization for
// direct-list-initialization).
// - Otherwise, if T is a character array and the initializer list has a
// single element that is an appropriately-typed string literal
// (8.5.2 [dcl.init.string]), initialization is performed as described
// in that section.
// - Otherwise, if T is an aggregate, [...] (continue below).
if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
if (DestType->isRecordType()) {
QualType InitType = InitList->getInit(0)->getType();
if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
S.IsDerivedFrom(InitType, DestType)) {
Expr *InitAsExpr = InitList->getInit(0);
TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
Sequence, /*InitListSyntax*/ false,
/*IsInitListCopy*/ true);
return;
}
}
if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
Expr *SubInit[1] = {InitList->getInit(0)};
if (!isa<VariableArrayType>(DestAT) &&
IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
InitializationKind SubKind =
Kind.getKind() == InitializationKind::IK_DirectList
? InitializationKind::CreateDirect(Kind.getLocation(),
InitList->getLBraceLoc(),
InitList->getRBraceLoc())
: Kind;
Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
/*TopLevelOfInitList*/ true);
// TryStringLiteralInitialization() (in InitializeFrom()) will fail if
// the element is not an appropriately-typed string literal, in which
// case we should proceed as in C++11 (below).
if (Sequence) {
Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
return;
}
}
}
}
// C++11 [dcl.init.list]p3:
// - If T is an aggregate, aggregate initialization is performed.
if (DestType->isRecordType() && !DestType->isAggregateType()) {
if (S.getLangOpts().CPlusPlus11) {
// - Otherwise, if the initializer list has no elements and T is a
// class type with a default constructor, the object is
// value-initialized.
if (InitList->getNumInits() == 0) {
CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
if (RD->hasDefaultConstructor()) {
TryValueInitialization(S, Entity, Kind, Sequence, InitList);
return;
}
}
// - Otherwise, if T is a specialization of std::initializer_list<E>,
// an initializer_list object constructed [...]
if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
return;
// - Otherwise, if T is a class type, constructors are considered.
Expr *InitListAsExpr = InitList;
TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Sequence, /*InitListSyntax*/ true);
} else
Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
return;
}
if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
InitList->getNumInits() == 1 &&
InitList->getInit(0)->getType()->isRecordType()) {
// - Otherwise, if the initializer list has a single element of type E
// [...references are handled above...], the object or reference is
// initialized from that element (by copy-initialization for
// copy-list-initialization, or by direct-initialization for
// direct-list-initialization); if a narrowing conversion is required
// to convert the element to T, the program is ill-formed.
//
// Per core-24034, this is direct-initialization if we were performing
// direct-list-initialization and copy-initialization otherwise.
// We can't use InitListChecker for this, because it always performs
// copy-initialization. This only matters if we might use an 'explicit'
// conversion operator, so we only need to handle the cases where the source
// is of record type.
InitializationKind SubKind =
Kind.getKind() == InitializationKind::IK_DirectList
? InitializationKind::CreateDirect(Kind.getLocation(),
InitList->getLBraceLoc(),
InitList->getRBraceLoc())
: Kind;
Expr *SubInit[1] = { InitList->getInit(0) };
Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
/*TopLevelOfInitList*/true);
if (Sequence)
Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
return;
}
InitListChecker CheckInitList(S, Entity, Kind, InitList, // HLSL Change - add Kind
DestType, /*VerifyOnly=*/true);
if (CheckInitList.HadError()) {
Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
return;
}
// Add the list initialization step with the built init list.
Sequence.AddListInitializationStep(DestType);
}
/// \brief Try a reference initialization that involves calling a conversion
/// function.
static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
Expr *Initializer,
bool AllowRValues,
InitializationSequence &Sequence) {
QualType DestType = Entity.getType();
QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
QualType T1 = cv1T1.getUnqualifiedType();
QualType cv2T2 = Initializer->getType();
QualType T2 = cv2T2.getUnqualifiedType();
bool DerivedToBase;
bool ObjCConversion;
bool ObjCLifetimeConversion;
assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
T1, T2, DerivedToBase,
ObjCConversion,
ObjCLifetimeConversion) &&
"Must have incompatible references when binding via conversion");
(void)DerivedToBase;
(void)ObjCConversion;
(void)ObjCLifetimeConversion;
// Build the candidate set directly in the initialization sequence
// structure, so that it will persist if we fail.
OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
CandidateSet.clear();
// Determine whether we are allowed to call explicit constructors or
// explicit conversion operators.
bool AllowExplicit = Kind.AllowExplicit();
bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
const RecordType *T1RecordType = nullptr;
if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
!S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
// The type we're converting to is a class type. Enumerate its constructors
// to see if there is a suitable conversion.
CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
// Find the constructor (which may be a template).
CXXConstructorDecl *Constructor = nullptr;
FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
if (ConstructorTmpl)
Constructor = cast<CXXConstructorDecl>(
ConstructorTmpl->getTemplatedDecl());
else
Constructor = cast<CXXConstructorDecl>(D);
if (!Constructor->isInvalidDecl() &&
Constructor->isConvertingConstructor(AllowExplicit)) {
if (ConstructorTmpl)
S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
/*ExplicitArgs*/ nullptr,
Initializer, CandidateSet,
/*SuppressUserConversions=*/true);
else
S.AddOverloadCandidate(Constructor, FoundDecl,
Initializer, CandidateSet,
/*SuppressUserConversions=*/true);
}
}
}
if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
return OR_No_Viable_Function;
const RecordType *T2RecordType = nullptr;
if ((T2RecordType = T2->getAs<RecordType>()) &&
!S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
// The type we're converting from is a class type, enumerate its conversion
// functions.
CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
NamedDecl *D = *I;
CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
if (isa<UsingShadowDecl>(D))
D = cast<UsingShadowDecl>(D)->getTargetDecl();
FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
CXXConversionDecl *Conv;
if (ConvTemplate)
Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
else
Conv = cast<CXXConversionDecl>(D);
// If the conversion function doesn't return a reference type,
// it can't be considered for this conversion unless we're allowed to
// consider rvalues.
// FIXME: Do we need to make sure that we only consider conversion
// candidates with reference-compatible results? That might be needed to
// break recursion.
if ((AllowExplicitConvs || !Conv->isExplicit()) &&
(AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
if (ConvTemplate)
S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
ActingDC, Initializer,
DestType, CandidateSet,
/*AllowObjCConversionOnExplicit=*/
false);
else
S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Initializer, DestType, CandidateSet,
/*AllowObjCConversionOnExplicit=*/false);
}
}
}
if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
return OR_No_Viable_Function;
SourceLocation DeclLoc = Initializer->getLocStart();
// Perform overload resolution. If it fails, return the failed result.
OverloadCandidateSet::iterator Best;
if (OverloadingResult Result
= CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
return Result;
FunctionDecl *Function = Best->Function;
// This is the overload that will be used for this initialization step if we
// use this initialization. Mark it as referenced.
Function->setReferenced();
// Compute the returned type of the conversion.
if (isa<CXXConversionDecl>(Function))
T2 = Function->getReturnType();
else
T2 = cv1T1;
// Add the user-defined conversion step.
bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sequence.AddUserConversionStep(Function, Best->FoundDecl,
T2.getNonLValueExprType(S.Context),
HadMultipleCandidates);
// Determine whether we need to perform derived-to-base or
// cv-qualification adjustments.
ExprValueKind VK = VK_RValue;
if (T2->isLValueReferenceType())
VK = VK_LValue;
else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
bool NewDerivedToBase = false;
bool NewObjCConversion = false;
bool NewObjCLifetimeConversion = false;
Sema::ReferenceCompareResult NewRefRelationship
= S.CompareReferenceRelationship(DeclLoc, T1,
T2.getNonLValueExprType(S.Context),
NewDerivedToBase, NewObjCConversion,
NewObjCLifetimeConversion);
if (NewRefRelationship == Sema::Ref_Incompatible) {
// If the type we've converted to is not reference-related to the
// type we're looking for, then there is another conversion step
// we need to perform to produce a temporary of the right type
// that we'll be binding to.
ImplicitConversionSequence ICS;
ICS.setStandard();
ICS.Standard = Best->FinalConversion;
T2 = ICS.Standard.getToType(2);
Sequence.AddConversionSequenceStep(ICS, T2);
} else if (NewDerivedToBase)
Sequence.AddDerivedToBaseCastStep(
S.Context.getQualifiedType(T1,
T2.getNonReferenceType().getQualifiers()),
VK);
else if (NewObjCConversion)
Sequence.AddObjCObjectConversionStep(
S.Context.getQualifiedType(T1,
T2.getNonReferenceType().getQualifiers()));
if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
Sequence.AddQualificationConversionStep(cv1T1, VK);
Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
return OR_Success;
}
static void CheckCXX98CompatAccessibleCopy(Sema &S,
const InitializedEntity &Entity,
Expr *CurInitExpr);
/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
static void TryReferenceInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
Expr *Initializer,
InitializationSequence &Sequence) {
QualType DestType = Entity.getType();
QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Qualifiers T1Quals;
QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
QualType cv2T2 = Initializer->getType();
Qualifiers T2Quals;
QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
// If the initializer is the address of an overloaded function, try
// to resolve the overloaded function. If all goes well, T2 is the
// type of the resulting function.
if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
T1, Sequence))
return;
// Delegate everything else to a subfunction.
TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
T1Quals, cv2T2, T2, T2Quals, Sequence);
}
/// Converts the target of reference initialization so that it has the
/// appropriate qualifiers and value kind.
///
/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
/// \code
/// int x;
/// const int &r = x;
/// \endcode
///
/// In this case the reference is binding to a bitfield lvalue, which isn't
/// valid. Perform a load to create a lifetime-extended temporary instead.
/// \code
/// const int &r = someStruct.bitfield;
/// \endcode
static ExprValueKind
convertQualifiersAndValueKindIfNecessary(Sema &S,
InitializationSequence &Sequence,
Expr *Initializer,
QualType cv1T1,
Qualifiers T1Quals,
Qualifiers T2Quals,
bool IsLValueRef) {
bool IsNonAddressableType = Initializer->refersToBitField() ||
Initializer->refersToVectorElement();
if (IsNonAddressableType) {
// C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
// lvalue reference to a non-volatile const type, or the reference shall be
// an rvalue reference.
//
// If not, we can't make a temporary and bind to that. Give up and allow the
// error to be diagnosed later.
if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
assert(Initializer->isGLValue());
return Initializer->getValueKind();
}
// Force a load so we can materialize a temporary.
Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
return VK_RValue;
}
if (T1Quals != T2Quals) {
Sequence.AddQualificationConversionStep(cv1T1,
Initializer->getValueKind());
}
return Initializer->getValueKind();
}
/// \brief Reference initialization without resolving overloaded functions.
static void TryReferenceInitializationCore(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
Expr *Initializer,
QualType cv1T1, QualType T1,
Qualifiers T1Quals,
QualType cv2T2, QualType T2,
Qualifiers T2Quals,
InitializationSequence &Sequence) {
QualType DestType = Entity.getType();
SourceLocation DeclLoc = Initializer->getLocStart();
// Compute some basic properties of the types and the initializer.
bool isLValueRef = DestType->isLValueReferenceType();
bool isRValueRef = !isLValueRef;
bool DerivedToBase = false;
bool ObjCConversion = false;
bool ObjCLifetimeConversion = false;
Expr::Classification InitCategory = Initializer->Classify(S.Context);
Sema::ReferenceCompareResult RefRelationship
= S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
ObjCConversion, ObjCLifetimeConversion);
// C++0x [dcl.init.ref]p5:
// A reference to type "cv1 T1" is initialized by an expression of type
// "cv2 T2" as follows:
//
// - If the reference is an lvalue reference and the initializer
// expression
// Note the analogous bullet points for rvalue refs to functions. Because
// there are no function rvalues in C++, rvalue refs to functions are treated
// like lvalue refs.
OverloadingResult ConvOvlResult = OR_Success;
bool T1Function = T1->isFunctionType();
if (isLValueRef || T1Function) {
if (InitCategory.isLValue() &&
(RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
(Kind.isCStyleOrFunctionalCast() &&
RefRelationship == Sema::Ref_Related))) {
// - is an lvalue (but is not a bit-field), and "cv1 T1" is
// reference-compatible with "cv2 T2," or
//
// Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
// bit-field when we're determining whether the reference initialization
// can occur. However, we do pay attention to whether it is a bit-field
// to decide whether we're actually binding to a temporary created from
// the bit-field.
if (DerivedToBase)
Sequence.AddDerivedToBaseCastStep(
S.Context.getQualifiedType(T1, T2Quals),
VK_LValue);
else if (ObjCConversion)
Sequence.AddObjCObjectConversionStep(
S.Context.getQualifiedType(T1, T2Quals));
ExprValueKind ValueKind =
convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
cv1T1, T1Quals, T2Quals,
isLValueRef);
Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
return;
}
// - has a class type (i.e., T2 is a class type), where T1 is not
// reference-related to T2, and can be implicitly converted to an
// lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
// with "cv3 T3" (this conversion is selected by enumerating the
// applicable conversion functions (13.3.1.6) and choosing the best
// one through overload resolution (13.3)),
// If we have an rvalue ref to function type here, the rhs must be
// an rvalue. DR1287 removed the "implicitly" here.
if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
(isLValueRef || InitCategory.isRValue())) {
ConvOvlResult = TryRefInitWithConversionFunction(
S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
if (ConvOvlResult == OR_Success)
return;
if (ConvOvlResult != OR_No_Viable_Function)
Sequence.SetOverloadFailure(
InitializationSequence::FK_ReferenceInitOverloadFailed,
ConvOvlResult);
}
}
// - Otherwise, the reference shall be an lvalue reference to a
// non-volatile const type (i.e., cv1 shall be const), or the reference
// shall be an rvalue reference.
if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Sequence.SetOverloadFailure(
InitializationSequence::FK_ReferenceInitOverloadFailed,
ConvOvlResult);
else
Sequence.SetFailed(InitCategory.isLValue()
? (RefRelationship == Sema::Ref_Related
? InitializationSequence::FK_ReferenceInitDropsQualifiers
: InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
: InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
return;
}
// - If the initializer expression
// - is an xvalue, class prvalue, array prvalue, or function lvalue and
// "cv1 T1" is reference-compatible with "cv2 T2"
// Note: functions are handled below.
if (!T1Function &&
(RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
(Kind.isCStyleOrFunctionalCast() &&
RefRelationship == Sema::Ref_Related)) &&
(InitCategory.isXValue() ||
(InitCategory.isPRValue() && T2->isRecordType()) ||
(InitCategory.isPRValue() && T2->isArrayType()))) {
ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
if (InitCategory.isPRValue() && T2->isRecordType()) {
// The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
// compiler the freedom to perform a copy here or bind to the
// object, while C++0x requires that we bind directly to the
// object. Hence, we always bind to the object without making an
// extra copy. However, in C++03 requires that we check for the
// presence of a suitable copy constructor:
//
// The constructor that would be used to make the copy shall
// be callable whether or not the copy is actually done.
if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Sequence.AddExtraneousCopyToTemporary(cv2T2);
else if (S.getLangOpts().CPlusPlus11)
CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
}
if (DerivedToBase)
Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
ValueKind);
else if (ObjCConversion)
Sequence.AddObjCObjectConversionStep(
S.Context.getQualifiedType(T1, T2Quals));
ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
Initializer, cv1T1,
T1Quals, T2Quals,
isLValueRef);
Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
return;
}
// - has a class type (i.e., T2 is a class type), where T1 is not
// reference-related to T2, and can be implicitly converted to an
// xvalue, class prvalue, or function lvalue of type "cv3 T3",
// where "cv1 T1" is reference-compatible with "cv3 T3",
//
// DR1287 removes the "implicitly" here.
if (T2->isRecordType()) {
if (RefRelationship == Sema::Ref_Incompatible) {
ConvOvlResult = TryRefInitWithConversionFunction(
S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
if (ConvOvlResult)
Sequence.SetOverloadFailure(
InitializationSequence::FK_ReferenceInitOverloadFailed,
ConvOvlResult);
return;
}
if ((RefRelationship == Sema::Ref_Compatible ||
RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
isRValueRef && InitCategory.isLValue()) {
Sequence.SetFailed(
InitializationSequence::FK_RValueReferenceBindingToLValue);
return;
}
Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
return;
}
// - Otherwise, a temporary of type "cv1 T1" is created and initialized
// from the initializer expression using the rules for a non-reference
// copy-initialization (8.5). The reference is then bound to the
// temporary. [...]
InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
// FIXME: Why do we use an implicit conversion here rather than trying
// copy-initialization?
ImplicitConversionSequence ICS
= S.TryImplicitConversion(Initializer, TempEntity.getType(),
/*SuppressUserConversions=*/false,
/*AllowExplicit=*/false,
/*FIXME:InOverloadResolution=*/false,
/*CStyle=*/Kind.isCStyleOrFunctionalCast(),
/*AllowObjCWritebackConversion=*/false);
if (ICS.isBad()) {
// FIXME: Use the conversion function set stored in ICS to turn
// this into an overloading ambiguity diagnostic. However, we need
// to keep that set as an OverloadCandidateSet rather than as some
// other kind of set.
if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Sequence.SetOverloadFailure(
InitializationSequence::FK_ReferenceInitOverloadFailed,
ConvOvlResult);
else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
else
Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
return;
} else {
Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
}
// [...] If T1 is reference-related to T2, cv1 must be the
// same cv-qualification as, or greater cv-qualification
// than, cv2; otherwise, the program is ill-formed.
unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
if (RefRelationship == Sema::Ref_Related &&
(T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
return;
}
// [...] If T1 is reference-related to T2 and the reference is an rvalue
// reference, the initializer expression shall not be an lvalue.
if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
InitCategory.isLValue()) {
Sequence.SetFailed(
InitializationSequence::FK_RValueReferenceBindingToLValue);
return;
}
Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
return;
}
/// \brief Attempt character array initialization from a string literal
/// (C++ [dcl.init.string], C99 6.7.8).
static void TryStringLiteralInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
Expr *Initializer,
InitializationSequence &Sequence) {
Sequence.AddStringInitStep(Entity.getType());
}
/// \brief Attempt value initialization (C++ [dcl.init]p7).
static void TryValueInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
InitializationSequence &Sequence,
InitListExpr *InitList) {
assert((!InitList || InitList->getNumInits() == 0) &&
"Shouldn't use value-init for non-empty init lists");
// C++98 [dcl.init]p5, C++11 [dcl.init]p7:
//
// To value-initialize an object of type T means:
QualType T = Entity.getType();
// -- if T is an array type, then each element is value-initialized;
T = S.Context.getBaseElementType(T);
if (const RecordType *RT = T->getAs<RecordType>()) {
if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
bool NeedZeroInitialization = true;
if (!S.getLangOpts().CPlusPlus11) {
// C++98:
// -- if T is a class type (clause 9) with a user-declared constructor
// (12.1), then the default constructor for T is called (and the
// initialization is ill-formed if T has no accessible default
// constructor);
if (ClassDecl->hasUserDeclaredConstructor())
NeedZeroInitialization = false;
} else {
// C++11:
// -- if T is a class type (clause 9) with either no default constructor
// (12.1 [class.ctor]) or a default constructor that is user-provided
// or deleted, then the object is default-initialized;
CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
NeedZeroInitialization = false;
}
// -- if T is a (possibly cv-qualified) non-union class type without a
// user-provided or deleted default constructor, then the object is
// zero-initialized and, if T has a non-trivial default constructor,
// default-initialized;
// The 'non-union' here was removed by DR1502. The 'non-trivial default
// constructor' part was removed by DR1507.
if (NeedZeroInitialization)
Sequence.AddZeroInitializationStep(Entity.getType());
// C++03:
// -- if T is a non-union class type without a user-declared constructor,
// then every non-static data member and base class component of T is
// value-initialized;
// [...] A program that calls for [...] value-initialization of an
// entity of reference type is ill-formed.
//
// C++11 doesn't need this handling, because value-initialization does not
// occur recursively there, and the implicit default constructor is
// defined as deleted in the problematic cases.
if (!S.getLangOpts().CPlusPlus11 &&
ClassDecl->hasUninitializedReferenceMember()) {
Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
return;
}
// If this is list-value-initialization, pass the empty init list on when
// building the constructor call. This affects the semantics of a few
// things (such as whether an explicit default constructor can be called).
Expr *InitListAsExpr = InitList;
MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
bool InitListSyntax = InitList;
return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
InitListSyntax);
}
}
Sequence.AddZeroInitializationStep(Entity.getType());
}
/// \brief Attempt default initialization (C++ [dcl.init]p6).
static void TryDefaultInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
InitializationSequence &Sequence) {
assert(Kind.getKind() == InitializationKind::IK_Default);
// C++ [dcl.init]p6:
// To default-initialize an object of type T means:
// - if T is an array type, each element is default-initialized;
QualType DestType = S.Context.getBaseElementType(Entity.getType());
// - if T is a (possibly cv-qualified) class type (Clause 9), the default
// constructor for T is called (and the initialization is ill-formed if
// T has no accessible default constructor);
if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
return;
}
// - otherwise, no initialization is performed.
// If a program calls for the default initialization of an object of
// a const-qualified type T, T shall be a class type with a user-provided
// default constructor.
if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
return;
}
// If the destination type has a lifetime property, zero-initialize it.
if (DestType.getQualifiers().hasObjCLifetime()) {
Sequence.AddZeroInitializationStep(Entity.getType());
return;
}
}
/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
/// which enumerates all conversion functions and performs overload resolution
/// to select the best.
static void TryUserDefinedConversion(Sema &S,
QualType DestType,
const InitializationKind &Kind,
Expr *Initializer,
InitializationSequence &Sequence,
bool TopLevelOfInitList) {
assert(!DestType->isReferenceType() && "References are handled elsewhere");
QualType SourceType = Initializer->getType();
assert((DestType->isRecordType() || SourceType->isRecordType()) &&
"Must have a class type to perform a user-defined conversion");
// Build the candidate set directly in the initialization sequence
// structure, so that it will persist if we fail.
OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
CandidateSet.clear();
// Determine whether we are allowed to call explicit constructors or
// explicit conversion operators.
bool AllowExplicit = Kind.AllowExplicit();
if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
// The type we're converting to is a class type. Enumerate its constructors
// to see if there is a suitable conversion.
CXXRecordDecl *DestRecordDecl
= cast<CXXRecordDecl>(DestRecordType->getDecl());
// Try to complete the type we're converting to.
if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
// The container holding the constructors can under certain conditions
// be changed while iterating. To be safe we copy the lookup results
// to a new container.
SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
for (SmallVectorImpl<NamedDecl *>::iterator
Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Con != ConEnd; ++Con) {
NamedDecl *D = *Con;
DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
// Find the constructor (which may be a template).
CXXConstructorDecl *Constructor = nullptr;
FunctionTemplateDecl *ConstructorTmpl
= dyn_cast<FunctionTemplateDecl>(D);
if (ConstructorTmpl)
Constructor = cast<CXXConstructorDecl>(
ConstructorTmpl->getTemplatedDecl());
else
Constructor = cast<CXXConstructorDecl>(D);
if (!Constructor->isInvalidDecl() &&
Constructor->isConvertingConstructor(AllowExplicit)) {
if (ConstructorTmpl)
S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
/*ExplicitArgs*/ nullptr,
Initializer, CandidateSet,
/*SuppressUserConversions=*/true);
else
S.AddOverloadCandidate(Constructor, FoundDecl,
Initializer, CandidateSet,
/*SuppressUserConversions=*/true);
}
}
}
}
SourceLocation DeclLoc = Initializer->getLocStart();
if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
// The type we're converting from is a class type, enumerate its conversion
// functions.
// We can only enumerate the conversion functions for a complete type; if
// the type isn't complete, simply skip this step.
if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
CXXRecordDecl *SourceRecordDecl
= cast<CXXRecordDecl>(SourceRecordType->getDecl());
const auto &Conversions =
SourceRecordDecl->getVisibleConversionFunctions();
for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
NamedDecl *D = *I;
CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
if (isa<UsingShadowDecl>(D))
D = cast<UsingShadowDecl>(D)->getTargetDecl();
FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
CXXConversionDecl *Conv;
if (ConvTemplate)
Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
else
Conv = cast<CXXConversionDecl>(D);
if (AllowExplicit || !Conv->isExplicit()) {
if (ConvTemplate)
S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
ActingDC, Initializer, DestType,
CandidateSet, AllowExplicit);
else
S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Initializer, DestType, CandidateSet,
AllowExplicit);
}
}
}
}
// Perform overload resolution. If it fails, return the failed result.
OverloadCandidateSet::iterator Best;
if (OverloadingResult Result
= CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sequence.SetOverloadFailure(
InitializationSequence::FK_UserConversionOverloadFailed,
Result);
return;
}
FunctionDecl *Function = Best->Function;
Function->setReferenced();
bool HadMultipleCandidates = (CandidateSet.size() > 1);
if (isa<CXXConstructorDecl>(Function)) {
// Add the user-defined conversion step. Any cv-qualification conversion is
// subsumed by the initialization. Per DR5, the created temporary is of the
// cv-unqualified type of the destination.
Sequence.AddUserConversionStep(Function, Best->FoundDecl,
DestType.getUnqualifiedType(),
HadMultipleCandidates);
return;
}
// Add the user-defined conversion step that calls the conversion function.
QualType ConvType = Function->getCallResultType();
if (ConvType->getAs<RecordType>()) {
// If we're converting to a class type, there may be an copy of
// the resulting temporary object (possible to create an object of
// a base class type). That copy is not a separate conversion, so
// we just make a note of the actual destination type (possibly a
// base class of the type returned by the conversion function) and
// let the user-defined conversion step handle the conversion.
Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
HadMultipleCandidates);
return;
}
Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
HadMultipleCandidates);
// If the conversion following the call to the conversion function
// is interesting, add it as a separate step.
if (Best->FinalConversion.First || Best->FinalConversion.Second ||
Best->FinalConversion.Third) {
ImplicitConversionSequence ICS;
ICS.setStandard();
ICS.Standard = Best->FinalConversion;
Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
}
}
/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
/// a function with a pointer return type contains a 'return false;' statement.
/// In C++11, 'false' is not a null pointer, so this breaks the build of any
/// code using that header.
///
/// Work around this by treating 'return false;' as zero-initializing the result
/// if it's used in a pointer-returning function in a system header.
static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
const InitializedEntity &Entity,
const Expr *Init) {
return S.getLangOpts().CPlusPlus11 &&
Entity.getKind() == InitializedEntity::EK_Result &&
Entity.getType()->isPointerType() &&
isa<CXXBoolLiteralExpr>(Init) &&
!cast<CXXBoolLiteralExpr>(Init)->getValue() &&
S.getSourceManager().isInSystemHeader(Init->getExprLoc());
}
/// The non-zero enum values here are indexes into diagnostic alternatives.
enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
/// Determines whether this expression is an acceptable ICR source.
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
bool isAddressOf, bool &isWeakAccess) {
// Skip parens.
e = e->IgnoreParens();
// Skip address-of nodes.
if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
if (op->getOpcode() == UO_AddrOf)
return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
isWeakAccess);
// Skip certain casts.
} else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
switch (ce->getCastKind()) {
case CK_Dependent:
case CK_BitCast:
case CK_LValueBitCast:
case CK_NoOp:
return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
case CK_ArrayToPointerDecay:
return IIK_nonscalar;
case CK_NullToPointer:
return IIK_okay;
default:
break;
}
// If we have a declaration reference, it had better be a local variable.
} else if (isa<DeclRefExpr>(e)) {
// set isWeakAccess to true, to mean that there will be an implicit
// load which requires a cleanup.
if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
isWeakAccess = true;
if (!isAddressOf) return IIK_nonlocal;
VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
if (!var) return IIK_nonlocal;
return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
// If we have a conditional operator, check both sides.
} else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
isWeakAccess))
return iik;
return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
// These are never scalar.
} else if (isa<ArraySubscriptExpr>(e)) {
return IIK_nonscalar;
// Otherwise, it needs to be a null pointer constant.
} else {
return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
? IIK_okay : IIK_nonlocal);
}
return IIK_nonlocal;
}
/// Check whether the given expression is a valid operand for an
/// indirect copy/restore.
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
assert(src->isRValue());
bool isWeakAccess = false;
InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
// If isWeakAccess to true, there will be an implicit
// load which requires a cleanup.
if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
S.ExprNeedsCleanups = true;
if (iik == IIK_okay) return;
S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
<< ((unsigned) iik - 1) // shift index into diagnostic explanations
<< src->getSourceRange();
}
/// \brief Determine whether we have compatible array types for the
/// purposes of GNU by-copy array initialization.
static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
const ArrayType *Source) {
// If the source and destination array types are equivalent, we're
// done.
if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
return true;
// Make sure that the element types are the same.
if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
return false;
// The only mismatch we allow is when the destination is an
// incomplete array type and the source is a constant array type.
return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
}
static bool tryObjCWritebackConversion(Sema &S,
InitializationSequence &Sequence,
const InitializedEntity &Entity,
Expr *Initializer) {
bool ArrayDecay = false;
QualType ArgType = Initializer->getType();
QualType ArgPointee;
if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
ArrayDecay = true;
ArgPointee = ArgArrayType->getElementType();
ArgType = S.Context.getPointerType(ArgPointee);
}
// Handle write-back conversion.
QualType ConvertedArgType;
if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
ConvertedArgType))
return false;
// We should copy unless we're passing to an argument explicitly
// marked 'out'.
bool ShouldCopy = true;
if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
// Do we need an lvalue conversion?
if (ArrayDecay || Initializer->isGLValue()) {
ImplicitConversionSequence ICS;
ICS.setStandard();
ICS.Standard.setAsIdentityConversion();
QualType ResultType;
if (ArrayDecay) {
ICS.Standard.First = ICK_Array_To_Pointer;
ResultType = S.Context.getPointerType(ArgPointee);
} else {
ICS.Standard.First = ICK_Lvalue_To_Rvalue;
ResultType = Initializer->getType().getNonLValueExprType(S.Context);
}
Sequence.AddConversionSequenceStep(ICS, ResultType);
}
Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
return true;
}
static bool TryOCLSamplerInitialization(Sema &S,
InitializationSequence &Sequence,
QualType DestType,
Expr *Initializer) {
if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
!Initializer->isIntegerConstantExpr(S.getASTContext()))
return false;
Sequence.AddOCLSamplerInitStep(DestType);
return true;
}
//
// OpenCL 1.2 spec, s6.12.10
//
// The event argument can also be used to associate the
// async_work_group_copy with a previous async copy allowing
// an event to be shared by multiple async copies; otherwise
// event should be zero.
//
static bool TryOCLZeroEventInitialization(Sema &S,
InitializationSequence &Sequence,
QualType DestType,
Expr *Initializer) {
if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
!Initializer->isIntegerConstantExpr(S.getASTContext()) ||
(Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
return false;
Sequence.AddOCLZeroEventStep(DestType);
return true;
}
InitializationSequence::InitializationSequence(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args,
bool TopLevelOfInitList)
: FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
}
void InitializationSequence::InitializeFrom(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args,
bool TopLevelOfInitList) {
ASTContext &Context = S.Context;
// Eliminate non-overload placeholder types in the arguments. We
// need to do this before checking whether types are dependent
// because lowering a pseudo-object expression might well give us
// something of dependent type.
for (unsigned I = 0, E = Args.size(); I != E; ++I)
if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
// FIXME: should we be doing this here?
ExprResult result = S.CheckPlaceholderExpr(Args[I]);
if (result.isInvalid()) {
SetFailed(FK_PlaceholderType);
return;
}
Args[I] = result.get();
}
// C++0x [dcl.init]p16:
// The semantics of initializers are as follows. The destination type is
// the type of the object or reference being initialized and the source
// type is the type of the initializer expression. The source type is not
// defined when the initializer is a braced-init-list or when it is a
// parenthesized list of expressions.
QualType DestType = Entity.getType();
if (DestType->isDependentType() ||
Expr::hasAnyTypeDependentArguments(Args)) {
SequenceKind = DependentSequence;
return;
}
// Almost everything is a normal sequence.
setSequenceKind(NormalSequence);
QualType SourceType;
Expr *Initializer = nullptr;
if (Args.size() == 1) {
Initializer = Args[0];
if (S.getLangOpts().ObjC1) {
if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
DestType, Initializer->getType(),
Initializer) ||
S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
Args[0] = Initializer;
}
if (!isa<InitListExpr>(Initializer))
SourceType = Initializer->getType();
}
// HLSL Change Starts
if (S.getLangOpts().HLSL) {
hlsl::InitializeInitSequenceForHLSL(&S, Entity, Kind, Args, TopLevelOfInitList, this);
return;
}
// HLSL Change Ends
// - If the initializer is a (non-parenthesized) braced-init-list, the
// object is list-initialized (8.5.4).
if (Kind.getKind() != InitializationKind::IK_Direct) {
if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
TryListInitialization(S, Entity, Kind, InitList, *this);
return;
}
}
// - If the destination type is a reference type, see 8.5.3.
if (DestType->isReferenceType()) {
// C++0x [dcl.init.ref]p1:
// A variable declared to be a T& or T&&, that is, "reference to type T"
// (8.3.2), shall be initialized by an object, or function, of type T or
// by an object that can be converted into a T.
// (Therefore, multiple arguments are not permitted.)
if (Args.size() != 1)
SetFailed(FK_TooManyInitsForReference);
else
TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
return;
}
// - If the initializer is (), the object is value-initialized.
if (Kind.getKind() == InitializationKind::IK_Value ||
(Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
TryValueInitialization(S, Entity, Kind, *this);
return;
}
// Handle default initialization.
if (Kind.getKind() == InitializationKind::IK_Default) {
TryDefaultInitialization(S, Entity, Kind, *this);
return;
}
// - If the destination type is an array of characters, an array of
// char16_t, an array of char32_t, or an array of wchar_t, and the
// initializer is a string literal, see 8.5.2.
// - Otherwise, if the destination type is an array, the program is
// ill-formed.
if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
if (Initializer && isa<VariableArrayType>(DestAT)) {
SetFailed(FK_VariableLengthArrayHasInitializer);
return;
}
if (Initializer) {
switch (IsStringInit(Initializer, DestAT, Context)) {
case SIF_None:
TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
return;
case SIF_NarrowStringIntoWideChar:
SetFailed(FK_NarrowStringIntoWideCharArray);
return;
case SIF_WideStringIntoChar:
SetFailed(FK_WideStringIntoCharArray);
return;
case SIF_IncompatWideStringIntoWideChar:
SetFailed(FK_IncompatWideStringIntoWideChar);
return;
case SIF_Other:
break;
}
}
// Note: as an GNU C extension, we allow initialization of an
// array from a compound literal that creates an array of the same
// type, so long as the initializer has no side effects.
if (!S.getLangOpts().CPlusPlus && Initializer &&
isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
Initializer->getType()->isArrayType()) {
const ArrayType *SourceAT
= Context.getAsArrayType(Initializer->getType());
if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
SetFailed(FK_ArrayTypeMismatch);
else if (Initializer->HasSideEffects(S.Context))
SetFailed(FK_NonConstantArrayInit);
else {
AddArrayInitStep(DestType);
}
}
// Note: as a GNU C++ extension, we allow list-initialization of a
// class member of array type from a parenthesized initializer list.
else if (S.getLangOpts().CPlusPlus &&
Entity.getKind() == InitializedEntity::EK_Member &&
Initializer && isa<InitListExpr>(Initializer)) {
TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
*this);
AddParenthesizedArrayInitStep(DestType);
} else if (DestAT->getElementType()->isCharType())
SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
else if (IsWideCharCompatible(DestAT->getElementType(), Context))
SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
else
SetFailed(FK_ArrayNeedsInitList);
return;
}
// Determine whether we should consider writeback conversions for
// Objective-C ARC.
bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Entity.isParameterKind();
// We're at the end of the line for C: it's either a write-back conversion
// or it's a C assignment. There's no need to check anything else.
if (!S.getLangOpts().CPlusPlus) {
// If allowed, check whether this is an Objective-C writeback conversion.
if (allowObjCWritebackConversion &&
tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
return;
}
if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
return;
if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
return;
// Handle initialization in C
AddCAssignmentStep(DestType);
MaybeProduceObjCObject(S, *this, Entity);
return;
}
assert(S.getLangOpts().CPlusPlus);
// - If the destination type is a (possibly cv-qualified) class type:
if (DestType->isRecordType()) {
// - If the initialization is direct-initialization, or if it is
// copy-initialization where the cv-unqualified version of the
// source type is the same class as, or a derived class of, the
// class of the destination, constructors are considered. [...]
if (Kind.getKind() == InitializationKind::IK_Direct ||
(Kind.getKind() == InitializationKind::IK_Copy &&
(Context.hasSameUnqualifiedType(SourceType, DestType) ||
S.IsDerivedFrom(SourceType, DestType))))
TryConstructorInitialization(S, Entity, Kind, Args,
DestType, *this);
// - Otherwise (i.e., for the remaining copy-initialization cases),
// user-defined conversion sequences that can convert from the source
// type to the destination type or (when a conversion function is
// used) to a derived class thereof are enumerated as described in
// 13.3.1.4, and the best one is chosen through overload resolution
// (13.3).
else
TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
TopLevelOfInitList);
return;
}
if (Args.size() > 1) {
SetFailed(FK_TooManyInitsForScalar);
return;
}
assert(Args.size() == 1 && "Zero-argument case handled above");
// HLSL Change Starts
assert(Initializer != nullptr && "otherwise prior code changed and Args.size() == 1 no longer reads from first argument");
_Analysis_assume_(Initializer != nullptr);
// HLSL Change Ends
// - Otherwise, if the source type is a (possibly cv-qualified) class
// type, conversion functions are considered.
if (!SourceType.isNull() && SourceType->isRecordType()) {
// For a conversion to _Atomic(T) from either T or a class type derived
// from T, initialize the T object then convert to _Atomic type.
bool NeedAtomicConversion = false;
if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
DestType = Atomic->getValueType();
NeedAtomicConversion = true;
}
}
TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
TopLevelOfInitList);
MaybeProduceObjCObject(S, *this, Entity);
if (!Failed() && NeedAtomicConversion)
AddAtomicConversionStep(Entity.getType());
return;
}
// - Otherwise, the initial value of the object being initialized is the
// (possibly converted) value of the initializer expression. Standard
// conversions (Clause 4) will be used, if necessary, to convert the
// initializer expression to the cv-unqualified version of the
// destination type; no user-defined conversions are considered.
ImplicitConversionSequence ICS
= S.TryImplicitConversion(Initializer, DestType,
/*SuppressUserConversions*/true,
/*AllowExplicitConversions*/ false,
/*InOverloadResolution*/ false,
/*CStyle=*/Kind.isCStyleOrFunctionalCast(),
allowObjCWritebackConversion);
if (ICS.isStandard() &&
ICS.Standard.Second == ICK_Writeback_Conversion) {
// Objective-C ARC writeback conversion.
// We should copy unless we're passing to an argument explicitly
// marked 'out'.
bool ShouldCopy = true;
if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
// If there was an lvalue adjustment, add it as a separate conversion.
if (ICS.Standard.First == ICK_Array_To_Pointer ||
ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
ImplicitConversionSequence LvalueICS;
LvalueICS.setStandard();
LvalueICS.Standard.setAsIdentityConversion();
LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
LvalueICS.Standard.First = ICS.Standard.First;
AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
}
AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
} else if (ICS.isBad()) {
DeclAccessPair dap;
if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
AddZeroInitializationStep(Entity.getType());
} else if (Initializer->getType() == Context.OverloadTy &&
!S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
false, dap))
SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
else
SetFailed(InitializationSequence::FK_ConversionFailed);
} else {
AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
MaybeProduceObjCObject(S, *this, Entity);
}
}
InitializationSequence::~InitializationSequence() {
for (auto &S : Steps)
S.Destroy();
}
//===----------------------------------------------------------------------===//
// Perform initialization
//===----------------------------------------------------------------------===//
static Sema::AssignmentAction
getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
switch(Entity.getKind()) {
case InitializedEntity::EK_Variable:
case InitializedEntity::EK_New:
case InitializedEntity::EK_Exception:
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
return Sema::AA_Initializing;
case InitializedEntity::EK_Parameter:
if (Entity.getDecl() &&
isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
return Sema::AA_Sending;
return Sema::AA_Passing;
case InitializedEntity::EK_Parameter_CF_Audited:
if (Entity.getDecl() &&
isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
return Sema::AA_Sending;
return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
case InitializedEntity::EK_Result:
return Sema::AA_Returning;
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_RelatedResult:
// FIXME: Can we tell apart casting vs. converting?
return Sema::AA_Casting;
case InitializedEntity::EK_Member:
case InitializedEntity::EK_ArrayElement:
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_ComplexElement:
case InitializedEntity::EK_BlockElement:
case InitializedEntity::EK_LambdaCapture:
case InitializedEntity::EK_CompoundLiteralInit:
return Sema::AA_Initializing;
}
llvm_unreachable("Invalid EntityKind!");
}
/// \brief Whether we should bind a created object as a temporary when
/// initializing the given entity.
static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
switch (Entity.getKind()) {
case InitializedEntity::EK_ArrayElement:
case InitializedEntity::EK_Member:
case InitializedEntity::EK_Result:
case InitializedEntity::EK_New:
case InitializedEntity::EK_Variable:
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_ComplexElement:
case InitializedEntity::EK_Exception:
case InitializedEntity::EK_BlockElement:
case InitializedEntity::EK_LambdaCapture:
case InitializedEntity::EK_CompoundLiteralInit:
return false;
case InitializedEntity::EK_Parameter:
case InitializedEntity::EK_Parameter_CF_Audited:
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_RelatedResult:
return true;
}
llvm_unreachable("missed an InitializedEntity kind?");
}
/// \brief Whether the given entity, when initialized with an object
/// created for that initialization, requires destruction.
static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
switch (Entity.getKind()) {
case InitializedEntity::EK_Result:
case InitializedEntity::EK_New:
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_ComplexElement:
case InitializedEntity::EK_BlockElement:
case InitializedEntity::EK_LambdaCapture:
return false;
case InitializedEntity::EK_Member:
case InitializedEntity::EK_Variable:
case InitializedEntity::EK_Parameter:
case InitializedEntity::EK_Parameter_CF_Audited:
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_ArrayElement:
case InitializedEntity::EK_Exception:
case InitializedEntity::EK_CompoundLiteralInit:
case InitializedEntity::EK_RelatedResult:
return true;
}
llvm_unreachable("missed an InitializedEntity kind?");
}
/// \brief Look for copy and move constructors and constructor templates, for
/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
static void LookupCopyAndMoveConstructors(Sema &S,
OverloadCandidateSet &CandidateSet,
CXXRecordDecl *Class,
Expr *CurInitExpr) {
DeclContext::lookup_result R = S.LookupConstructors(Class);
// The container holding the constructors can under certain conditions
// be changed while iterating (e.g. because of deserialization).
// To be safe we copy the lookup results to a new container.
SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
for (SmallVectorImpl<NamedDecl *>::iterator
CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
NamedDecl *D = *CI;
CXXConstructorDecl *Constructor = nullptr;
if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
// Handle copy/moveconstructors, only.
if (!Constructor || Constructor->isInvalidDecl() ||
!Constructor->isCopyOrMoveConstructor() ||
!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
continue;
DeclAccessPair FoundDecl
= DeclAccessPair::make(Constructor, Constructor->getAccess());
S.AddOverloadCandidate(Constructor, FoundDecl,
CurInitExpr, CandidateSet);
continue;
}
// Handle constructor templates.
FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
if (ConstructorTmpl->isInvalidDecl())
continue;
Constructor = cast<CXXConstructorDecl>(
ConstructorTmpl->getTemplatedDecl());
if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
continue;
// FIXME: Do we need to limit this to copy-constructor-like
// candidates?
DeclAccessPair FoundDecl
= DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
CurInitExpr, CandidateSet, true);
}
}
/// \brief Get the location at which initialization diagnostics should appear.
static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
Expr *Initializer) {
switch (Entity.getKind()) {
case InitializedEntity::EK_Result:
return Entity.getReturnLoc();
case InitializedEntity::EK_Exception:
return Entity.getThrowLoc();
case InitializedEntity::EK_Variable:
return Entity.getDecl()->getLocation();
case InitializedEntity::EK_LambdaCapture:
return Entity.getCaptureLoc();
case InitializedEntity::EK_ArrayElement:
case InitializedEntity::EK_Member:
case InitializedEntity::EK_Parameter:
case InitializedEntity::EK_Parameter_CF_Audited:
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_New:
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_ComplexElement:
case InitializedEntity::EK_BlockElement:
case InitializedEntity::EK_CompoundLiteralInit:
case InitializedEntity::EK_RelatedResult:
return Initializer->getLocStart();
}
llvm_unreachable("missed an InitializedEntity kind?");
}
/// \brief Make a (potentially elidable) temporary copy of the object
/// provided by the given initializer by calling the appropriate copy
/// constructor.
///
/// \param S The Sema object used for type-checking.
///
/// \param T The type of the temporary object, which must either be
/// the type of the initializer expression or a superclass thereof.
///
/// \param Entity The entity being initialized.
///
/// \param CurInit The initializer expression.
///
/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
/// is permitted in C++03 (but not C++0x) when binding a reference to
/// an rvalue.
///
/// \returns An expression that copies the initializer expression into
/// a temporary object, or an error expression if a copy could not be
/// created.
static ExprResult CopyObject(Sema &S,
QualType T,
const InitializedEntity &Entity,
ExprResult CurInit,
bool IsExtraneousCopy) {
if (CurInit.isInvalid())
return CurInit;
// Determine which class type we're copying to.
Expr *CurInitExpr = (Expr *)CurInit.get();
CXXRecordDecl *Class = nullptr;
if (const RecordType *Record = T->getAs<RecordType>())
Class = cast<CXXRecordDecl>(Record->getDecl());
if (!Class)
return CurInit;
// C++0x [class.copy]p32:
// When certain criteria are met, an implementation is allowed to
// omit the copy/move construction of a class object, even if the
// copy/move constructor and/or destructor for the object have
// side effects. [...]
// - when a temporary class object that has not been bound to a
// reference (12.2) would be copied/moved to a class object
// with the same cv-unqualified type, the copy/move operation
// can be omitted by constructing the temporary object
// directly into the target of the omitted copy/move
//
// Note that the other three bullets are handled elsewhere. Copy
// elision for return statements and throw expressions are handled as part
// of constructor initialization, while copy elision for exception handlers
// is handled by the run-time.
bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
// Make sure that the type we are copying is complete.
if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
return CurInit;
// Perform overload resolution using the class's copy/move constructors.
// Only consider constructors and constructor templates. Per
// C++0x [dcl.init]p16, second bullet to class types, this initialization
// is direct-initialization.
OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
bool HadMultipleCandidates = (CandidateSet.size() > 1);
OverloadCandidateSet::iterator Best;
switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
case OR_Success:
break;
case OR_No_Viable_Function:
S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
? diag::ext_rvalue_to_reference_temp_copy_no_viable
: diag::err_temp_copy_no_viable)
<< (int)Entity.getKind() << CurInitExpr->getType()
<< CurInitExpr->getSourceRange();
CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
if (!IsExtraneousCopy || S.isSFINAEContext())
return ExprError();
return CurInit;
case OR_Ambiguous:
S.Diag(Loc, diag::err_temp_copy_ambiguous)
<< (int)Entity.getKind() << CurInitExpr->getType()
<< CurInitExpr->getSourceRange();
CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
return ExprError();
case OR_Deleted:
S.Diag(Loc, diag::err_temp_copy_deleted)
<< (int)Entity.getKind() << CurInitExpr->getType()
<< CurInitExpr->getSourceRange();
S.NoteDeletedFunction(Best->Function);
return ExprError();
}
CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
SmallVector<Expr*, 8> ConstructorArgs;
CurInit.get(); // Ownership transferred into MultiExprArg, below.
S.CheckConstructorAccess(Loc, Constructor, Entity,
Best->FoundDecl.getAccess(), IsExtraneousCopy);
if (IsExtraneousCopy) {
// If this is a totally extraneous copy for C++03 reference
// binding purposes, just return the original initialization
// expression. We don't generate an (elided) copy operation here
// because doing so would require us to pass down a flag to avoid
// infinite recursion, where each step adds another extraneous,
// elidable copy.
// Instantiate the default arguments of any extra parameters in
// the selected copy constructor, as if we were going to create a
// proper call to the copy constructor.
for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
ParmVarDecl *Parm = Constructor->getParamDecl(I);
if (S.RequireCompleteType(Loc, Parm->getType(),
diag::err_call_incomplete_argument))
break;
// Build the default argument expression; we don't actually care
// if this succeeds or not, because this routine will complain
// if there was a problem.
S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
}
return CurInitExpr;
}
// Determine the arguments required to actually perform the
// constructor call (we might have derived-to-base conversions, or
// the copy constructor may have default arguments).
if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
return ExprError();
// Actually perform the constructor call.
CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
ConstructorArgs,
HadMultipleCandidates,
/*ListInit*/ false,
/*StdInitListInit*/ false,
/*ZeroInit*/ false,
CXXConstructExpr::CK_Complete,
SourceRange());
// If we're supposed to bind temporaries, do so.
if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
return CurInit;
}
/// \brief Check whether elidable copy construction for binding a reference to
/// a temporary would have succeeded if we were building in C++98 mode, for
/// -Wc++98-compat.
static void CheckCXX98CompatAccessibleCopy(Sema &S,
const InitializedEntity &Entity,
Expr *CurInitExpr) {
assert(S.getLangOpts().CPlusPlus11);
const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
if (!Record)
return;
SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
return;
// Find constructors which would have been considered.
OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
LookupCopyAndMoveConstructors(
S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
// Perform overload resolution.
OverloadCandidateSet::iterator Best;
OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
<< OR << (int)Entity.getKind() << CurInitExpr->getType()
<< CurInitExpr->getSourceRange();
switch (OR) {
case OR_Success:
S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Entity, Best->FoundDecl.getAccess(), Diag);
// FIXME: Check default arguments as far as that's possible.
break;
case OR_No_Viable_Function:
S.Diag(Loc, Diag);
CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
break;
case OR_Ambiguous:
S.Diag(Loc, Diag);
CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
break;
case OR_Deleted:
S.Diag(Loc, Diag);
S.NoteDeletedFunction(Best->Function);
break;
}
}
void InitializationSequence::PrintInitLocationNote(Sema &S,
const InitializedEntity &Entity) {
if (Entity.isParameterKind() && Entity.getDecl()) {
if (Entity.getDecl()->getLocation().isInvalid())
return;
if (Entity.getDecl()->getDeclName())
S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
<< Entity.getDecl()->getDeclName();
else
S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
}
else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
Entity.getMethodDecl())
S.Diag(Entity.getMethodDecl()->getLocation(),
diag::note_method_return_type_change)
<< Entity.getMethodDecl()->getDeclName();
}
static bool isReferenceBinding(const InitializationSequence::Step &s) {
return s.Kind == InitializationSequence::SK_BindReference ||
s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
}
/// Returns true if the parameters describe a constructor initialization of
/// an explicit temporary object, e.g. "Point(x, y)".
static bool isExplicitTemporary(const InitializedEntity &Entity,
const InitializationKind &Kind,
unsigned NumArgs) {
switch (Entity.getKind()) {
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_CompoundLiteralInit:
case InitializedEntity::EK_RelatedResult:
break;
default:
return false;
}
switch (Kind.getKind()) {
case InitializationKind::IK_DirectList:
return true;
// FIXME: Hack to work around cast weirdness.
case InitializationKind::IK_Direct:
case InitializationKind::IK_Value:
return NumArgs != 1;
default:
return false;
}
}
static ExprResult
PerformConstructorInitialization(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args,
const InitializationSequence::Step& Step,
bool &ConstructorInitRequiresZeroInit,
bool IsListInitialization,
bool IsStdInitListInitialization,
SourceLocation LBraceLoc,
SourceLocation RBraceLoc) {
unsigned NumArgs = Args.size();
CXXConstructorDecl *Constructor
= cast<CXXConstructorDecl>(Step.Function.Function);
bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
// Build a call to the selected constructor.
SmallVector<Expr*, 8> ConstructorArgs;
SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
? Kind.getEqualLoc()
: Kind.getLocation();
if (Kind.getKind() == InitializationKind::IK_Default) {
// Force even a trivial, implicit default constructor to be
// semantically checked. We do this explicitly because we don't build
// the definition for completely trivial constructors.
assert(Constructor->getParent() && "No parent class for constructor.");
if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Constructor->isTrivial() && !Constructor->isUsed(false))
S.DefineImplicitDefaultConstructor(Loc, Constructor);
}
ExprResult CurInit((Expr *)nullptr);
// C++ [over.match.copy]p1:
// - When initializing a temporary to be bound to the first parameter
// of a constructor that takes a reference to possibly cv-qualified
// T as its first argument, called with a single argument in the
// context of direct-initialization, explicit conversion functions
// are also considered.
bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
Args.size() == 1 &&
Constructor->isCopyOrMoveConstructor();
// Determine the arguments required to actually perform the constructor
// call.
if (S.CompleteConstructorCall(Constructor, Args,
Loc, ConstructorArgs,
AllowExplicitConv,
IsListInitialization))
return ExprError();
if (isExplicitTemporary(Entity, Kind, NumArgs)) {
// An explicitly-constructed temporary, e.g., X(1, 2).
S.MarkFunctionReferenced(Loc, Constructor);
if (S.DiagnoseUseOfDecl(Constructor, Loc))
return ExprError();
TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
if (!TSInfo)
TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
SourceRange ParenOrBraceRange =
(Kind.getKind() == InitializationKind::IK_DirectList)
? SourceRange(LBraceLoc, RBraceLoc)
: Kind.getParenRange();
CurInit = new (S.Context) CXXTemporaryObjectExpr(
S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
HadMultipleCandidates, IsListInitialization,
IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
} else {
CXXConstructExpr::ConstructionKind ConstructKind =
CXXConstructExpr::CK_Complete;
if (Entity.getKind() == InitializedEntity::EK_Base) {
ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
CXXConstructExpr::CK_VirtualBase :
CXXConstructExpr::CK_NonVirtualBase;
} else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
ConstructKind = CXXConstructExpr::CK_Delegating;
}
// Only get the parenthesis or brace range if it is a list initialization or
// direct construction.
SourceRange ParenOrBraceRange;
if (IsListInitialization)
ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
else if (Kind.getKind() == InitializationKind::IK_Direct)
ParenOrBraceRange = Kind.getParenRange();
// If the entity allows NRVO, mark the construction as elidable
// unconditionally.
if (Entity.allowsNRVO())
CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Constructor, /*Elidable=*/true,
ConstructorArgs,
HadMultipleCandidates,
IsListInitialization,
IsStdInitListInitialization,
ConstructorInitRequiresZeroInit,
ConstructKind,
ParenOrBraceRange);
else
CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Constructor,
ConstructorArgs,
HadMultipleCandidates,
IsListInitialization,
IsStdInitListInitialization,
ConstructorInitRequiresZeroInit,
ConstructKind,
ParenOrBraceRange);
}
if (CurInit.isInvalid())
return ExprError();
// Only check access if all of that succeeded.
S.CheckConstructorAccess(Loc, Constructor, Entity,
Step.Function.FoundDecl.getAccess());
if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
return ExprError();
if (shouldBindAsTemporary(Entity))
CurInit = S.MaybeBindToTemporary(CurInit.get());
return CurInit;
}
/// Determine whether the specified InitializedEntity definitely has a lifetime
/// longer than the current full-expression. Conservatively returns false if
/// it's unclear.
static bool
InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
const InitializedEntity *Top = &Entity;
while (Top->getParent())
Top = Top->getParent();
switch (Top->getKind()) {
case InitializedEntity::EK_Variable:
case InitializedEntity::EK_Result:
case InitializedEntity::EK_Exception:
case InitializedEntity::EK_Member:
case InitializedEntity::EK_New:
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
return true;
case InitializedEntity::EK_ArrayElement:
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_BlockElement:
case InitializedEntity::EK_ComplexElement:
// Could not determine what the full initialization is. Assume it might not
// outlive the full-expression.
return false;
case InitializedEntity::EK_Parameter:
case InitializedEntity::EK_Parameter_CF_Audited:
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_LambdaCapture:
case InitializedEntity::EK_CompoundLiteralInit:
case InitializedEntity::EK_RelatedResult:
// The entity being initialized might not outlive the full-expression.
return false;
}
llvm_unreachable("unknown entity kind");
}
/// Determine the declaration which an initialized entity ultimately refers to,
/// for the purpose of lifetime-extending a temporary bound to a reference in
/// the initialization of \p Entity.
static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
const InitializedEntity *Entity,
const InitializedEntity *FallbackDecl = nullptr) {
// C++11 [class.temporary]p5:
switch (Entity->getKind()) {
case InitializedEntity::EK_Variable:
// The temporary [...] persists for the lifetime of the reference
return Entity;
case InitializedEntity::EK_Member:
// For subobjects, we look at the complete object.
if (Entity->getParent())
return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
Entity);
// except:
// -- A temporary bound to a reference member in a constructor's
// ctor-initializer persists until the constructor exits.
return Entity;
case InitializedEntity::EK_Parameter:
case InitializedEntity::EK_Parameter_CF_Audited:
// -- A temporary bound to a reference parameter in a function call
// persists until the completion of the full-expression containing
// the call.
case InitializedEntity::EK_Result:
// -- The lifetime of a temporary bound to the returned value in a
// function return statement is not extended; the temporary is
// destroyed at the end of the full-expression in the return statement.
case InitializedEntity::EK_New:
// -- A temporary bound to a reference in a new-initializer persists
// until the completion of the full-expression containing the
// new-initializer.
return nullptr;
case InitializedEntity::EK_Temporary:
case InitializedEntity::EK_CompoundLiteralInit:
case InitializedEntity::EK_RelatedResult:
// We don't yet know the storage duration of the surrounding temporary.
// Assume it's got full-expression duration for now, it will patch up our
// storage duration if that's not correct.
return nullptr;
case InitializedEntity::EK_ArrayElement:
// For subobjects, we look at the complete object.
return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
FallbackDecl);
case InitializedEntity::EK_Base:
case InitializedEntity::EK_Delegating:
// We can reach this case for aggregate initialization in a constructor:
// struct A { int &&r; };
// struct B : A { B() : A{0} {} };
// In this case, use the innermost field decl as the context.
return FallbackDecl;
case InitializedEntity::EK_BlockElement:
case InitializedEntity::EK_LambdaCapture:
case InitializedEntity::EK_Exception:
case InitializedEntity::EK_VectorElement:
case InitializedEntity::EK_ComplexElement:
return nullptr;
}
llvm_unreachable("unknown entity kind");
}
static void performLifetimeExtension(Expr *Init,
const InitializedEntity *ExtendingEntity);
/// Update a glvalue expression that is used as the initializer of a reference
/// to note that its lifetime is extended.
/// \return \c true if any temporary had its lifetime extended.
static bool
performReferenceExtension(Expr *Init,
const InitializedEntity *ExtendingEntity) {
// Walk past any constructs which we can lifetime-extend across.
Expr *Old;
do {
Old = Init;
if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
// This is just redundant braces around an initializer. Step over it.
Init = ILE->getInit(0);
}
}
// Step over any subobject adjustments; we may have a materialized
// temporary inside them.
SmallVector<const Expr *, 2> CommaLHSs;
SmallVector<SubobjectAdjustment, 2> Adjustments;
Init = const_cast<Expr *>(
Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
// Per current approach for DR1376, look through casts to reference type
// when performing lifetime extension.
if (CastExpr *CE = dyn_cast<CastExpr>(Init))
if (CE->getSubExpr()->isGLValue())
Init = CE->getSubExpr();
// FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
// It's unclear if binding a reference to that xvalue extends the array
// temporary.
} while (Init != Old);
if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
// Update the storage duration of the materialized temporary.
// FIXME: Rebuild the expression instead of mutating it.
ME->setExtendingDecl(ExtendingEntity->getDecl(),
ExtendingEntity->allocateManglingNumber());
performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
return true;
}
return false;
}
/// Update a prvalue expression that is going to be materialized as a
/// lifetime-extended temporary.
static void performLifetimeExtension(Expr *Init,
const InitializedEntity *ExtendingEntity) {
// Dig out the expression which constructs the extended temporary.
SmallVector<const Expr *, 2> CommaLHSs;
SmallVector<SubobjectAdjustment, 2> Adjustments;
Init = const_cast<Expr *>(
Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
Init = BTE->getSubExpr();
if (CXXStdInitializerListExpr *ILE =
dyn_cast<CXXStdInitializerListExpr>(Init)) {
performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
return;
}
if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
if (ILE->getType()->isArrayType()) {
for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
return;
}
if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
assert(RD->isAggregate() && "aggregate init on non-aggregate");
// If we lifetime-extend a braced initializer which is initializing an
// aggregate, and that aggregate contains reference members which are
// bound to temporaries, those temporaries are also lifetime-extended.
if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
performReferenceExtension(ILE->getInit(0), ExtendingEntity);
else {
unsigned Index = 0;
for (const auto *I : RD->fields()) {
if (Index >= ILE->getNumInits())
break;
if (I->isUnnamedBitfield())
continue;
Expr *SubInit = ILE->getInit(Index);
if (I->getType()->isReferenceType())
performReferenceExtension(SubInit, ExtendingEntity);
else if (isa<InitListExpr>(SubInit) ||
isa<CXXStdInitializerListExpr>(SubInit))
// This may be either aggregate-initialization of a member or
// initialization of a std::initializer_list object. Either way,
// we should recursively lifetime-extend that initializer.
performLifetimeExtension(SubInit, ExtendingEntity);
++Index;
}
}
}
}
}
static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
const Expr *Init, bool IsInitializerList,
const ValueDecl *ExtendingDecl) {
// Warn if a field lifetime-extends a temporary.
if (isa<FieldDecl>(ExtendingDecl)) {
if (IsInitializerList) {
S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
<< /*at end of constructor*/true;
return;
}
bool IsSubobjectMember = false;
for (const InitializedEntity *Ent = Entity.getParent(); Ent;
Ent = Ent->getParent()) {
if (Ent->getKind() != InitializedEntity::EK_Base) {
IsSubobjectMember = true;
break;
}
}
S.Diag(Init->getExprLoc(),
diag::warn_bind_ref_member_to_temporary)
<< ExtendingDecl << Init->getSourceRange()
<< IsSubobjectMember << IsInitializerList;
if (IsSubobjectMember)
S.Diag(ExtendingDecl->getLocation(),
diag::note_ref_subobject_of_member_declared_here);
else
S.Diag(ExtendingDecl->getLocation(),
diag::note_ref_or_ptr_member_declared_here)
<< /*is pointer*/false;
}
}
static void DiagnoseNarrowingInInitList(Sema &S,
const ImplicitConversionSequence &ICS,
QualType PreNarrowingType,
QualType EntityType,
const Expr *PostInit);
/// Provide warnings when std::move is used on construction.
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
bool IsReturnStmt) {
if (!InitExpr)
return;
if (!S.ActiveTemplateInstantiations.empty())
return;
QualType DestType = InitExpr->getType();
if (!DestType->isRecordType())
return;
unsigned DiagID = 0;
if (IsReturnStmt) {
const CXXConstructExpr *CCE =
dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
if (!CCE || CCE->getNumArgs() != 1)
return;
if (!CCE->getConstructor()->isCopyOrMoveConstructor())
return;
InitExpr = CCE->getArg(0)->IgnoreImpCasts();
}
// Find the std::move call and get the argument.
const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
if (!CE || CE->getNumArgs() != 1)
return;
const FunctionDecl *MoveFunction = CE->getDirectCallee();
if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
!MoveFunction->getIdentifier() ||
!MoveFunction->getIdentifier()->isStr("move"))
return;
const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
if (IsReturnStmt) {
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
if (!DRE || DRE->refersToEnclosingVariableOrCapture())
return;
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
if (!VD || !VD->hasLocalStorage())
return;
QualType SourceType = VD->getType();
if (!SourceType->isRecordType())
return;
if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
return;
}
// If we're returning a function parameter, copy elision
// is not possible.
if (isa<ParmVarDecl>(VD))
DiagID = diag::warn_redundant_move_on_return;
else
DiagID = diag::warn_pessimizing_move_on_return;
} else {
DiagID = diag::warn_pessimizing_move_on_initialization;
const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
return;
}
S.Diag(CE->getLocStart(), DiagID);
// Get all the locations for a fix-it. Don't emit the fix-it if any location
// is within a macro.
SourceLocation CallBegin = CE->getCallee()->getLocStart();
if (CallBegin.isMacroID())
return;
SourceLocation RParen = CE->getRParenLoc();
if (RParen.isMacroID())
return;
SourceLocation LParen;
SourceLocation ArgLoc = Arg->getLocStart();
// Special testing for the argument location. Since the fix-it needs the
// location right before the argument, the argument location can be in a
// macro only if it is at the beginning of the macro.
while (ArgLoc.isMacroID() &&
S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
}
if (LParen.isMacroID())
return;
LParen = ArgLoc.getLocWithOffset(-1);
S.Diag(CE->getLocStart(), diag::note_remove_move)
<< FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
<< FixItHint::CreateRemoval(SourceRange(RParen, RParen));
}
ExprResult
InitializationSequence::Perform(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args,
QualType *ResultType) {
if (Failed()) {
Diagnose(S, Entity, Kind, Args);
return ExprError();
}
if (!ZeroInitializationFixit.empty()) {
unsigned DiagID = diag::err_default_init_const;
if (Decl *D = Entity.getDecl())
if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
DiagID = diag::ext_default_init_const;
// The initialization would have succeeded with this fixit. Since the fixit
// is on the error, we need to build a valid AST in this case, so this isn't
// handled in the Failed() branch above.
QualType DestType = Entity.getType();
S.Diag(Kind.getLocation(), DiagID)
<< DestType << (bool)DestType->getAs<RecordType>()
<< FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
ZeroInitializationFixit);
}
if (getKind() == DependentSequence) {
// If the declaration is a non-dependent, incomplete array type
// that has an initializer, then its type will be completed once
// the initializer is instantiated.
if (ResultType && !Entity.getType()->isDependentType() &&
Args.size() == 1) {
QualType DeclType = Entity.getType();
if (const IncompleteArrayType *ArrayT
= S.Context.getAsIncompleteArrayType(DeclType)) {
// FIXME: We don't currently have the ability to accurately
// compute the length of an initializer list without
// performing full type-checking of the initializer list
// (since we have to determine where braces are implicitly
// introduced and such). So, we fall back to making the array
// type a dependently-sized array type with no specified
// bound.
if (isa<InitListExpr>((Expr *)Args[0])) {
SourceRange Brackets;
// Scavange the location of the brackets from the entity, if we can.
if (DeclaratorDecl *DD = Entity.getDecl()) {
if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
TypeLoc TL = TInfo->getTypeLoc();
if (IncompleteArrayTypeLoc ArrayLoc =
TL.getAs<IncompleteArrayTypeLoc>())
Brackets = ArrayLoc.getBracketsRange();
}
}
*ResultType
= S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
/*NumElts=*/nullptr,
ArrayT->getSizeModifier(),
ArrayT->getIndexTypeCVRQualifiers(),
Brackets);
}
}
}
if (Kind.getKind() == InitializationKind::IK_Direct &&
!Kind.isExplicitCast()) {
// Rebuild the ParenListExpr.
SourceRange ParenRange = Kind.getParenRange();
return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Args);
}
assert(Kind.getKind() == InitializationKind::IK_Copy ||
Kind.isExplicitCast() ||
Kind.getKind() == InitializationKind::IK_DirectList);
return ExprResult(Args[0]);
}
// No steps means no initialization.
if (Steps.empty())
return ExprResult((Expr *)nullptr);
if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
!Entity.isParameterKind()) {
// Produce a C++98 compatibility warning if we are initializing a reference
// from an initializer list. For parameters, we produce a better warning
// elsewhere.
Expr *Init = Args[0];
S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
<< Init->getSourceRange();
}
// Diagnose cases where we initialize a pointer to an array temporary, and the
// pointer obviously outlives the temporary.
if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Entity.getType()->isPointerType() &&
InitializedEntityOutlivesFullExpression(Entity)) {
Expr *Init = Args[0];
Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
<< Init->getSourceRange();
}
QualType DestType = Entity.getType().getNonReferenceType();
// FIXME: Ugly hack around the fact that Entity.getType() is not
// the same as Entity.getDecl()->getType() in cases involving type merging,
// and we want latter when it makes sense.
if (ResultType)
*ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Entity.getType();
ExprResult CurInit((Expr *)nullptr);
// For initialization steps that start with a single initializer,
// grab the only argument out the Args and place it into the "current"
// initializer.
switch (Steps.front().Kind) {
// HLSL Change Starts
case SK_ListInitialization: {
// In vector constructor cases, we may synthesize an InitListExpr
assert(Args.size() == 1 || S.getLangOpts().HLSL);
CurInit = Args[0];
Expr* CurInitExpr = CurInit.get();
if (!CurInitExpr) return ExprError();
if (CurInitExpr->getStmtClass() != Stmt::StmtClass::InitListExprClass) {
assert(S.getLangOpts().HLSL);
for (unsigned i = 0; i < Args.size(); ++i) {
if (Args[i]->isLValue()) {
Args[i] = ImplicitCastExpr::Create(S.Context, Args[i]->getType(),
CK_LValueToRValue, Args[i], /*BasePath=*/0, VK_RValue);
}
}
InitListExpr *castInit = new (S.getASTContext())
InitListExpr(S.getASTContext(), Kind.getParenRange().getBegin(), Args,
Kind.getParenRange().getEnd());
castInit->sawVectorInitWithCXXFunctionalCastExpr(true);
CurInit = castInit;
}
break;
}
// HLSL Change Ends
case SK_ResolveAddressOfOverloadedFunction:
case SK_CastDerivedToBaseRValue:
case SK_CastDerivedToBaseXValue:
case SK_CastDerivedToBaseLValue:
case SK_BindReference:
case SK_BindReferenceToTemporary:
case SK_ExtraneousCopyToTemporary:
case SK_UserConversion:
case SK_QualificationConversionLValue:
case SK_QualificationConversionXValue:
case SK_QualificationConversionRValue:
case SK_AtomicConversion:
case SK_LValueToRValue:
case SK_ConversionSequence:
case SK_ConversionSequenceNoNarrowing:
case SK_UnwrapInitList:
case SK_RewrapInitList:
case SK_CAssignment:
case SK_StringInit:
case SK_ObjCObjectConversion:
case SK_ArrayInit:
case SK_ParenthesizedArrayInit:
case SK_PassByIndirectCopyRestore:
case SK_PassByIndirectRestore:
case SK_ProduceObjCObject:
case SK_StdInitializerList:
case SK_OCLSamplerInit:
case SK_OCLZeroEvent: {
assert(Args.size() == 1);
CurInit = Args[0];
if (!CurInit.get()) return ExprError();
break;
}
case SK_ConstructorInitialization:
case SK_ConstructorInitializationFromList:
case SK_StdInitializerListConstructorCall:
case SK_ZeroInitialization:
break;
}
// Walk through the computed steps for the initialization sequence,
// performing the specified conversions along the way.
bool ConstructorInitRequiresZeroInit = false;
for (step_iterator Step = step_begin(), StepEnd = step_end();
Step != StepEnd; ++Step) {
if (CurInit.isInvalid())
return ExprError();
QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
switch (Step->Kind) {
case SK_ResolveAddressOfOverloadedFunction:
// Overload resolution determined which function invoke; update the
// initializer to reflect that choice.
S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
return ExprError();
CurInit = S.FixOverloadedFunctionReference(CurInit,
Step->Function.FoundDecl,
Step->Function.Function);
break;
case SK_CastDerivedToBaseRValue:
case SK_CastDerivedToBaseXValue:
case SK_CastDerivedToBaseLValue: {
// We have a derived-to-base cast that produces either an rvalue or an
// lvalue. Perform that cast.
CXXCastPath BasePath;
// Casts to inaccessible base classes are allowed with C-style casts.
bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
CurInit.get()->getLocStart(),
CurInit.get()->getSourceRange(),
&BasePath, IgnoreBaseAccess))
return ExprError();
ExprValueKind VK =
Step->Kind == SK_CastDerivedToBaseLValue ?
VK_LValue :
(Step->Kind == SK_CastDerivedToBaseXValue ?
VK_XValue :
VK_RValue);
CurInit =
ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
CurInit.get(), &BasePath, VK);
break;
}
case SK_BindReference:
// References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
if (CurInit.get()->refersToBitField()) {
// We don't necessarily have an unambiguous source bit-field.
FieldDecl *BitField = CurInit.get()->getSourceBitField();
S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
<< Entity.getType().isVolatileQualified()
<< (BitField ? BitField->getDeclName() : DeclarationName())
<< (BitField != nullptr)
<< CurInit.get()->getSourceRange();
if (BitField)
S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
return ExprError();
}
if (CurInit.get()->refersToVectorElement()) {
// References cannot bind to vector elements.
S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
<< Entity.getType().isVolatileQualified()
<< CurInit.get()->getSourceRange();
PrintInitLocationNote(S, Entity);
return ExprError();
}
// Reference binding does not have any corresponding ASTs.
// Check exception specifications
if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
return ExprError();
// Even though we didn't materialize a temporary, the binding may still
// extend the lifetime of a temporary. This happens if we bind a reference
// to the result of a cast to reference type.
if (const InitializedEntity *ExtendingEntity =
getEntityForTemporaryLifetimeExtension(&Entity))
if (performReferenceExtension(CurInit.get(), ExtendingEntity))
warnOnLifetimeExtension(S, Entity, CurInit.get(),
/*IsInitializerList=*/false,
ExtendingEntity->getDecl());
break;
case SK_BindReferenceToTemporary: {
// Make sure the "temporary" is actually an rvalue.
assert(CurInit.get()->isRValue() && "not a temporary");
// Check exception specifications
if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
return ExprError();
// Materialize the temporary into memory.
MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Entity.getType().getNonReferenceType(), CurInit.get(),
Entity.getType()->isLValueReferenceType());
// Maybe lifetime-extend the temporary's subobjects to match the
// entity's lifetime.
if (const InitializedEntity *ExtendingEntity =
getEntityForTemporaryLifetimeExtension(&Entity))
if (performReferenceExtension(MTE, ExtendingEntity))
warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
ExtendingEntity->getDecl());
// If we're binding to an Objective-C object that has lifetime, we
// need cleanups. Likewise if we're extending this temporary to automatic
// storage duration -- we need to register its cleanup during the
// full-expression's cleanups.
if ((S.getLangOpts().ObjCAutoRefCount &&
MTE->getType()->isObjCLifetimeType()) ||
(MTE->getStorageDuration() == SD_Automatic &&
MTE->getType().isDestructedType()))
S.ExprNeedsCleanups = true;
CurInit = MTE;
break;
}
case SK_ExtraneousCopyToTemporary:
CurInit = CopyObject(S, Step->Type, Entity, CurInit,
/*IsExtraneousCopy=*/true);
break;
case SK_UserConversion: {
// We have a user-defined conversion that invokes either a constructor
// or a conversion function.
CastKind CastKind;
bool IsCopy = false;
FunctionDecl *Fn = Step->Function.Function;
DeclAccessPair FoundFn = Step->Function.FoundDecl;
bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
bool CreatedObject = false;
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
// Build a call to the selected constructor.
SmallVector<Expr*, 8> ConstructorArgs;
SourceLocation Loc = CurInit.get()->getLocStart();
CurInit.get(); // Ownership transferred into MultiExprArg, below.
// Determine the arguments required to actually perform the constructor
// call.
Expr *Arg = CurInit.get();
if (S.CompleteConstructorCall(Constructor,
MultiExprArg(&Arg, 1),
Loc, ConstructorArgs))
return ExprError();
// Build an expression that constructs a temporary.
CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
ConstructorArgs,
HadMultipleCandidates,
/*ListInit*/ false,
/*StdInitListInit*/ false,
/*ZeroInit*/ false,
CXXConstructExpr::CK_Complete,
SourceRange());
if (CurInit.isInvalid())
return ExprError();
S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
FoundFn.getAccess());
if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
return ExprError();
CastKind = CK_ConstructorConversion;
QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
S.IsDerivedFrom(SourceType, Class))
IsCopy = true;
CreatedObject = true;
} else {
// Build a call to the conversion function.
CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
FoundFn);
if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
return ExprError();
// FIXME: Should we move this initialization into a separate
// derived-to-base conversion? I believe the answer is "no", because
// we don't want to turn off access control here for c-style casts.
ExprResult CurInitExprRes =
S.PerformObjectArgumentInitialization(CurInit.get(),
/*Qualifier=*/nullptr,
FoundFn, Conversion);
if(CurInitExprRes.isInvalid())
return ExprError();
CurInit = CurInitExprRes;
// Build the actual call to the conversion function.
CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
HadMultipleCandidates);
if (CurInit.isInvalid() || !CurInit.get())
return ExprError();
CastKind = CK_UserDefinedConversion;
CreatedObject = Conversion->getReturnType()->isRecordType();
}
bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
QualType T = CurInit.get()->getType();
if (const RecordType *Record = T->getAs<RecordType>()) {
CXXDestructorDecl *Destructor
= S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
S.PDiag(diag::err_access_dtor_temp) << T);
S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
return ExprError();
}
}
CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
CastKind, CurInit.get(), nullptr,
CurInit.get()->getValueKind());
if (MaybeBindToTemp)
CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
if (RequiresCopy)
CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
CurInit, /*IsExtraneousCopy=*/false);
break;
}
case SK_QualificationConversionLValue:
case SK_QualificationConversionXValue:
case SK_QualificationConversionRValue: {
// Perform a qualification conversion; these can never go wrong.
ExprValueKind VK =
Step->Kind == SK_QualificationConversionLValue ?
VK_LValue :
(Step->Kind == SK_QualificationConversionXValue ?
VK_XValue :
VK_RValue);
CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
break;
}
case SK_AtomicConversion: {
assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
CK_NonAtomicToAtomic, VK_RValue);
break;
}
case SK_LValueToRValue: {
assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
CK_LValueToRValue, CurInit.get(),
/*BasePath=*/nullptr, VK_RValue);
break;
}
case SK_ConversionSequence:
case SK_ConversionSequenceNoNarrowing: {
Sema::CheckedConversionKind CCK
= Kind.isCStyleCast()? Sema::CCK_CStyleCast
: Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
: Kind.isExplicitCast()? Sema::CCK_OtherCast
: Sema::CCK_ImplicitConversion;
ExprResult CurInitExprRes =
S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
getAssignmentAction(Entity), CCK);
if (CurInitExprRes.isInvalid())
return ExprError();
CurInit = CurInitExprRes;
if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
CurInit.get());
break;
}
case SK_ListInitialization: {
InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
// If we're not initializing the top-level entity, we need to create an
// InitializeTemporary entity for our target type.
QualType Ty = Step->Type;
bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
// HLSL Change Starts - all analysis done - TODO semantic changes for IR
if (S.getLangOpts().HLSL) {
CurInit.get();
InitList->setType(InitEntity.getType());
CurInit = shouldBindAsTemporary(InitEntity)
? S.MaybeBindToTemporary(InitList)
: InitList;
// Hack: We must update *ResultType if available in order to set the
// bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
// Worst case: 'const int (&arref)[] = {1, 2, 3};'.
if (ResultType &&
ResultType->getNonReferenceType()->isIncompleteArrayType()) {
const IncompleteArrayType *IncompleteAT =
S.getASTContext().getAsIncompleteArrayType(
ResultType->getNonReferenceType());
QualType EltTy = IncompleteAT->getElementType();
unsigned arraySize = hlsl::CaculateInitListArraySizeForHLSL(&S, InitList, EltTy);
if (arraySize) {
llvm::APInt Size(
/*numBits=*/32, arraySize);
QualType AT = S.getASTContext().getConstantArrayType(
EltTy, Size, ArrayType::ArraySizeModifier::Normal,
/*IndexTypeQuals=*/0);
*ResultType = AT;
InitList->setType(AT);
}
}
} else { // HLSL Change Ends code below is conditional
InitListChecker PerformInitList(S, InitEntity, Kind, // HLSL Change - added Kind
InitList, Ty, /*VerifyOnly=*/false);
if (PerformInitList.HadError())
return ExprError();
// Hack: We must update *ResultType if available in order to set the
// bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
// Worst case: 'const int (&arref)[] = {1, 2, 3};'.
if (ResultType &&
ResultType->getNonReferenceType()->isIncompleteArrayType()) {
if ((*ResultType)->isRValueReferenceType())
Ty = S.Context.getRValueReferenceType(Ty);
else if ((*ResultType)->isLValueReferenceType())
Ty = S.Context.getLValueReferenceType(Ty,
(*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
*ResultType = Ty;
}
InitListExpr *StructuredInitList =
PerformInitList.getFullyStructuredList();
CurInit.get();
CurInit = shouldBindAsTemporary(InitEntity)
? S.MaybeBindToTemporary(StructuredInitList)
: StructuredInitList;
} // HLSL Change - end conditional
break;
}
case SK_ConstructorInitializationFromList: {
// When an initializer list is passed for a parameter of type "reference
// to object", we don't get an EK_Temporary entity, but instead an
// EK_Parameter entity with reference type.
// FIXME: This is a hack. What we really should do is create a user
// conversion step for this case, but this makes it considerably more
// complicated. For now, this will do.
InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
Entity.getType().getNonReferenceType());
bool UseTemporary = Entity.getType()->isReferenceType();
assert(Args.size() == 1 && "expected a single argument for list init");
InitListExpr *InitList = cast<InitListExpr>(Args[0]);
S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
<< InitList->getSourceRange();
MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
Entity,
Kind, Arg, *Step,
ConstructorInitRequiresZeroInit,
/*IsListInitialization*/true,
/*IsStdInitListInit*/false,
InitList->getLBraceLoc(),
InitList->getRBraceLoc());
break;
}
case SK_UnwrapInitList:
CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
break;
case SK_RewrapInitList: {
Expr *E = CurInit.get();
InitListExpr *Syntactic = Step->WrappingSyntacticList;
InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
ILE->setSyntacticForm(Syntactic);
ILE->setType(E->getType());
ILE->setValueKind(E->getValueKind());
CurInit = ILE;
break;
}
case SK_ConstructorInitialization:
case SK_StdInitializerListConstructorCall: {
// When an initializer list is passed for a parameter of type "reference
// to object", we don't get an EK_Temporary entity, but instead an
// EK_Parameter entity with reference type.
// FIXME: This is a hack. What we really should do is create a user
// conversion step for this case, but this makes it considerably more
// complicated. For now, this will do.
InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
Entity.getType().getNonReferenceType());
bool UseTemporary = Entity.getType()->isReferenceType();
bool IsStdInitListInit =
Step->Kind == SK_StdInitializerListConstructorCall;
CurInit = PerformConstructorInitialization(
S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
ConstructorInitRequiresZeroInit,
/*IsListInitialization*/IsStdInitListInit,
/*IsStdInitListInitialization*/IsStdInitListInit,
/*LBraceLoc*/SourceLocation(),
/*RBraceLoc*/SourceLocation());
break;
}
case SK_ZeroInitialization: {
step_iterator NextStep = Step;
++NextStep;
if (NextStep != StepEnd &&
(NextStep->Kind == SK_ConstructorInitialization ||
NextStep->Kind == SK_ConstructorInitializationFromList)) {
// The need for zero-initialization is recorded directly into
// the call to the object's constructor within the next step.
ConstructorInitRequiresZeroInit = true;
} else if (Kind.getKind() == InitializationKind::IK_Value &&
S.getLangOpts().CPlusPlus &&
!Kind.isImplicitValueInit()) {
TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
if (!TSInfo)
TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Kind.getRange().getBegin());
CurInit = new (S.Context) CXXScalarValueInitExpr(
TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
Kind.getRange().getEnd());
} else {
CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
}
break;
}
case SK_CAssignment: {
QualType SourceType = CurInit.get()->getType();
ExprResult Result = CurInit;
Sema::AssignConvertType ConvTy =
S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
if (Result.isInvalid())
return ExprError();
CurInit = Result;
// If this is a call, allow conversion to a transparent union.
ExprResult CurInitExprRes = CurInit;
if (ConvTy != Sema::Compatible &&
Entity.isParameterKind() &&
S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
== Sema::Compatible)
ConvTy = Sema::Compatible;
if (CurInitExprRes.isInvalid())
return ExprError();
CurInit = CurInitExprRes;
bool Complained;
if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
Step->Type, SourceType,
CurInit.get(),
getAssignmentAction(Entity, true),
&Complained)) {
PrintInitLocationNote(S, Entity);
return ExprError();
} else if (Complained)
PrintInitLocationNote(S, Entity);
break;
}
case SK_StringInit: {
QualType Ty = Step->Type;
CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
S.Context.getAsArrayType(Ty), S);
break;
}
case SK_ObjCObjectConversion:
CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
CK_ObjCObjectLValueCast,
CurInit.get()->getValueKind());
break;
case SK_ArrayInit:
// Okay: we checked everything before creating this step. Note that
// this is a GNU extension.
S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
<< Step->Type << CurInit.get()->getType()
<< CurInit.get()->getSourceRange();
// If the destination type is an incomplete array type, update the
// type accordingly.
if (ResultType) {
if (const IncompleteArrayType *IncompleteDest
= S.Context.getAsIncompleteArrayType(Step->Type)) {
if (const ConstantArrayType *ConstantSource
= S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
*ResultType = S.Context.getConstantArrayType(
IncompleteDest->getElementType(),
ConstantSource->getSize(),
ArrayType::Normal, 0);
}
}
}
break;
case SK_ParenthesizedArrayInit:
// Okay: we checked everything before creating this step. Note that
// this is a GNU extension.
S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
<< CurInit.get()->getSourceRange();
break;
case SK_PassByIndirectCopyRestore:
case SK_PassByIndirectRestore:
checkIndirectCopyRestoreSource(S, CurInit.get());
CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
CurInit.get(), Step->Type,
Step->Kind == SK_PassByIndirectCopyRestore);
break;
case SK_ProduceObjCObject:
CurInit =
ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
CurInit.get(), nullptr, VK_RValue);
break;
case SK_StdInitializerList: {
S.Diag(CurInit.get()->getExprLoc(),
diag::warn_cxx98_compat_initializer_list_init)
<< CurInit.get()->getSourceRange();
// Materialize the temporary into memory.
MaterializeTemporaryExpr *MTE = new (S.Context)
MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
/*BoundToLvalueReference=*/false);
// Maybe lifetime-extend the array temporary's subobjects to match the
// entity's lifetime.
if (const InitializedEntity *ExtendingEntity =
getEntityForTemporaryLifetimeExtension(&Entity))
if (performReferenceExtension(MTE, ExtendingEntity))
warnOnLifetimeExtension(S, Entity, CurInit.get(),
/*IsInitializerList=*/true,
ExtendingEntity->getDecl());
// Wrap it in a construction of a std::initializer_list<T>.
CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
// Bind the result, in case the library has given initializer_list a
// non-trivial destructor.
if (shouldBindAsTemporary(Entity))
CurInit = S.MaybeBindToTemporary(CurInit.get());
break;
}
case SK_OCLSamplerInit: {
assert(Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.");
QualType SourceType = CurInit.get()->getType();
if (Entity.isParameterKind()) {
if (!SourceType->isSamplerT())
S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
<< SourceType;
} else if (Entity.getKind() != InitializedEntity::EK_Variable) {
llvm_unreachable("Invalid EntityKind!");
}
break;
}
case SK_OCLZeroEvent: {
assert(Step->Type->isEventT() &&
"Event initialization on non-event type.");
CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
CK_ZeroToOCLEvent,
CurInit.get()->getValueKind());
break;
}
}
}
// Diagnose non-fatal problems with the completed initialization.
if (Entity.getKind() == InitializedEntity::EK_Member &&
cast<FieldDecl>(Entity.getDecl())->isBitField())
S.CheckBitFieldInitialization(Kind.getLocation(),
cast<FieldDecl>(Entity.getDecl()),
CurInit.get());
// Check for std::move on construction.
if (const Expr *E = CurInit.get()) {
CheckMoveOnConstruction(S, E,
Entity.getKind() == InitializedEntity::EK_Result);
}
return CurInit;
}
/// Somewhere within T there is an uninitialized reference subobject.
/// Dig it out and diagnose it.
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
QualType T) {
if (T->isReferenceType()) {
S.Diag(Loc, diag::err_reference_without_init)
<< T.getNonReferenceType();
return true;
}
CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
if (!RD || !RD->hasUninitializedReferenceMember())
return false;
for (const auto *FI : RD->fields()) {
if (FI->isUnnamedBitfield())
continue;
if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
S.Diag(Loc, diag::note_value_initialization_here) << RD;
return true;
}
}
for (const auto &BI : RD->bases()) {
if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
S.Diag(Loc, diag::note_value_initialization_here) << RD;
return true;
}
}
return false;
}
//===----------------------------------------------------------------------===//
// Diagnose initialization failures
//===----------------------------------------------------------------------===//
/// Emit notes associated with an initialization that failed due to a
/// "simple" conversion failure.
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
Expr *op) {
QualType destType = entity.getType();
if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
op->getType()->isObjCObjectPointerType()) {
// Emit a possible note about the conversion failing because the
// operand is a message send with a related result type.
S.EmitRelatedResultTypeNote(op);
// Emit a possible note about a return failing because we're
// expecting a related result type.
if (entity.getKind() == InitializedEntity::EK_Result)
S.EmitRelatedResultTypeNoteForReturn(destType);
}
}
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
const InitializationKind &Kind, // HLSL Change - added Kind
InitListExpr *InitList) {
QualType DestType = Entity.getType();
QualType E;
if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
QualType ArrayType = S.Context.getConstantArrayType(
E.withConst(),
llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
InitList->getNumInits()),
clang::ArrayType::Normal, 0);
InitializedEntity HiddenArray =
InitializedEntity::InitializeTemporary(ArrayType);
return diagnoseListInit(S, HiddenArray, Kind, InitList); // HLSL Change - added Kind
}
if (DestType->isReferenceType()) {
// A list-initialization failure for a reference means that we tried to
// create a temporary of the inner type (per [dcl.init.list]p3.6) and the
// inner initialization failed.
QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), Kind, InitList);
SourceLocation Loc = InitList->getLocStart();
if (auto *D = Entity.getDecl())
Loc = D->getLocation();
S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
return;
}
InitListChecker DiagnoseInitList(S, Entity, Kind, InitList, DestType, // HLSL Change - added Kind
/*VerifyOnly=*/false);
assert(DiagnoseInitList.HadError() &&
"Inconsistent init list check result.");
}
bool InitializationSequence::Diagnose(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
ArrayRef<Expr *> Args) {
if (!Failed())
return false;
QualType DestType = Entity.getType();
switch (Failure) {
case FK_TooManyInitsForReference:
// FIXME: Customize for the initialized entity?
if (Args.empty()) {
// Dig out the reference subobject which is uninitialized and diagnose it.
// If this is value-initialization, this could be nested some way within
// the target type.
assert(Kind.getKind() == InitializationKind::IK_Value ||
DestType->isReferenceType());
bool Diagnosed =
DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
(void)Diagnosed;
} else // FIXME: diagnostic below could be better!
S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
<< SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
break;
case FK_ArrayNeedsInitList:
S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
break;
case FK_ArrayNeedsInitListOrStringLiteral:
S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
break;
case FK_ArrayNeedsInitListOrWideStringLiteral:
S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
break;
case FK_NarrowStringIntoWideCharArray:
S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
break;
case FK_WideStringIntoCharArray:
S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
break;
case FK_IncompatWideStringIntoWideChar:
S.Diag(Kind.getLocation(),
diag::err_array_init_incompat_wide_string_into_wchar);
break;
case FK_ArrayTypeMismatch:
case FK_NonConstantArrayInit:
S.Diag(Kind.getLocation(),
(Failure == FK_ArrayTypeMismatch
? diag::err_array_init_different_type
: diag::err_array_init_non_constant_array))
<< DestType.getNonReferenceType()
<< Args[0]->getType()
<< Args[0]->getSourceRange();
break;
case FK_VariableLengthArrayHasInitializer:
S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
<< Args[0]->getSourceRange();
break;
case FK_AddressOfOverloadFailed: {
DeclAccessPair Found;
S.ResolveAddressOfOverloadedFunction(Args[0],
DestType.getNonReferenceType(),
true,
Found);
break;
}
case FK_ReferenceInitOverloadFailed:
case FK_UserConversionOverloadFailed:
switch (FailedOverloadResult) {
case OR_Ambiguous:
if (Failure == FK_UserConversionOverloadFailed)
S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
<< Args[0]->getType() << DestType
<< Args[0]->getSourceRange();
else
S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
<< DestType << Args[0]->getType()
<< Args[0]->getSourceRange();
FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
break;
case OR_No_Viable_Function:
if (!S.RequireCompleteType(Kind.getLocation(),
DestType.getNonReferenceType(),
diag::err_typecheck_nonviable_condition_incomplete,
Args[0]->getType(), Args[0]->getSourceRange()))
S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
<< Args[0]->getType() << Args[0]->getSourceRange()
<< DestType.getNonReferenceType();
FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
break;
case OR_Deleted: {
S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
<< Args[0]->getType() << DestType.getNonReferenceType()
<< Args[0]->getSourceRange();
OverloadCandidateSet::iterator Best;
OverloadingResult Ovl
= FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
true);
if (Ovl == OR_Deleted) {
S.NoteDeletedFunction(Best->Function);
} else {
llvm_unreachable("Inconsistent overload resolution?");
}
break;
}
case OR_Success:
llvm_unreachable("Conversion did not fail!");
}
break;
case FK_NonConstLValueReferenceBindingToTemporary:
if (isa<InitListExpr>(Args[0])) {
S.Diag(Kind.getLocation(),
diag::err_lvalue_reference_bind_to_initlist)
<< DestType.getNonReferenceType().isVolatileQualified()
<< DestType.getNonReferenceType()
<< Args[0]->getSourceRange();
break;
}
// Intentional fallthrough
case FK_NonConstLValueReferenceBindingToUnrelated:
S.Diag(Kind.getLocation(),
Failure == FK_NonConstLValueReferenceBindingToTemporary
? diag::err_lvalue_reference_bind_to_temporary
: diag::err_lvalue_reference_bind_to_unrelated)
<< DestType.getNonReferenceType().isVolatileQualified()
<< DestType.getNonReferenceType()
<< Args[0]->getType()
<< Args[0]->getSourceRange();
break;
case FK_RValueReferenceBindingToLValue:
S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
<< DestType.getNonReferenceType() << Args[0]->getType()
<< Args[0]->getSourceRange();
break;
case FK_ReferenceInitDropsQualifiers: {
QualType SourceType = Args[0]->getType();
QualType NonRefType = DestType.getNonReferenceType();
Qualifiers DroppedQualifiers =
SourceType.getQualifiers() - NonRefType.getQualifiers();
S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
<< SourceType
<< NonRefType
<< DroppedQualifiers.getCVRQualifiers()
<< Args[0]->getSourceRange();
break;
}
case FK_ReferenceInitFailed:
S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
<< DestType.getNonReferenceType()
<< Args[0]->isLValue()
<< Args[0]->getType()
<< Args[0]->getSourceRange();
emitBadConversionNotes(S, Entity, Args[0]);
break;
case FK_ConversionFailed: {
QualType FromType = Args[0]->getType();
PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
<< (int)Entity.getKind()
<< DestType
<< Args[0]->isLValue()
<< FromType
<< Args[0]->getSourceRange();
S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
S.Diag(Kind.getLocation(), PDiag);
emitBadConversionNotes(S, Entity, Args[0]);
break;
}
case FK_ConversionFromPropertyFailed:
// No-op. This error has already been reported.
break;
case FK_TooManyInitsForScalar: {
SourceRange R;
auto *InitList = dyn_cast<InitListExpr>(Args[0]);
if (InitList && InitList->getNumInits() == 1)
R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
else
R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
R.setBegin(S.getLocForEndOfToken(R.getBegin()));
if (Kind.isCStyleOrFunctionalCast())
S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
<< R;
else
S.Diag(Kind.getLocation(), diag::err_excess_initializers)
<< /*scalar=*/2 << R;
break;
}
case FK_ReferenceBindingToInitList:
S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
<< DestType.getNonReferenceType() << Args[0]->getSourceRange();
break;
case FK_InitListBadDestinationType:
S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
<< (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
break;
case FK_ListConstructorOverloadFailed:
case FK_ConstructorOverloadFailed: {
SourceRange ArgsRange;
if (Args.size())
ArgsRange = SourceRange(Args.front()->getLocStart(),
Args.back()->getLocEnd());
if (Failure == FK_ListConstructorOverloadFailed) {
assert(Args.size() == 1 &&
"List construction from other than 1 argument.");
InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
}
// FIXME: Using "DestType" for the entity we're printing is probably
// bad.
switch (FailedOverloadResult) {
case OR_Ambiguous:
S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
<< DestType << ArgsRange;
FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
break;
case OR_No_Viable_Function:
if (Kind.getKind() == InitializationKind::IK_Default &&
(Entity.getKind() == InitializedEntity::EK_Base ||
Entity.getKind() == InitializedEntity::EK_Member) &&
isa<CXXConstructorDecl>(S.CurContext)) {
// This is implicit default initialization of a member or
// base within a constructor. If no viable function was
// found, notify the user that she needs to explicitly
// initialize this base/member.
CXXConstructorDecl *Constructor
= cast<CXXConstructorDecl>(S.CurContext);
if (Entity.getKind() == InitializedEntity::EK_Base) {
S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
<< (Constructor->getInheritedConstructor() ? 2 :
Constructor->isImplicit() ? 1 : 0)
<< S.Context.getTypeDeclType(Constructor->getParent())
<< /*base=*/0
<< Entity.getType();
RecordDecl *BaseDecl
= Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
->getDecl();
S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
<< S.Context.getTagDeclType(BaseDecl);
} else {
S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
<< (Constructor->getInheritedConstructor() ? 2 :
Constructor->isImplicit() ? 1 : 0)
<< S.Context.getTypeDeclType(Constructor->getParent())
<< /*member=*/1
<< Entity.getName();
S.Diag(Entity.getDecl()->getLocation(),
diag::note_member_declared_at);
if (const RecordType *Record
= Entity.getType()->getAs<RecordType>())
S.Diag(Record->getDecl()->getLocation(),
diag::note_previous_decl)
<< S.Context.getTagDeclType(Record->getDecl());
}
break;
}
S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
<< DestType << ArgsRange;
FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
break;
case OR_Deleted: {
OverloadCandidateSet::iterator Best;
OverloadingResult Ovl
= FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
if (Ovl != OR_Deleted) {
S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
<< true << DestType << ArgsRange;
llvm_unreachable("Inconsistent overload resolution?");
break;
}
// If this is a defaulted or implicitly-declared function, then
// it was implicitly deleted. Make it clear that the deletion was
// implicit.
if (S.isImplicitlyDeleted(Best->Function))
S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
<< S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
<< DestType << ArgsRange;
else
S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
<< true << DestType << ArgsRange;
S.NoteDeletedFunction(Best->Function);
break;
}
case OR_Success:
llvm_unreachable("Conversion did not fail!");
}
}
break;
case FK_DefaultInitOfConst:
if (Entity.getKind() == InitializedEntity::EK_Member &&
isa<CXXConstructorDecl>(S.CurContext)) {
// This is implicit default-initialization of a const member in
// a constructor. Complain that it needs to be explicitly
// initialized.
CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
<< (Constructor->getInheritedConstructor() ? 2 :
Constructor->isImplicit() ? 1 : 0)
<< S.Context.getTypeDeclType(Constructor->getParent())
<< /*const=*/1
<< Entity.getName();
S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
<< Entity.getName();
} else {
S.Diag(Kind.getLocation(), diag::err_default_init_const)
<< DestType << (bool)DestType->getAs<RecordType>();
}
break;
case FK_Incomplete:
S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
diag::err_init_incomplete_type);
break;
case FK_ListInitializationFailed: {
// Run the init list checker again to emit diagnostics.
// HLSL Change Starts: allow for the possibility of having to construct an InitListExpr.
if (!S.getLangOpts().HLSL) {
InitListExpr *InitList = cast<InitListExpr>(Args[0]);
diagnoseListInit(S, Entity, Kind, InitList); // HLSL Change - added Kind
}
else {
// For HLSL, InitializeInitSequenceForHLSL should report error messages.
}
// HLSL Change Ends
break;
}
case FK_PlaceholderType: {
// FIXME: Already diagnosed!
break;
}
case FK_ExplicitConstructor: {
S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
<< Args[0]->getSourceRange();
OverloadCandidateSet::iterator Best;
OverloadingResult Ovl
= FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
(void)Ovl;
assert(Ovl == OR_Success && "Inconsistent overload resolution");
CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
break;
}
}
PrintInitLocationNote(S, Entity);
return true;
}
void InitializationSequence::dump(raw_ostream &OS) const {
switch (SequenceKind) {
case FailedSequence: {
OS << "Failed sequence: ";
switch (Failure) {
case FK_TooManyInitsForReference:
OS << "too many initializers for reference";
break;
case FK_ArrayNeedsInitList:
OS << "array requires initializer list";
break;
case FK_ArrayNeedsInitListOrStringLiteral:
OS << "array requires initializer list or string literal";
break;
case FK_ArrayNeedsInitListOrWideStringLiteral:
OS << "array requires initializer list or wide string literal";
break;
case FK_NarrowStringIntoWideCharArray:
OS << "narrow string into wide char array";
break;
case FK_WideStringIntoCharArray:
OS << "wide string into char array";
break;
case FK_IncompatWideStringIntoWideChar:
OS << "incompatible wide string into wide char array";
break;
case FK_ArrayTypeMismatch:
OS << "array type mismatch";
break;
case FK_NonConstantArrayInit:
OS << "non-constant array initializer";
break;
case FK_AddressOfOverloadFailed:
OS << "address of overloaded function failed";
break;
case FK_ReferenceInitOverloadFailed:
OS << "overload resolution for reference initialization failed";
break;
case FK_NonConstLValueReferenceBindingToTemporary:
OS << "non-const lvalue reference bound to temporary";
break;
case FK_NonConstLValueReferenceBindingToUnrelated:
OS << "non-const lvalue reference bound to unrelated type";
break;
case FK_RValueReferenceBindingToLValue:
OS << "rvalue reference bound to an lvalue";
break;
case FK_ReferenceInitDropsQualifiers:
OS << "reference initialization drops qualifiers";
break;
case FK_ReferenceInitFailed:
OS << "reference initialization failed";
break;
case FK_ConversionFailed:
OS << "conversion failed";
break;
case FK_ConversionFromPropertyFailed:
OS << "conversion from property failed";
break;
case FK_TooManyInitsForScalar:
OS << "too many initializers for scalar";
break;
case FK_ReferenceBindingToInitList:
OS << "referencing binding to initializer list";
break;
case FK_InitListBadDestinationType:
OS << "initializer list for non-aggregate, non-scalar type";
break;
case FK_UserConversionOverloadFailed:
OS << "overloading failed for user-defined conversion";
break;
case FK_ConstructorOverloadFailed:
OS << "constructor overloading failed";
break;
case FK_DefaultInitOfConst:
OS << "default initialization of a const variable";
break;
case FK_Incomplete:
OS << "initialization of incomplete type";
break;
case FK_ListInitializationFailed:
OS << "list initialization checker failure";
break;
case FK_VariableLengthArrayHasInitializer:
OS << "variable length array has an initializer";
break;
case FK_PlaceholderType:
OS << "initializer expression isn't contextually valid";
break;
case FK_ListConstructorOverloadFailed:
OS << "list constructor overloading failed";
break;
case FK_ExplicitConstructor:
OS << "list copy initialization chose explicit constructor";
break;
}
OS << '\n';
return;
}
case DependentSequence:
OS << "Dependent sequence\n";
return;
case NormalSequence:
OS << "Normal sequence: ";
break;
}
for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
if (S != step_begin()) {
OS << " -> ";
}
switch (S->Kind) {
case SK_ResolveAddressOfOverloadedFunction:
OS << "resolve address of overloaded function";
break;
case SK_CastDerivedToBaseRValue:
OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
break;
case SK_CastDerivedToBaseXValue:
OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
break;
case SK_CastDerivedToBaseLValue:
OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
break;
case SK_BindReference:
OS << "bind reference to lvalue";
break;
case SK_BindReferenceToTemporary:
OS << "bind reference to a temporary";
break;
case SK_ExtraneousCopyToTemporary:
OS << "extraneous C++03 copy to temporary";
break;
case SK_UserConversion:
OS << "user-defined conversion via " << *S->Function.Function;
break;
case SK_QualificationConversionRValue:
OS << "qualification conversion (rvalue)";
break;
case SK_QualificationConversionXValue:
OS << "qualification conversion (xvalue)";
break;
case SK_QualificationConversionLValue:
OS << "qualification conversion (lvalue)";
break;
case SK_AtomicConversion:
OS << "non-atomic-to-atomic conversion";
break;
case SK_LValueToRValue:
OS << "load (lvalue to rvalue)";
break;
case SK_ConversionSequence:
OS << "implicit conversion sequence (";
S->ICS->dump(); // FIXME: use OS
OS << ")";
break;
case SK_ConversionSequenceNoNarrowing:
OS << "implicit conversion sequence with narrowing prohibited (";
S->ICS->dump(); // FIXME: use OS
OS << ")";
break;
case SK_ListInitialization:
OS << "list aggregate initialization";
break;
case SK_UnwrapInitList:
OS << "unwrap reference initializer list";
break;
case SK_RewrapInitList:
OS << "rewrap reference initializer list";
break;
case SK_ConstructorInitialization:
OS << "constructor initialization";
break;
case SK_ConstructorInitializationFromList:
OS << "list initialization via constructor";
break;
case SK_ZeroInitialization:
OS << "zero initialization";
break;
case SK_CAssignment:
OS << "C assignment";
break;
case SK_StringInit:
OS << "string initialization";
break;
case SK_ObjCObjectConversion:
OS << "Objective-C object conversion";
break;
case SK_ArrayInit:
OS << "array initialization";
break;
case SK_ParenthesizedArrayInit:
OS << "parenthesized array initialization";
break;
case SK_PassByIndirectCopyRestore:
OS << "pass by indirect copy and restore";
break;
case SK_PassByIndirectRestore:
OS << "pass by indirect restore";
break;
case SK_ProduceObjCObject:
OS << "Objective-C object retension";
break;
case SK_StdInitializerList:
OS << "std::initializer_list from initializer list";
break;
case SK_StdInitializerListConstructorCall:
OS << "list initialization from std::initializer_list";
break;
case SK_OCLSamplerInit:
OS << "OpenCL sampler_t from integer constant";
break;
case SK_OCLZeroEvent:
OS << "OpenCL event_t from zero";
break;
}
OS << " [" << S->Type.getAsString() << ']';
}
OS << '\n';
}
void InitializationSequence::dump() const {
dump(llvm::errs());
}
static void DiagnoseNarrowingInInitList(Sema &S,
const ImplicitConversionSequence &ICS,
QualType PreNarrowingType,
QualType EntityType,
const Expr *PostInit) {
const StandardConversionSequence *SCS = nullptr;
switch (ICS.getKind()) {
case ImplicitConversionSequence::StandardConversion:
SCS = &ICS.Standard;
break;
case ImplicitConversionSequence::UserDefinedConversion:
SCS = &ICS.UserDefined.After;
break;
case ImplicitConversionSequence::AmbiguousConversion:
case ImplicitConversionSequence::EllipsisConversion:
case ImplicitConversionSequence::BadConversion:
return;
}
// C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
APValue ConstantValue;
QualType ConstantType;
switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
ConstantType)) {
case NK_Not_Narrowing:
// No narrowing occurred.
return;
case NK_Type_Narrowing:
// This was a floating-to-integer conversion, which is always considered a
// narrowing conversion even if the value is a constant and can be
// represented exactly as an integer.
S.Diag(PostInit->getLocStart(),
(S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
? diag::warn_init_list_type_narrowing
: diag::ext_init_list_type_narrowing)
<< PostInit->getSourceRange()
<< PreNarrowingType.getLocalUnqualifiedType()
<< EntityType.getLocalUnqualifiedType();
break;
case NK_Constant_Narrowing:
// A constant value was narrowed.
S.Diag(PostInit->getLocStart(),
(S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
? diag::warn_init_list_constant_narrowing
: diag::ext_init_list_constant_narrowing)
<< PostInit->getSourceRange()
<< ConstantValue.getAsString(S.getASTContext(), ConstantType)
<< EntityType.getLocalUnqualifiedType();
break;
case NK_Variable_Narrowing:
// A variable's value may have been narrowed.
S.Diag(PostInit->getLocStart(),
(S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
? diag::warn_init_list_variable_narrowing
: diag::ext_init_list_variable_narrowing)
<< PostInit->getSourceRange()
<< PreNarrowingType.getLocalUnqualifiedType()
<< EntityType.getLocalUnqualifiedType();
break;
}
SmallString<128> StaticCast;
llvm::raw_svector_ostream OS(StaticCast);
OS << "static_cast<";
if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
// It's important to use the typedef's name if there is one so that the
// fixit doesn't break code using types like int64_t.
//
// FIXME: This will break if the typedef requires qualification. But
// getQualifiedNameAsString() includes non-machine-parsable components.
OS << *TT->getDecl();
} else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
OS << BT->getName(S.getLangOpts());
else {
// Oops, we didn't find the actual type of the variable. Don't emit a fixit
// with a broken cast.
return;
}
OS << ">(";
S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
<< PostInit->getSourceRange()
<< FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
<< FixItHint::CreateInsertion(
S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
}
//===----------------------------------------------------------------------===//
// Initialization helper functions
//===----------------------------------------------------------------------===//
bool
Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init) {
if (Init.isInvalid())
return false;
Expr *InitE = Init.get();
assert(InitE && "No initialization expression");
InitializationKind Kind
= InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
InitializationSequence Seq(*this, Entity, Kind, InitE);
return !Seq.Failed();
}
ExprResult
Sema::PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList,
bool AllowExplicit) {
if (Init.isInvalid())
return ExprError();
Expr *InitE = Init.get();
assert(InitE && "No initialization expression?");
if (EqualLoc.isInvalid())
EqualLoc = InitE->getLocStart();
InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
EqualLoc,
AllowExplicit);
InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
return Result;
}
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2020 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/vulkan/vulkan_shader.h"
#include "third_party/fmt/include/fmt/format.h"
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/ui/vulkan/vulkan_device.h"
#include "xenia/ui/vulkan/vulkan_util.h"
namespace xe {
namespace gpu {
namespace vulkan {
using xe::ui::vulkan::CheckResult;
VulkanShader::VulkanShader(ui::vulkan::VulkanDevice* device,
xenos::ShaderType shader_type, uint64_t data_hash,
const uint32_t* dword_ptr, uint32_t dword_count)
: Shader(shader_type, data_hash, dword_ptr, dword_count), device_(device) {}
VulkanShader::VulkanTranslation::~VulkanTranslation() {
if (shader_module_) {
const VulkanShader& vulkan_shader = static_cast<VulkanShader&>(shader());
const ui::vulkan::VulkanDevice* device = vulkan_shader.device_;
const ui::vulkan::VulkanDevice::DeviceFunctions& dfn = device->dfn();
dfn.vkDestroyShaderModule(*device, shader_module_, nullptr);
shader_module_ = nullptr;
}
}
bool VulkanShader::VulkanTranslation::Prepare() {
assert_null(shader_module_);
assert_true(is_valid());
const VulkanShader& vulkan_shader = static_cast<VulkanShader&>(shader());
const ui::vulkan::VulkanDevice* device = vulkan_shader.device_;
const ui::vulkan::VulkanDevice::DeviceFunctions& dfn = device->dfn();
// Create the shader module.
VkShaderModuleCreateInfo shader_info;
shader_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shader_info.pNext = nullptr;
shader_info.flags = 0;
shader_info.codeSize = translated_binary().size();
shader_info.pCode =
reinterpret_cast<const uint32_t*>(translated_binary().data());
auto status =
dfn.vkCreateShaderModule(*device, &shader_info, nullptr, &shader_module_);
CheckResult(status, "vkCreateShaderModule");
char type_char;
switch (vulkan_shader.type()) {
case xenos::ShaderType::kVertex:
type_char = 'v';
break;
case xenos::ShaderType::kPixel:
type_char = 'p';
break;
default:
type_char = 'u';
}
device->DbgSetObjectName(uint64_t(shader_module_),
VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
fmt::format("S({}): {:016X}", type_char,
vulkan_shader.ucode_data_hash()));
return status == VK_SUCCESS;
}
Shader::Translation* VulkanShader::CreateTranslationInstance(
uint64_t modification) {
return new VulkanTranslation(*this, modification);
}
} // namespace vulkan
} // namespace gpu
} // namespace xe
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#ifdef JUCE_AUDIO_PROCESSORS_H_INCLUDED
/* When you add this cpp file to your project, you mustn't include it in a file where you've
already included any other headers - just put it inside a file on its own, possibly with your config
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
header files that the compiler may be using.
*/
#error "Incorrect use of JUCE cpp file"
#endif
#define JUCE_CORE_INCLUDE_NATIVE_HEADERS 1
#define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
#define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
#define JUCE_GUI_BASICS_INCLUDE_SCOPED_THREAD_DPI_AWARENESS_SETTER 1
#include "juce_audio_processors.h"
#include <juce_gui_extra/juce_gui_extra.h>
//==============================================================================
#if JUCE_MAC
#if JUCE_SUPPORT_CARBON && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)
#include <Carbon/Carbon.h>
#include <juce_gui_extra/native/juce_mac_CarbonViewWrapperComponent.h>
#endif
#endif
#if (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_VST3) && JUCE_LINUX
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <sys/utsname.h>
#undef KeyPress
#endif
#if ! JUCE_WINDOWS && ! JUCE_MAC && ! JUCE_LINUX
#undef JUCE_PLUGINHOST_VST3
#define JUCE_PLUGINHOST_VST3 0
#endif
#if JUCE_PLUGINHOST_AU && (JUCE_MAC || JUCE_IOS)
#include <AudioUnit/AudioUnit.h>
#endif
//==============================================================================
namespace juce
{
#if JUCE_PLUGINHOST_VST || (JUCE_PLUGINHOST_LADSPA && JUCE_LINUX)
static bool arrayContainsPlugin (const OwnedArray<PluginDescription>& list,
const PluginDescription& desc)
{
for (auto* p : list)
if (p->isDuplicateOf (desc))
return true;
return false;
}
#endif
#if JUCE_WINDOWS
//==============================================================================
class HWNDComponentWithParent : public HWNDComponent,
private Timer
{
public:
HWNDComponentWithParent()
{
String className ("JUCE_");
className << String::toHexString (Time::getHighResolutionTicks());
HMODULE moduleHandle = (HMODULE) Process::getCurrentModuleInstanceHandle();
WNDCLASSEX wc = {};
wc.cbSize = sizeof (wc);
wc.lpfnWndProc = (WNDPROC) wndProc;
wc.cbWndExtra = 4;
wc.hInstance = moduleHandle;
wc.lpszClassName = className.toWideCharPointer();
atom = RegisterClassEx (&wc);
jassert (atom != 0);
hwnd = CreateWindow (getClassNameFromAtom(), L"HWNDComponentWithParent",
0, 0, 0, 0, 0,
nullptr, nullptr, moduleHandle, nullptr);
jassert (hwnd != nullptr);
setHWND (hwnd);
startTimer (30);
}
~HWNDComponentWithParent() override
{
if (IsWindow (hwnd))
DestroyWindow (hwnd);
UnregisterClass (getClassNameFromAtom(), nullptr);
}
private:
//==============================================================================
static LRESULT CALLBACK wndProc (HWND h, const UINT message, const WPARAM wParam, const LPARAM lParam)
{
if (message == WM_SHOWWINDOW && wParam == TRUE)
return 0;
return DefWindowProc (h, message, wParam, lParam);
}
void timerCallback() override
{
if (HWND child = getChildHWND())
{
stopTimer();
ShowWindow (child, SW_HIDE);
SetParent (child, NULL);
auto windowFlags = GetWindowLongPtr (child, -16);
windowFlags &= ~WS_CHILD;
windowFlags |= WS_POPUP;
SetWindowLongPtr (child, -16, windowFlags);
setHWND (child);
}
}
LPCTSTR getClassNameFromAtom() noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
HWND getChildHWND() const
{
if (HWND parent = (HWND) getHWND())
return GetWindow (parent, GW_CHILD);
return nullptr;
}
//==============================================================================
ATOM atom;
HWND hwnd;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentWithParent)
};
#elif JUCE_MAC || JUCE_IOS
#if JUCE_IOS
#define JUCE_IOS_MAC_VIEW UIView
using ViewComponentBaseClass = UIViewComponent;
#else
#define JUCE_IOS_MAC_VIEW NSView
using ViewComponentBaseClass = NSViewComponent;
#endif
//==============================================================================
struct AutoResizingNSViewComponent : public ViewComponentBaseClass,
private AsyncUpdater
{
void childBoundsChanged (Component*) override { triggerAsyncUpdate(); }
void handleAsyncUpdate() override { resizeToFitView(); }
};
//==============================================================================
struct AutoResizingNSViewComponentWithParent : public AutoResizingNSViewComponent,
private Timer
{
AutoResizingNSViewComponentWithParent()
{
JUCE_IOS_MAC_VIEW* v = [[JUCE_IOS_MAC_VIEW alloc] init];
setView (v);
[v release];
startTimer (30);
}
JUCE_IOS_MAC_VIEW* getChildView() const
{
if (JUCE_IOS_MAC_VIEW* parent = (JUCE_IOS_MAC_VIEW*) getView())
if ([[parent subviews] count] > 0)
return [[parent subviews] objectAtIndex: 0];
return nil;
}
void timerCallback() override
{
if (JUCE_IOS_MAC_VIEW* child = getChildView())
{
stopTimer();
setView (child);
}
}
};
#endif
} // namespace juce
#include "format/juce_AudioPluginFormat.cpp"
#include "format/juce_AudioPluginFormatManager.cpp"
#include "format_types/juce_LegacyAudioParameter.cpp"
#include "processors/juce_AudioProcessor.cpp"
#include "processors/juce_AudioPluginInstance.cpp"
#include "processors/juce_AudioProcessorEditor.cpp"
#include "processors/juce_AudioProcessorGraph.cpp"
#include "processors/juce_GenericAudioProcessorEditor.cpp"
#include "processors/juce_PluginDescription.cpp"
#include "format_types/juce_LADSPAPluginFormat.cpp"
#include "format_types/juce_VSTPluginFormat.cpp"
#include "format_types/juce_VST3PluginFormat.cpp"
#include "format_types/juce_AudioUnitPluginFormat.mm"
#include "scanning/juce_KnownPluginList.cpp"
#include "scanning/juce_PluginDirectoryScanner.cpp"
#include "scanning/juce_PluginListComponent.cpp"
#include "processors/juce_AudioProcessorParameterGroup.cpp"
#include "utilities/juce_AudioProcessorParameterWithID.cpp"
#include "utilities/juce_RangedAudioParameter.cpp"
#include "utilities/juce_AudioParameterFloat.cpp"
#include "utilities/juce_AudioParameterInt.cpp"
#include "utilities/juce_AudioParameterBool.cpp"
#include "utilities/juce_AudioParameterChoice.cpp"
#include "utilities/juce_ParameterAttachments.cpp"
#include "utilities/juce_AudioProcessorValueTreeState.cpp"
#include "utilities/juce_PluginHostType.cpp"
|
/**
* @author Moe_Sakiya sakiya@tun.moe
* @date 2019-08-04 15:04:16
*
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
const int maxN = 100005;
int arr[maxN];
int arrIdx[maxN];
int sum, limit;
struct Node
{
int val;
int idx;
bool operator < (const Node & n) const {
return val < n.val;
}
} N[maxN];
int LowBit(int x) {
return x & -x;
}
bool Check(int val) {
int ptr = 0;
for (int i = 1; i <= limit; i++)
N[i] = {arr[i], i};
sort(N + 1, N + limit + 1);
for (int i = limit; i >= 1; i--)
if (sum > 0) {
if (N[i].val <= sum) {
sum -= N[i].val;
arrIdx[ptr++] = N[i].idx;
}
}
if (sum == 0) {
printf("%d\n", ptr );
for (int i = 0; i < ptr; i++)
printf("%d ", arrIdx[i]);
putchar('\n');
return true;
}
return false;
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
for (int i = 1; i <= maxN; i++)
arr[i] = LowBit(i);
scanf("%d %d", &sum, &limit);
if (Check(sum) == false)
printf("-1\n");
return 0;
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Declares the types and functions that implement the
// OpenGL rendering functionality of DXGL
#ifndef __GLCOMMON__
#define __GLCOMMON__
#include "GLPlatform.hpp"
#import <sys/utsname.h>
#import <Foundation/Foundation.h>
#ifdef _DEBUG
# define DXMETAL_DEBUG_PIPELINE
# define DXMETAL_DEBUG_SHADER_COMPILER
#endif // _DEBUG
#ifdef DXMETAL_DEBUG_PIPELINE
# define LOG_METAL_PIPELINE_ERRORS(...) NSLog(__VA_ARGS__)
#else
# define LOG_METAL_PIPELINE_ERRORS(...)
#endif // DXMETAL_DEBUG_PIPELINE
#ifdef DXMETAL_DEBUG_SHADER_COMPILER
# define LOG_METAL_PIPELINE_ERRORS(...) NSLog(__VA_ARGS__)
# define LOG_METAL_SHADER_ERRORS(...) NSLog(__VA_ARGS__)
// Dump shader source every time a new one is compiled
# define LOG_METAL_SHADER_SOURCE(...) NSLog(__VA_ARGS__)
// Dump verbouse shader inputs information during pipeline creation
# define LOG_METAL_SHADER_REFLECTION_VALIDATION(...) NSLog(__VA_ARGS__)
#else
# define LOG_METAL_SHADER_ERRORS(...)
# define LOG_METAL_SHADER_SOURCE(...)
# define LOG_METAL_SHADER_REFLECTION_VALIDATION(...)
#endif // DXMETAL_DEBUG_SHADER_COMPILER
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
DXMETAL_TODO("consider this floating around. Those defines define some points to modify for the future extensions.")
// Is implemented for GL ES 3.1+
#define DXGL_SUPPORT_MULTISAMPLING 0
#define DXGL_SUPPORT_MULTISAMPLED_TEXTURES 0
#define DXGL_SUPPORT_COMPUTE 1
#define DXGL_SUPPORT_SHADER_STORAGE_BLOCKS 1
// Is implemented for GL 4.1+
#define DXGL_SUPPORT_TEXTURE_BUFFERS 1
#define DXMETAL_MAX_ENTRIES_BUFFER_ARG_TABLE 31
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace NCryMetal
{
inline bool SupportTextureViews()
{
return true;
}
inline bool SupportsStencilTextures()
{
return true;
}
inline int GetAvailableMRTbpp()
{
static int ret = 0;
if (ret == 0)
{
// Figure out availble MRT bpp
// https://developer.apple.com/library/mac/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/MetalFeatureSetTables/MetalFeatureSetTables.html
// "16 bytes per pixel in iOS GPU Family 1; 32 bytes per pixel in iOS GPU Family 2 and 3"
// There's no way to get GPU family via code, we have to deduct it from the device name.
// A7 is family 1 = 128bpp
// A8 is family 2 = 256bpp
// A9 is family 3 = 256bpp
// We only check for devices that support Metal which are shown in the link above on Table 2-1.
struct utsname sysInfo;
uname(&sysInfo);
NSString* deviceCode = [NSString stringWithCString:sysInfo.machine encoding:NSUTF8StringEncoding];
// A7 GPUs only have 128bpp available
if ([deviceCode rangeOfString:@"iPhone6"].location != NSNotFound || // iPhone 5s
[deviceCode rangeOfString:@"iPad4"].location != NSNotFound) // iPad Air, iPad Mini 2, iPad Mini 3
{
ret = 128;
}
else // Assume newer hardware
{
ret = 256;
}
}
return ret;
}
static bool s_isIosMinVersion9_0 = false;
static bool s_isOsxMinVersion10_11 = false;
//Cache the OS version which can then be used to query if certain API calls are enabled/disabled.
inline void CacheMinOSVersionInfo()
{
#if defined(AZ_PLATFORM_APPLE_OSX)
s_isOsxMinVersion10_11 = [[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 11, 0}];
#elif defined(AZ_PLATFORM_APPLE_IOS)
s_isIosMinVersion9_0 = [[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){9, 0, 0}];
#endif
}
}
enum
{
DXGL_NUM_SUPPORTED_VIEWPORTS = 1,
DXGL_NUM_SUPPORTED_SCISSOR_RECTS = 1,
};
////////////////////////////////////////////////////////////////////////////
// Conform extension definitions
////////////////////////////////////////////////////////////////////////////
namespace NCryMetal
{
typedef void* TWindowContext;
}
#endif //__GLCOMMON__
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/arcore-android-sdk/src/libraries/include/arcore_c_api.h"
#include <dlfcn.h>
#include "base/logging.h"
namespace {
// Run CALL macro for every function defined in the API.
#define FOR_EACH_API_FN \
CALL(ArCamera_getDisplayOrientedPose) \
CALL(ArCamera_getProjectionMatrix) \
CALL(ArCamera_getTrackingState) \
CALL(ArConfig_create) \
CALL(ArConfig_destroy) \
CALL(ArFrame_acquireCamera) \
CALL(ArFrame_create) \
CALL(ArFrame_destroy) \
CALL(ArFrame_transformDisplayUvCoords) \
CALL(ArPose_create) \
CALL(ArPose_destroy) \
CALL(ArPose_getPoseRaw) \
CALL(ArSession_checkSupported) \
CALL(ArSession_configure) \
CALL(ArSession_create) \
CALL(ArSession_destroy) \
CALL(ArSession_pause) \
CALL(ArSession_resume) \
CALL(ArSession_setCameraTextureName) \
CALL(ArSession_setDisplayGeometry) \
CALL(ArSession_update)
#define CALL(fn) decltype(&fn) impl_##fn = nullptr;
struct ArCoreApi {
FOR_EACH_API_FN
};
#undef CALL
static void* sdk_handle = nullptr;
static ArCoreApi* arcore_api = nullptr;
template <typename Fn>
void LoadFunction(void* handle, const char* function_name, Fn* fn_out) {
void* fn = dlsym(handle, function_name);
if (!fn)
return;
*fn_out = reinterpret_cast<Fn>(fn);
}
} // namespace
namespace vr {
bool LoadArCoreSdk() {
if (arcore_api)
return true;
sdk_handle = dlopen("libarcore_sdk_c_minimal.so", RTLD_GLOBAL | RTLD_NOW);
if (!sdk_handle) {
DLOG(ERROR) << "could not open libarcore_sdk_c_minimal.so";
return false;
}
// TODO(vollick): check SDK version.
arcore_api = new ArCoreApi();
#define CALL(fn) LoadFunction(sdk_handle, #fn, &arcore_api->impl_##fn);
FOR_EACH_API_FN
#undef CALL
return true;
}
} // namespace vr
#undef FOR_EACH_API_FN
void ArCamera_getDisplayOrientedPose(const ArSession* session,
const ArCamera* camera,
ArPose* out_pose) {
arcore_api->impl_ArCamera_getDisplayOrientedPose(session, camera, out_pose);
}
void ArCamera_getProjectionMatrix(const ArSession* session,
const ArCamera* camera,
float near,
float far,
float* dest_col_major_4x4) {
arcore_api->impl_ArCamera_getProjectionMatrix(session, camera, near, far,
dest_col_major_4x4);
}
void ArCamera_getTrackingState(const ArSession* session,
const ArCamera* camera,
ArTrackingState* out_tracking_state) {
arcore_api->impl_ArCamera_getTrackingState(session, camera,
out_tracking_state);
}
void ArConfig_create(const ArSession* session, ArConfig** out_config) {
arcore_api->impl_ArConfig_create(session, out_config);
}
void ArConfig_destroy(ArConfig* config) {
arcore_api->impl_ArConfig_destroy(config);
}
void ArFrame_acquireCamera(const ArSession* session,
const ArFrame* frame,
ArCamera** out_camera) {
arcore_api->impl_ArFrame_acquireCamera(session, frame, out_camera);
}
void ArFrame_create(const ArSession* session, ArFrame** out_frame) {
arcore_api->impl_ArFrame_create(session, out_frame);
}
void ArFrame_destroy(ArFrame* frame) {
arcore_api->impl_ArFrame_destroy(frame);
}
void ArFrame_transformDisplayUvCoords(const ArSession* session,
const ArFrame* frame,
int32_t num_elements,
const float* uvs_in,
float* uvs_out) {
arcore_api->impl_ArFrame_transformDisplayUvCoords(
session, frame, num_elements, uvs_in, uvs_out);
}
void ArPose_create(const ArSession* session,
const float* pose_raw,
ArPose** out_pose) {
arcore_api->impl_ArPose_create(session, pose_raw, out_pose);
}
void ArPose_destroy(ArPose* pose) {
arcore_api->impl_ArPose_destroy(pose);
}
void ArPose_getPoseRaw(const ArSession* session,
const ArPose* pose,
float* out_pose_raw) {
arcore_api->impl_ArPose_getPoseRaw(session, pose, out_pose_raw);
}
ArStatus ArSession_checkSupported(const ArSession* session,
const ArConfig* config) {
return arcore_api->impl_ArSession_checkSupported(session, config);
}
ArStatus ArSession_configure(ArSession* session, const ArConfig* config) {
return arcore_api->impl_ArSession_configure(session, config);
}
ArStatus ArSession_create(void* env,
void* application_context,
ArSession** out_session_pointer) {
return arcore_api->impl_ArSession_create(env, application_context,
out_session_pointer);
}
void ArSession_destroy(ArSession* session) {
arcore_api->impl_ArSession_destroy(session);
}
ArStatus ArSession_pause(ArSession* session) {
return arcore_api->impl_ArSession_pause(session);
}
ArStatus ArSession_resume(ArSession* session) {
return arcore_api->impl_ArSession_resume(session);
}
void ArSession_setCameraTextureName(ArSession* session, uint32_t texture_id) {
return arcore_api->impl_ArSession_setCameraTextureName(session, texture_id);
}
void ArSession_setDisplayGeometry(ArSession* session,
int32_t rotation,
int32_t width,
int32_t height) {
return arcore_api->impl_ArSession_setDisplayGeometry(session, rotation, width,
height);
}
ArStatus ArSession_update(ArSession* session, ArFrame* out_frame) {
return arcore_api->impl_ArSession_update(session, out_frame);
}
|
/**********************************************************************
* Online Judge : POJ
* Problem Title : Cows
* ID : 2481
* Date : 11/28/2008
* Time : 22:16:38
* Computer Name : EVERLASTING-PC
***********************************************************************/
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 100001
struct Cow
{
int s,e,index;
};
Cow cows[MAXN];
int C[MAXN];
int n;
int ans[MAXN];
inline bool cmp(Cow a,Cow b)
{
return a.e==b.e?a.s>b.s:a.e>b.e;
}
inline int LowBit(int x)
{
return x&(-x);
}
int Sum(int i)
{
int s=0;
while(i>0)
{
s+=C[i];
i-=LowBit(i);
}
return s;
}
void Modify(int i,int delta,int len)
{
while(i<=len)
{
C[i]+=delta;
i+=LowBit(i);
}
}
int main()
{
//freopen("in_2481.txt","r",stdin);
cows[0].e=-1;
while(cin>>n&&n)
{
memset(C,0,sizeof(C));
for(int i=1;i<=n;++i)
{
cin>>cows[i].s>>cows[i].e;
cows[i].s++;
cows[i].e++;
cows[i].index=i;
}
sort(cows+1,cows+n+1,cmp);
for(int i=1;i<=n;++i)
{
if(cows[i].s==cows[i-1].s&&cows[i].e==cows[i-1].e)
{
ans[cows[i].index]=ans[cows[i-1].index];
}
else
{
ans[cows[i].index]=Sum(cows[i].s);
}
Modify(cows[i].s,1,cows[i].e);
}
for(int i=1;i<=n;++i)
{
if(i!=1)
{
cout<<' ';
}
cout<<ans[i];
}
cout<<endl;
}
return 0;
}
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <wchar.h>
#include "Assert.hpp"
#include "lib.hpp"
#include <axl.util/WString.hpp>
int main(int argc, char *argv[])
{
bool verbose = argc > 1 && (0 == strcmp(argv[1], "-v") || 0 == strcmp(argv[1], "--verbose"));
using namespace axl;
using namespace axl::util;
printf("axl.util %s library - version %u.%u.%u --- [WString] test\n", buildType(lib::BUILD), lib::VERSION.major, lib::VERSION.minor, lib::VERSION.patch);
puts("----------------------------------------");
Assertve(sizeof(WString::char_t) == 2U, verbose);
{ // Static variables tests
Assertv(WString::NullWChar == '\0', verbose);
Assertv(WString::NullCWStr == (const WString::char_t*)0, verbose);
Assertv(WString::NullWStr == (WString::char_t*)0, verbose);
}
{ // Static methods tests
{
Assertv(WString::scwLength(L"Hello World!") == 12, verbose);
Assertv(WString::scwLength(L"Hello World!", 13) == 12, verbose);
Assertv(WString::scwLength(L"Hello World!", 12) == 12, verbose);
Assertv(WString::scwLength(L"Hello World!", 11) == 11, verbose);
}
{
WString::char_t buffer[32] = {L"123456789abcdef"};
WString::scwCopy(L"Hello World!", buffer, 13);
Assertv(0 == wcsncmp(buffer, L"Hello World!", 13), verbose);
}
{
WString::char_t buffer[32] = L"123456789abcdef";
WString::scwCopy(L"Hello World!", buffer, 7, 6);
Assertv(0 == wcsncmp(buffer, L"World!", 7), verbose);
}
{
WString::char_t buffer[32] = L"123456789abcdef";
WString::scwCopy(L"Hello World!", buffer, 12, 0, 3);
Assertv(0 == wcsncmp(buffer, L"123Hello World!", 16), verbose);
}
{
WString::char_t buffer[32] = {L"123456789abcdef"};
WString::scCopy("Hello World!", buffer, 13);
Assertv(0 == wcsncmp(buffer, L"Hello World!", 13), verbose);
}
{
WString::char_t buffer[32] = L"123456789abcdef";
WString::scCopy("Hello World!", buffer, 7, 6);
Assertv(0 == wcsncmp(buffer, L"World!", 7), verbose);
}
{
WString::char_t buffer[32] = L"123456789abcdef";
WString::scCopy("Hello World!", buffer, 12, 0, 3);
Assertv(0 == wcsncmp(buffer, L"123Hello World!", 16), verbose);
}
{ // scEqual
const WString::char_t* hello = L"Hello World!";
Assertv(!WString::scwEquals(0, 0), verbose);
Assertv(WString::scwEquals(L"", L""), verbose);
Assertv(WString::scwEquals(L"1", L"1"), verbose);
Assertv(!WString::scwEquals(L"1", L"2"), verbose);
Assertv(WString::scwEquals(hello, L"Hello World!"), verbose);
Assertv(!WString::scwEquals(hello, L"Hello World! "), verbose);
Assertv(!WString::scwEquals(hello, L"Hello World"), verbose);
Assertv(!WString::scwEquals(hello, L"Hello"), verbose);
Assertv(!WString::scwEquals(hello, L"Hello Morld!"), verbose);
}
}
{ // Destructor tests
{ // Non-sensitive
WString wstr(L"Hello");
WString::char_t* cwstr = wstr.wstr();
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
Assertv(cwstr == wstr.cwstr(), verbose);
wstr.destroy();
Assertv(wstr.cwstr() == WString::NullCWStr, verbose);
Assertv(wstr.size() == 0U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.length(false) == 0U, verbose);
Assertv(wstr.length(true) == 0U, verbose);
}
{ // Sensitive
WString wstr(L"Hello World! How are you?");
WString::char_t* cwstr = wstr.wstr();
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! How are you?"), verbose);
Assertv(cwstr == wstr.cwstr(), verbose);
wstr.destroy();
Assertv(wstr.cwstr() == WString::NullCWStr, verbose);
Assertv(wstr.size() == 0U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.length(false) == 0U, verbose);
Assertv(wstr.length(true) == 0U, verbose);
Assertv(0 != wcsncmp(cwstr, L"Hello World! How are you?", 6), verbose);
}
}
{ // Constructor tests
{ // Default constructor
WString wstr;
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(wstr.isNull(), verbose);
Assertv(wstr.size() == 1U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L""), verbose);
}
{ // Length constructor
WString wstr(12);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr()[0] == WString::NullWChar, verbose);
WString::scwCopy(L"Hello World!", wstr.wstr(), 13);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.length(true) == 12U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
}
{ // Cstring constructors
{
WString wstr(L"");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(wstr.isNull(), verbose);
Assertv(wstr.size() == 1U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L""), verbose);
}
{
WString wstr(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
}
{
WString wstr(L"Hello World!", 5);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 6U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
}
{
WString wstr(L"Hello World!", 6, 6);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 7U, verbose);
Assertv(wstr.length() == 6U, verbose);
Assertv(wstr.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"World!"), verbose);
}
}
{ // Copy constructors
{
WString wstr(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
WString copy_str(wstr);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 13U, verbose);
Assertv(copy_str.length() == 12U, verbose);
Assertv(copy_str.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello World!"), verbose);
}
{
WString wstr(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
wstr.wstr()[5] = WString::NullWChar;
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.length(true) == 5U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
Assertv(0 == wcsncmp(wstr.cwstr(), L"Hello\0World!", 13), verbose);
WString copy_str(wstr);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 6U, verbose);
Assertv(copy_str.length() == 5U, verbose);
Assertv(copy_str.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello"), verbose);
}
{
const WString wstr(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
{
WString copy_str(wstr, 5);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 6U, verbose);
Assertv(copy_str.length() == 5U, verbose);
Assertv(copy_str.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello"), verbose);
}
{
WString copy_str(wstr, 6, 6);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 7U, verbose);
Assertv(copy_str.length() == 6U, verbose);
Assertv(copy_str.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"World!"), verbose);
}
{
WString copy_str(wstr, 0, 6);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
{
WString copy_str(wstr, 1, 6);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 2U, verbose);
Assertv(copy_str.length() == 1U, verbose);
Assertv(copy_str.cwstr()[1] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"W"), verbose);
}
{
WString copy_str(wstr, 7, 6);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 7U, verbose);
Assertv(copy_str.length() == 6U, verbose);
Assertv(copy_str.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"World!"), verbose);
}
{
WString copy_str(wstr, 8, 6);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 7U, verbose);
Assertv(copy_str.length() == 6U, verbose);
Assertv(copy_str.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"World!"), verbose);
}
{
WString copy_str(wstr, 6, 11);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 2U, verbose);
Assertv(copy_str.length() == 1U, verbose);
Assertv(copy_str.cwstr()[1] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"!"), verbose);
}
{
WString copy_str(wstr, 6, 12);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
{
WString copy_str(wstr, 6, 13);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
{
WString copy_str(wstr, 6, 14);
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
}
{
const String str("Hello World!");
Assertv(str.size() == 13U, verbose);
Assertv(str.length() == 12U, verbose);
Assertv(0 == strcmp(str.cstr(), "Hello World!"), verbose);
{
WString copy_str(str);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 13U, verbose);
Assertv(copy_str.length() == 12U, verbose);
Assertv(copy_str.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello World!"), verbose);
}
{
WString copy_str(str, 5);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 6U, verbose);
Assertv(copy_str.length() == 5U, verbose);
Assertv(copy_str.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello"), verbose);
}
{
WString copy_str(str, 6, 6);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 7U, verbose);
Assertv(copy_str.length() == 6U, verbose);
Assertv(copy_str.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"World!"), verbose);
}
{
WString copy_str(str, 0, 6);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
{
WString copy_str(str, 1, 6);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 2U, verbose);
Assertv(copy_str.length() == 1U, verbose);
Assertv(copy_str.cwstr()[1] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"W"), verbose);
}
{
WString copy_str(str, 7, 6);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 7U, verbose);
Assertv(copy_str.length() == 6U, verbose);
Assertv(copy_str.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"World!"), verbose);
}
{
WString copy_str(str, 8, 6);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 7U, verbose);
Assertv(copy_str.length() == 6U, verbose);
Assertv(copy_str.cwstr()[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"World!"), verbose);
}
{
WString copy_str(str, 6, 11);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 2U, verbose);
Assertv(copy_str.length() == 1U, verbose);
Assertv(copy_str.cwstr()[1] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"!"), verbose);
}
{
WString copy_str(str, 6, 12);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
{
WString copy_str(str, 6, 13);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
{
WString copy_str(str, 6, 14);
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L""), verbose);
}
}
}
{ // Move constructor
{
WString wstr(WString(L"Hello World!"));
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
}
}
}
{ // Assignment operators
{ // Copy assignment operators
{
const WString wstr(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
WString copy_str;
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
copy_str = wstr;
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 13U, verbose);
Assertv(copy_str.length() == 12U, verbose);
Assertv(copy_str.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello World!"), verbose);
}
{
WString wstr(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.cwstr() == wstr.wstr(), verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
wstr.wstr()[5] = WString::NullWChar;
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.length(true) == 5U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
Assertv(0 == wcsncmp(wstr.cwstr(), L"Hello\0World!", 13), verbose);
WString copy_str;
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(copy_str.isNull(), verbose);
Assertv(copy_str.size() == 1U, verbose);
Assertv(copy_str.length() == 0U, verbose);
Assertv(copy_str.cwstr()[0] == WString::NullWChar, verbose);
copy_str = wstr;
Assertv(wstr.cwstr() != copy_str.cwstr(), verbose);
Assertv(copy_str.wstr() != WString::NullCWStr, verbose);
Assertv(copy_str.cwstr() == copy_str.wstr(), verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 6U, verbose);
Assertv(copy_str.length() == 5U, verbose);
Assertv(copy_str.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello"), verbose);
}
{
const String str("Hello World!");
Assertv(str.size() == 13U, verbose);
Assertv(str.length() == 12U, verbose);
Assertv(0 == strcmp(str.cstr(), "Hello World!"), verbose);
{
WString copy_str;
Assertv(copy_str.isNull(), verbose);
copy_str = str;
Assertv(copy_str.cwstr() != WString::NullCWStr, verbose);
Assertv(!copy_str.isNull(), verbose);
Assertv(copy_str.size() == 13U, verbose);
Assertv(copy_str.length() == 12U, verbose);
Assertv(copy_str.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(copy_str.cwstr(), L"Hello World!"), verbose);
}
}
{ // Cstring assignment operator
WString wstr;
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr.isNull(), verbose);
Assertv(wstr.size() == 1U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr()[0] == WString::NullWChar, verbose);
wstr = L"Hello World!";
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
wstr = L"Jello";
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 6U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Jello"), verbose);
const WString::char_t* cwstr = wstr.cwstr();
wstr = L"Hello";
Assertv(wstr.cwstr() == cwstr, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 6U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr()[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
}
}
{ // Move assignment operators
const WString wstr = WString(L"Hello World!");
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr()[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
}
}
{ // Operators tests
{ // Square bracket operators
{
const WString wstr = L"Hello World!";
Assertv(wstr[0] == 'H', verbose);
Assertv(wstr[10] == 'd', verbose);
Assertv(wstr[11] == '!', verbose);
Assertv(wstr[12] == '\0', verbose);
Assertv(0 == wcscmp(&wstr[0], L"Hello World!"), verbose);
}
{
WString wstr = L"Hello World!";
Assertv(wstr[0] == 'H', verbose);
Assertv(wstr[10] == 'd', verbose);
Assertv(wstr[11] == '!', verbose);
Assertv(wstr[12] == '\0', verbose);
Assertv(0 == wcscmp(&wstr[0], L"Hello World!"), verbose);
wstr[0] = 'J';
Assertv(wstr[0] == 'J', verbose);
Assertv(0 == wcscmp(&wstr[0], L"Jello World!"), verbose);
}
}
{ // Addition operator
{
const WString str1 = L"Hello Mars!";
const WString str2 = L"This is Earth.";
WString wstr = str1 + str2;
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 26U, verbose);
Assertv(wstr.length() == 25U, verbose);
Assertv(wstr.cwstr()[25] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello Mars!This is Earth."), verbose);
}
{
const WString str1 = L"Hello Mars!";
const WString::char_t* str2 = L"This is Earth.";
WString wstr = str1 + str2;
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 26U, verbose);
Assertv(wstr.length() == 25U, verbose);
Assertv(wstr.cwstr()[25] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello Mars!This is Earth."), verbose);
}
{
WString wstr = L"Hello Mars!";
const WString str2 = L"This is Earth.";
wstr += str2;
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 26U, verbose);
Assertv(wstr.length() == 25U, verbose);
Assertv(wstr.cwstr()[25] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello Mars!This is Earth."), verbose);
}
{
WString wstr = L"Hello Mars!";
const WString::char_t* str2 = L"This is Earth.";
wstr += str2;
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(!wstr.isNull(), verbose);
Assertv(wstr.size() == 26U, verbose);
Assertv(wstr.length() == 25U, verbose);
Assertv(wstr.cwstr()[25] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello Mars!This is Earth."), verbose);
}
}
{ // Comparison operators
{ // Equality operator
const WString str1 = L"Hello World!";
const WString str2 = L"Hello World!";
const WString str3 = L"Jello World!";
const WString str4 = L"Hello Morld!";
const WString str5 = L"Hello World";
Assertv(str1 == str2, verbose);
Assertv(!(str1 == str3), verbose);
Assertv(!(str1 == str4), verbose);
Assertv(!(str1 == str5), verbose);
}
{ // Inequality operator
const WString str1 = L"Hello World!";
const WString str2 = L"Hello World!";
const WString str3 = L"Jello World!";
const WString str4 = L"Hello Morld!";
const WString str5 = L"Hello World";
Assertv(!(str1 != str2), verbose);
Assertv(str1 != str3, verbose);
Assertv(str1 != str4, verbose);
Assertv(str1 != str5, verbose);
}
{
const WString Cat = L"Cat";
const WString Car = L"Car";
const WString Coat = L"Coat";
const WString Apple = L"Apple";
const WString Juice = L"Juice";
const WString Ape = L"Ape";
const WString Mango = L"Mango";
{ // Greater than or equal to
Assertv(Cat >= Cat, verbose);
Assertv(Cat >= Car, verbose);
Assertv(!(Cat >= Coat), verbose);
Assertv(Cat >= Apple, verbose);
Assertv(!(Cat >= Juice), verbose);
Assertv(Cat >= Ape, verbose);
Assertv(!(Cat >= Mango), verbose);
Assertv(Juice >= Juice, verbose);
Assertv(Juice >= Cat, verbose);
Assertv(Juice >= Car, verbose);
Assertv(Juice >= Coat, verbose);
Assertv(Juice >= Apple, verbose);
Assertv(Juice >= Ape, verbose);
Assertv(!(Juice >= Mango), verbose);
}
{ // Less than or equal to
Assertv(Cat <= Cat, verbose);
Assertv(!(Cat <= Car), verbose);
Assertv(Cat <= Coat, verbose);
Assertv(!(Cat <= Apple), verbose);
Assertv(Cat <= Juice, verbose);
Assertv(!(Cat <= Ape), verbose);
Assertv(Cat <= Mango, verbose);
Assertv(Juice <= Juice, verbose);
Assertv(!(Juice <= Cat), verbose);
Assertv(!(Juice <= Car), verbose);
Assertv(!(Juice <= Coat), verbose);
Assertv(!(Juice <= Apple), verbose);
Assertv(!(Juice <= Ape), verbose);
Assertv(Juice <= Mango, verbose);
}
{ // Greater than
Assertv(!(Cat > Cat), verbose);
Assertv(Cat > Car, verbose);
Assertv(!(Cat > Coat), verbose);
Assertv(Cat > Apple, verbose);
Assertv(!(Cat > Juice), verbose);
Assertv(Cat > Ape, verbose);
Assertv(!(Cat > Mango), verbose);
Assertv(!(Juice > Juice), verbose);
Assertv(Juice > Cat, verbose);
Assertv(Juice > Car, verbose);
Assertv(Juice > Coat, verbose);
Assertv(Juice > Apple, verbose);
Assertv(Juice > Ape, verbose);
Assertv(!(Juice > Mango), verbose);
}
{ // Less than
Assertv(!(Cat < Cat), verbose);
Assertv(!(Cat < Car), verbose);
Assertv(Cat < Coat, verbose);
Assertv(!(Cat < Apple), verbose);
Assertv(Cat < Juice, verbose);
Assertv(!(Cat < Ape), verbose);
Assertv(Cat < Mango, verbose);
Assertv(!(Juice < Juice), verbose);
Assertv(!(Juice < Cat), verbose);
Assertv(!(Juice < Car), verbose);
Assertv(!(Juice < Coat), verbose);
Assertv(!(Juice < Apple), verbose);
Assertv(!(Juice < Ape), verbose);
Assertv(Juice < Mango, verbose);
}
}
}
}
{ // Methods tests
{ // Resize
{
WString wstr;
Assertv(wstr.size() == 1U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[0] == WString::NullWChar, verbose);
Assertv(wstr.resize(5), verbose);
Assertv(wstr.size() == 6U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[0] == WString::NullWChar, verbose);
Assertv(wstr.resize(2), verbose);
Assertv(wstr.size() == 3U, verbose);
Assertv(wstr.length() == 0U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[0] == WString::NullWChar, verbose);
}
{
WString wstr = L"Hello";
Assertv(wstr.size() == 6U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
Assertv(wstr.resize(12), verbose);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello"), verbose);
WString::scwCopy(L"Hello World!", wstr.wstr(), 13);
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 5U, verbose);
Assertv(wstr.length(true) == 12U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
}
}
{ // Append
{ // Append WString
{
WString wstr = L"Hello World!";
const WString app_str = L" It's me Nati.";
wstr.append(app_str);
Assertv(wstr.size() == 27U, verbose);
Assertv(wstr.length() == 26U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[26] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! It's me Nati."), verbose);
}
{
WString wstr = L"Hello World!";
const WString app_str = L" It's me Nati.";
wstr.append(app_str, 0);
Assertv(wstr.size() == 27U, verbose);
Assertv(wstr.length() == 26U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[26] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! It's me Nati."), verbose);
}
{
WString wstr = L"Hello World!";
const WString app_str = L" It's me Nati.";
wstr.append(app_str, 8);
Assertv(wstr.size() == 21U, verbose);
Assertv(wstr.length() == 20U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[20] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! It's me"), verbose);
}
{
WString wstr = L"Hello World!";
const WString app_str = L" It's me Nati.";
wstr.append(app_str, 5, 9);
Assertv(wstr.size() == 18U, verbose);
Assertv(wstr.length() == 17U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[17] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!Nati."), verbose);
}
}
{ // Append cstring
{
WString wstr = L"Hello World!";
const WString::char_t* app_str = L" It's me Nati.";
wstr.append(app_str);
Assertv(wstr.size() == 27U, verbose);
Assertv(wstr.length() == 26U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[26] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! It's me Nati."), verbose);
}
{
WString wstr = L"Hello World!";
const WString::char_t* app_str = L" It's me Nati.";
wstr.append(app_str, 0);
Assertv(wstr.size() == 27U, verbose);
Assertv(wstr.length() == 26U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[26] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! It's me Nati."), verbose);
}
{
WString wstr = L"Hello World!";
const WString::char_t* app_str = L" It's me Nati.";
wstr.append(app_str, 8);
Assertv(wstr.size() == 21U, verbose);
Assertv(wstr.length() == 20U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[20] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! It's me"), verbose);
}
{
WString wstr = L"Hello World!";
const WString::char_t* app_str = L" It's me Nati.";
wstr.append(app_str, 5, 9);
Assertv(wstr.size() == 18U, verbose);
Assertv(wstr.length() == 17U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[17] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!Nati."), verbose);
}
}
}
{ // Substring
const WString wstr = L"Hello World!";
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
{
const WString sub_str = wstr.substring(5);
Assertv(sub_str.size() == 6U, verbose);
Assertv(sub_str.length() == 5U, verbose);
Assertv(sub_str.cwstr() != WString::NullCWStr, verbose);
Assertv(sub_str[5] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(sub_str.cwstr(), L"Hello"), verbose);
}
{
const WString sub_str = wstr.substring(6, 6);
Assertv(sub_str.size() == 7U, verbose);
Assertv(sub_str.length() == 6U, verbose);
Assertv(sub_str.cwstr() != WString::NullCWStr, verbose);
Assertv(sub_str[6] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(sub_str.cwstr(), L"World!"), verbose);
}
}
{ // Reverse
const WString wstr = L"Hello World!";
Assertv(wstr.size() == 13U, verbose);
Assertv(wstr.length() == 12U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World!"), verbose);
const WString rev_str = wstr.reverse();
Assertv(rev_str.size() == 13U, verbose);
Assertv(rev_str.length() == 12U, verbose);
Assertv(rev_str.cwstr() != WString::NullCWStr, verbose);
Assertv(rev_str[12] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(rev_str.cwstr(), L"!dlroW olleH"), verbose);
}
{ // ToUpper
const WString wstr = L"Hello World! 1234@#$%";
Assertv(wstr.size() == 22U, verbose);
Assertv(wstr.length() == 21U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[21] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello World! 1234@#$%"), verbose);
const WString upper_str = wstr.toUpper();
Assertv(upper_str.size() == 22U, verbose);
Assertv(upper_str.length() == 21U, verbose);
Assertv(upper_str.cwstr() != WString::NullCWStr, verbose);
Assertv(upper_str[21] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(upper_str.cwstr(), L"HELLO WORLD! 1234@#$%"), verbose);
}
{ // ToLower
const WString wstr = L"HeLLo WoRLD! 1234@#$%";
Assertv(wstr.size() == 22U, verbose);
Assertv(wstr.length() == 21U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(wstr[21] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"HeLLo WoRLD! 1234@#$%"), verbose);
const WString lower_str = wstr.toLower();
Assertv(lower_str.size() == 22U, verbose);
Assertv(lower_str.length() == 21U, verbose);
Assertv(lower_str.cwstr() != WString::NullCWStr, verbose);
Assertv(lower_str[21] == WString::NullWChar, verbose);
Assertv(0 == wcscmp(lower_str.cwstr(), L"hello world! 1234@#$%"), verbose);
}
{ // format
{
WString str(18);
Assertv(str.format(L"Doom%s %d", L"Ethernal", 3) == L"DoomEthernal 3", verbose);
}
{
WString str(15);
Assertv(str.format(L"Doom%s %d", L"Ethernal", 3) == L"DoomEthernal 3", verbose);
}
{
WString str(35);
Assertv(str.format(L"Temperature: %.1f, %.1lf", 24.5f, 72.66f) == L"Temperature: 24.5, 72.7", verbose);
}
}
{ // ToString
WString wstr = L"Hello Mars!";
Assertv(wstr.size() == 12U, verbose);
Assertv(wstr.length() == 11U, verbose);
Assertv(wstr.cwstr() != WString::NullCWStr, verbose);
Assertv(0 == wcscmp(wstr.cwstr(), L"Hello Mars!"), verbose);
String str = wstr.toString();
Assertv(str.size() == 12U, verbose);
Assertv(str.length() == 11U, verbose);
Assertv(str.cstr() != String::NullCStr, verbose);
Assertv(0 == strcmp(str.cstr(), "Hello Mars!"), verbose);
}
}
if(assert::_num_failed_tests > 0) puts("----------------------------------------");
printf("# %d Failed!\n", assert::_num_failed_tests);
return assert::_num_failed_tests;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2013 The SeedcoinX developer
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
#ifndef WIN32
#include <execinfo.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64 nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64 nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64 GetRand(uint64 nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
uint64 nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
static FILE* fileout = NULL;
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
loop
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
loop
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64& nRet)
{
string strWhole;
int64 nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64 nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64 nWhole = atoi64(strWhole);
int64 nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
loop
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64 GetArg(const std::string& strArg, int64 nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
loop
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "SeedcoinX";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void LogStackTrace() {
printf("\n\n******* exception encountered *******\n");
if (fileout)
{
#ifndef WIN32
void* pszBuffer[32];
size_t size;
size = backtrace(pszBuffer, 32);
backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
#endif
}
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\SeedcoinX
// Windows >= Vista: C:\Users\Username\AppData\Roaming\SeedcoinX
// Mac: ~/Library/Application Support/SeedcoinX
// Unix: ~/.SeedcoinX
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "SeedcoinX";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "SeedcoinX";
#else
// Unix
return pathRet / ".SeedcoinX";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet2";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "SeedcoinX.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No SeedcoinX.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override SeedcoinX.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "SeedcoinXd.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
int GetFilesize(FILE* file)
{
int nSavePos = ftell(file);
int nFilesize = -1;
if (fseek(file, 0, SEEK_END) == 0)
nFilesize = ftell(file);
fseek(file, nSavePos, SEEK_SET);
return nFilesize;
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && GetFilesize(file) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64 nMockTime = 0; // For unit testing
int64 GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64 nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64 nTimeOffset = 0;
int64 GetAdjustedTime()
{
return GetTime() + nTimeOffset;
}
void AddTimeData(const CNetAddr& ip, int64 nTime)
{
int64 nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
std::vector<int64> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64 nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong SeedcoinX will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("SeedcoinX"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+"PRI64d" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
|
// Computes the average image pixel intensity for the whole training
// set and stores the value in binaryproto file
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/text_format.h>
#include <stdint.h>
#include <sys/stat.h>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include "caffe/proto/caffe.pb.h"
using namespace caffe; // NOLINT(build/namespaces)
using std::string;
void WriteProtoToBinaryFile(const google::protobuf::Message& proto, const char* filename) {
std::fstream output(filename, std::ios::out | std::ios::trunc | std::ios::binary);
CHECK(proto.SerializeToOstream(&output));
}
uint32_t swap_endian(uint32_t val) {
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
void compute_mean(char* image_filename,
char* average_filename) {
// Open file
std::ifstream image_file(image_filename, std::ios::in | std::ios::binary);
CHECK(image_file) << "Unable to open file " << image_filename;
// Read the magic and the meta data
uint32_t magic;
uint32_t num_items;
uint32_t rows;
uint32_t cols;
image_file.read(reinterpret_cast<char*>(&magic), 4);
magic = swap_endian(magic);
CHECK_EQ(magic, 2051) << "Incorrect image file magic.";
image_file.read(reinterpret_cast<char*>(&num_items), 4);
num_items = swap_endian(num_items);
image_file.read(reinterpret_cast<char*>(&rows), 4);
rows = swap_endian(rows);
image_file.read(reinterpret_cast<char*>(&cols), 4);
cols = swap_endian(cols);
unsigned char* pixels = new unsigned char[rows * cols];
double sum_all = 0;
LOG(INFO) << "Rows: " << rows << " Cols: " << cols;
for (int item_id = 0; item_id < num_items; ++item_id) {
image_file.read((char*)pixels, rows * cols);
double sum = 0;
for( int i = 0; i < rows * cols; i++ )
sum += (double)pixels[i];
sum_all += sum / (rows*cols);
}
sum_all /= num_items;
LOG(INFO) << "Average value = " << sum_all << std::endl;
// Save average image as protobuf
caffe::BlobProto sum_blob;
sum_blob.set_num(1);
sum_blob.set_channels(1);
sum_blob.set_height(rows);
sum_blob.set_width(cols);
for( int i = 0; i < rows * cols; i++ )
sum_blob.add_data(float(sum_all));
WriteProtoToBinaryFile(sum_blob, average_filename);
}
int main(int argc, char** argv) {
#ifndef GFLAGS_GFLAGS_H_
namespace gflags = google;
#endif
gflags::SetUsageMessage("This script computes the average pixel value in the FRA/Amtrak dataset.\n"
"Usage:\n"
" create_average_image input_image_file output_protoblob\n");
if( argc < 3 ) {
gflags::ShowUsageWithFlagsRestrict(argv[0],
"examples/amtrak/create_average_image");
return 0;
} else {
google::InitGoogleLogging(argv[0]);
compute_mean(argv[1], argv[2]);
}
return 0;
}
|
#include "defs.inc"
#include <cmath>
#include <vector>
#include <atomic>
#include <thread>
double mylog2(double value)
{
constexpr int mantissa_bits = 52, exponent_bias = 1022;
const double half = 0.5;
std::uint64_t half_bits = reinterpret_cast<const std::uint64_t&>(half);
int e,lt;
uint64_t m;
double x, dbl_e, z, y, u, t;
m = reinterpret_cast<const std::uint64_t&>(value);
e = m >> mantissa_bits;
m &= std::uint64_t((1ull << mantissa_bits)-1);
m |= half_bits;
x = reinterpret_cast<const double&>(m);
lt = (x < 1/std::sqrt(2.)) ? -1 : 0;
dbl_e = e + lt - exponent_bias;
z = x - (half + (lt ? 0. : half));
y = half * (x - (lt ? half : 0.)) + half;
x = z/y;
z = x*x;
u = z + -3.56722798512324312549E1;
t = -7.89580278884799154124E-1;
u = u*z + 3.12093766372244180303E2;
t = t*z + 1.63866645699558079767E1;
u = u*z + -7.69691943550460008604E2;
t = t*z + -6.41409952958715622951E1;
y = z* (t/u) + (half+half);
return x*(y*std::log2(std::exp(1.))) + dbl_e;
}
template<bool WithMoment>
double ThreadLoopHelperIterate(double zr, double zi)
{
const double escape_radius_squared = ESCAPE_RADIUS_SQUARED;
const int maxiter = MAXITER;
double cr = zr, sr = cr;
double ci = zi, si = ci;
double dist;
int iter = maxiter, notescaped = -1;
if(zr*(1+zr*(8*zr*zr+(16*zi*zi-3)))+zi*zi*(8*zi*zi-3) < 3./32 || ((zr+1)*(zr+1)+zi*zi)<1./16) { iter=0; }
while(notescaped)
{
double r2 = cr * cr;
double i2 = ci * ci;
dist = r2 + i2;
notescaped &= ((iter != 0) & (dist < escape_radius_squared)) ? -1 : 0;
iter += notescaped;
double ri = cr * ci;
ci = zi + (ri * 2);
cr = zr + (r2 - i2);
if(WithMoment)
{
bool notmoment = iter & (iter-1);
iter = (cr == sr && ci == si) ? 0 : iter;
sr = notmoment ? sr : cr;
si = notmoment ? si : ci;
}
}
return iter ? mylog2( maxiter-iter + 1 - mylog2(mylog2(dist) / 2)) * (4/std::log2(std::exp(1.))) : 0;
}
template double ThreadLoopHelperIterate<false>(double zr, double zi);
template double ThreadLoopHelperIterate<true>(double zr, double zi);
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2014-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "AnalogOutput.h"
#include <limits>
#include <HAL/HAL.h>
#include <HAL/Ports.h>
#include "SensorBase.h"
#include "SmartDashboard/SendableBuilder.h"
#include "WPIErrors.h"
using namespace frc;
/**
* Construct an analog output on the given channel.
*
* All analog outputs are located on the MXP port.
*
* @param channel The channel number on the roboRIO to represent.
*/
AnalogOutput::AnalogOutput(int channel) {
if (!SensorBase::CheckAnalogOutputChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"analog output " + llvm::Twine(channel));
m_channel = std::numeric_limits<int>::max();
m_port = HAL_kInvalidHandle;
return;
}
m_channel = channel;
HAL_PortHandle port = HAL_GetPort(m_channel);
int32_t status = 0;
m_port = HAL_InitializeAnalogOutputPort(port, &status);
if (status != 0) {
wpi_setErrorWithContextRange(status, 0, HAL_GetNumAnalogOutputs(), channel,
HAL_GetErrorMessage(status));
m_channel = std::numeric_limits<int>::max();
m_port = HAL_kInvalidHandle;
return;
}
HAL_Report(HALUsageReporting::kResourceType_AnalogOutput, m_channel);
SetName("AnalogOutput", m_channel);
}
/**
* Destructor.
*
* Frees analog output resource.
*/
AnalogOutput::~AnalogOutput() { HAL_FreeAnalogOutputPort(m_port); }
/**
* Get the channel of this AnalogOutput.
*/
int AnalogOutput::GetChannel() { return m_channel; }
/**
* Set the value of the analog output.
*
* @param voltage The output value in Volts, from 0.0 to +5.0
*/
void AnalogOutput::SetVoltage(double voltage) {
int32_t status = 0;
HAL_SetAnalogOutput(m_port, voltage, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
}
/**
* Get the voltage of the analog output
*
* @return The value in Volts, from 0.0 to +5.0
*/
double AnalogOutput::GetVoltage() const {
int32_t status = 0;
double voltage = HAL_GetAnalogOutput(m_port, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
return voltage;
}
void AnalogOutput::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Analog Output");
builder.AddDoubleProperty("Value", [=]() { return GetVoltage(); },
[=](double value) { SetVoltage(value); });
}
|
/* NiuTrans.NMT - an open-source neural machine translation system.
* Copyright (C) 2020 NiuTrans Research. 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.
*/
/*
* $Created by: HU Chi (huchinlp@foxmail.com) 2019-04-03
* $Modified by: HU Chi (huchinlp@gmail.com) 2020-06
*/
#include <string>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#include "DataSet.h"
#include "../Utility.h"
using namespace nmt;
namespace nts {
/* sort the output by id (in ascending order) */
void DataSet::SortInput() {
sort(inputBuffer.items, inputBuffer.items + inputBuffer.count,
[](Example* a, Example* b) {
return a->values.count > b->values.count;
});
}
/* sort the input by length (in descending order) */
void DataSet::SortOutput() {
sort(outputBuffer.items, outputBuffer.items + outputBuffer.count,
[](Result* a, Result* b) {
return a->id < b->id;
});
}
/*
load data from the file to the buffer
*/
void DataSet::LoadDataToBuffer()
{
string line;
inputBuffer.Clear();
bufferUsed = 0;
int id = 0;
const string tokenDelimiter = " ";
while (getline(*fp, line)) {
IntList values;
/* load words and transform them to ids */
auto indices = SplitToPos(line, tokenDelimiter);
/* reserve the first 120 words if the input is too long */
size_t maxLen = indices.Size() > MAX_WORD_NUM ? MAX_WORD_NUM : indices.Size();
for (size_t i = 0; i < maxLen; i++) {
auto offset = (i != (indices.Size() - 1)) ?
indices[i + 1] - indices[i] - tokenDelimiter.size()
: line.size() - indices[i];
string word = line.substr(indices[i], offset);
if (srcVocab.word2id.find(word) == srcVocab.word2id.end())
values.Add(UNK);
else
values.Add(srcVocab.word2id.at(word));
}
/* make sure that the sequence ends with EOS */
if (values.Size() != 0 && values[-1] != EOS)
values.Add(EOS);
Example* example = new Example;
example->id = id;
example->values = values;
if (values.Size() != 0)
inputBuffer.Add(example);
else
emptyLines.Add(id);
id++;
}
fp->close();
SortInput();
XPRINT1(0, stderr, "[INFO] loaded %d sentences\n", id);
}
/*
load a mini-batch to the device (for translating)
>> batchEnc - a tensor to store the batch of input
>> paddingEnc - a tensor to store the batch of paddings
>> minSentBatch - the minimum number of sentence batch
>> batchSize - the maxium number of words in a batch
>> devID - the device id, -1 for the CPU
<< indices of the sentences
*/
UInt64List DataSet::LoadBatch(XTensor* batchEnc, XTensor* paddingEnc,
size_t minSentBatch, size_t batchSize, int devID)
{
size_t realBatchSize = minSentBatch;
/* get the maximum sentence length in a mini-batch */
size_t maxLen = inputBuffer[bufferUsed]->values.Size();
/* dynamic batching for sentences */
//while ((realBatchSize < (inputBuffer.Size() - bufferUsed))
// && (realBatchSize * maxLen < batchSize)) {
// realBatchSize++;
//}
/* real batch size */
if ((inputBuffer.Size() - bufferUsed) < realBatchSize) {
realBatchSize = inputBuffer.Size() - bufferUsed;
}
CheckNTErrors(maxLen != 0, "invalid length");
int* batchValues = new int[realBatchSize * maxLen];
float* paddingValues = new float[realBatchSize * maxLen];
for (int i = 0; i < realBatchSize * maxLen; i++) {
batchValues[i] = PAD;
paddingValues[i] = 1.0F;
}
size_t curSrc = 0;
/* right padding */
UInt64List infos;
size_t totalLength = 0;
for (int i = 0; i < realBatchSize; ++i) {
infos.Add(inputBuffer[bufferUsed + i]->id);
totalLength += inputBuffer[bufferUsed + i]->values.Size();
curSrc = maxLen * i;
for (int j = 0; j < inputBuffer[bufferUsed + i]->values.Size(); j++)
batchValues[curSrc++] = inputBuffer[bufferUsed + i]->values[j];
while (curSrc < maxLen * (i + 1))
paddingValues[curSrc++] = 0;
}
infos.Add(totalLength);
InitTensor2D(batchEnc, realBatchSize, maxLen, X_INT, devID);
InitTensor2D(paddingEnc, realBatchSize, maxLen, X_FLOAT, devID);
bufferUsed += realBatchSize;
batchEnc->SetData(batchValues, batchEnc->unitNum);
paddingEnc->SetData(paddingValues, paddingEnc->unitNum);
delete[] batchValues;
delete[] paddingValues;
return infos;
}
/*
the constructor of DataSet
>> dataFile - path of the data file
>> srcVocabFN - path of the source vocab file
>> tgtVocabFN - path of the target vocab file
*/
void DataSet::Init(const char* dataFile, const char* srcVocabFN, const char* tgtVocabFN)
{
fp = new ifstream(dataFile);
CheckNTErrors(fp->is_open(), "Can not open the test data");
bufferUsed = 0;
CheckNTErrors(strcmp(srcVocabFN, "") != 0, "missing source vocab file");
CheckNTErrors(strcmp(tgtVocabFN, "") != 0, "missing target vocab file");
srcVocab.Load(srcVocabFN);
/* share source and target vocabs */
if (strcmp(srcVocabFN, tgtVocabFN) == 0) {
XPRINT(0, stderr, "[INFO] share source and target vocabs \n");
tgtVocab.CopyFrom(srcVocab);
}
else {
tgtVocab.Load(tgtVocabFN);
}
LoadDataToBuffer();
}
/* check if the buffer is empty */
bool DataSet::IsEmpty() {
if (bufferUsed < inputBuffer.Size())
return false;
return true;
}
/* dump the translation to a file */
void DataSet::DumpRes(const char* ofn)
{
ofstream ofile(ofn, ios::out);
for (int t = 0; t < outputBuffer.Size(); t++) {
auto res = outputBuffer[t];
for (int i = 0; i < res->res.Size(); i++) {
if (res->res[i] < 4)
break;
ofile << tgtVocab.id2word[res->res[i]] << " ";
}
ofile << "\n";
}
ofile.close();
}
/* de-constructor */
DataSet::~DataSet()
{
/* release the file */
delete fp;
/* release the input buffer */
for (int i = 0; i < inputBuffer.Size(); i++)
delete inputBuffer[i];
/* release the output buffer */
for (int i = 0; i < outputBuffer.Size(); i++)
delete outputBuffer[i];
}
}
|
/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
//
#include <stdlib.h>
#include <eosio/rabbitmq_plugin/rabbitmq_producer.hpp>
#include <eosio/rabbitmq_plugin/rabbitmq_plugin.hpp>
#include <eosio/chain/eosio_contract.hpp>
#include <eosio/chain/config.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/types.hpp>
#include <fc/io/json.hpp>
#include <fc/utf8.hpp>
#include <fc/variant.hpp>
#include <boost/chrono.hpp>
#include <boost/signals2/connection.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
// #include <queue>
namespace fc { class variant; }
namespace eosio {
using chain::account_name;
using chain::action_name;
using chain::block_id_type;
using chain::permission_name;
using chain::transaction;
using chain::signed_transaction;
using chain::signed_block;
using chain::transaction_id_type;
using chain::packed_transaction;
static appbase::abstract_plugin& _rabbitmq_plugin = app().register_plugin<rabbitmq_plugin>();
using rabbitmq_producer_ptr = std::shared_ptr<class rabbitmq_producer>;
class rabbitmq_plugin_impl {
public:
rabbitmq_plugin_impl();
~rabbitmq_plugin_impl();
fc::optional<boost::signals2::scoped_connection> applied_transaction_connection;
chain_plugin *chain_plug;
struct trasaction_info_st {
uint64_t block_number;
fc::time_point block_time;
chain::transaction_trace_ptr trace;
};
void applied_transaction(const chain::transaction_trace_ptr &);
void process_applied_transaction(const trasaction_info_st &);
void init();
bool configured{false};
uint32_t start_block_num = 0;
boost::mutex mtx;
boost::condition_variable condition;
boost::thread consume_thread;
boost::atomic<bool> done{false};
boost::atomic<bool> startup{true};
rabbitmq_producer_ptr producer;
std::string m_applied_trx_exchange = "";
std::string m_applied_trx_exchange_type = "";
};
void rabbitmq_plugin_impl::applied_transaction(const chain::transaction_trace_ptr &t) {
try {
auto &chain = chain_plug->chain();
trasaction_info_st transactioninfo = trasaction_info_st{
.block_number = chain.pending_block_state()->block_num,
.block_time = chain.pending_block_time(),
.trace =chain::transaction_trace_ptr(t)
};
uint64_t time = (transactioninfo.block_time.time_since_epoch().count()/1000);
string transaction_metadata_json =
"{\"block_number\":" + std::to_string(transactioninfo.block_number) + ",\"block_time\":" + std::to_string(time) +
",\"trace\":" + fc::json::to_string(transactioninfo.trace).c_str() + "}";
producer->trx_rabbitmq_sendmsg("", m_applied_trx_exchange,transaction_metadata_json);
} catch (fc::exception &e) {
elog("FC Exception while applied_transaction ${e}", ("e", e.to_string()));
app().quit();
} catch (std::exception &e) {
elog("STD Exception while applied_transaction ${e}", ("e", e.what()));
app().quit();
} catch (...) {
elog("Unknown exception while applied_transaction");
app().quit();
}
}
rabbitmq_plugin_impl::rabbitmq_plugin_impl()
:producer(new rabbitmq_producer)
{
}
rabbitmq_plugin_impl::~rabbitmq_plugin_impl() {
if (!startup) {
try {
ilog( "rabbitmq_db_plugin shutdown in process please be patient this can take a few minutes" );
done = true;
condition.notify_one();
consume_thread.join();
producer->trx_rabbitmq_destroy();
} catch( std::exception& e ) {
elog( "Exception on rabbitmq_plugin shutdown of consume thread: ${e}", ("e", e.what()));
}
}
}
void rabbitmq_plugin_impl::init() {
ilog("starting rabbitmq plugin thread");
// consume_thread = boost::thread([this] { consume_blocks(); });
startup = false;
}
////////////
// rabbitmq_plugin
////////////
rabbitmq_plugin::rabbitmq_plugin()
: my(new rabbitmq_plugin_impl) {
}
rabbitmq_plugin::~rabbitmq_plugin() {
}
void rabbitmq_plugin::set_program_options(options_description &cli, options_description &cfg) {
cfg.add_options()
("rabbitmq-applied-trx-exchange", bpo::value<std::string>()->default_value("trx.applied"),
"The exchange for appiled transaction.")
("rabbitmq-applied-trx-exchange-type", bpo::value<std::string>()->default_value("fanout"),
"The exchange type for appiled transaction.")
("rabbitmq-username", bpo::value<std::string>()->default_value("guest"),
"the rabbitmq username (e.g. guest)")
("rabbitmq-password", bpo::value<std::string>()->default_value("guest"),
"the rabbitmq password (e.g. guest)")
("rabbitmq-hostname", bpo::value<std::string>()->default_value("127.0.0.1"),
"the rabbitmq hostname (e.g. localhost or 127.0.0.1)")
("rabbitmq-port", bpo::value<uint32_t>()->default_value(5672),
"the rabbitmq port (e.g. 5672)")
;
}
void rabbitmq_plugin::plugin_initialize(const variables_map &options) {
try {
if (options.count("rabbitmq-hostname")) {
auto hostname = options.at("rabbitmq-hostname").as<std::string>();
auto username = options.at("rabbitmq-username").as<std::string>();
auto password = options.at("rabbitmq-password").as<std::string>();
uint32_t port = options.at("rabbitmq-port").as<uint32_t>();
if (options.count("rabbitmq-applied-trx-exchange") != 0) {
my->m_applied_trx_exchange = options.at("rabbitmq-applied-trx-exchange").as<std::string>();
}
if (options.count("rabbitmq-applied-trx-exchange-type") != 0) {
my->m_applied_trx_exchange_type = options.at("rabbitmq-applied-trx-exchange-type").as<std::string>();
}
if (0!=my->producer->trx_rabbitmq_init(hostname, port, username, password)){
elog("trx_rabbitmq_init fail, killing node");
app().quit();
} else{
elog("trx_rabbitmq_init ok");
}
if (0!=my->producer->trx_rabbitmq_assert_exchange(my->m_applied_trx_exchange, my->m_applied_trx_exchange_type)){
elog("trx_rabbitmq_init fail, killing node");
app().quit();
} else{
elog("trx_rabbitmq_init ok");
}
ilog("initializing rabbitmq_plugin");
my->configured = true;
// hook up to signals on controller
my->chain_plug = app().find_plugin<chain_plugin>();
EOS_ASSERT(my->chain_plug, chain::missing_chain_plugin_exception, "");
auto &chain = my->chain_plug->chain();
my->applied_transaction_connection.emplace(
chain.applied_transaction.connect([&](const chain::transaction_trace_ptr &t) {
my->applied_transaction(t);
}));
my->init();
} else {
wlog( "eosio::rabbitmq_plugin configured, but no --rabbitmq-hostname specified." );
wlog( "rabbitmq_plugin disabled. killing eos node." );
app().quit();
}
}
FC_LOG_AND_RETHROW()
}
void rabbitmq_plugin::plugin_startup() {
}
void rabbitmq_plugin::plugin_shutdown() {
my->applied_transaction_connection.reset();
my.reset();
}
} // namespace eosio
|
#pragma once
#include <wrtstat/separator_options.hpp>
#include <wrtstat/types.hpp>
namespace wrtstat {
struct aggregator_options
: separator_options
{
size_type outgoing_reduced_size = 128;
};
}
|
/*
; Project: Open Vehicle Monitor System
; Date: 14th March 2017
;
; Changes:
; 1.0 Initial release
;
; (C) 2011 Michael Stegen / Stegen Electronics
; (C) 2011-2017 Mark Webb-Johnson
; (C) 2011 Sonny Chen @ EPRO/DX
;
; 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 "esp32adc.h"
esp32adc::esp32adc(const char* name, adc1_channel_t channel, adc_bits_width_t width, adc_atten_t attn)
: pcp(name)
{
m_channel = channel;
m_width = width;
m_attn = attn;
adc1_config_width(width);
adc1_config_channel_atten(channel,attn);
}
esp32adc::~esp32adc()
{
}
int esp32adc::read()
{
return adc1_get_voltage(m_channel);
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: PlatformAchievementsModelSO
#include "GlobalNamespace/PlatformAchievementsModelSO.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: PlatformAchievementsModelSO/UnlockAchievementCompletionHandler
// [TokenAttribute] Offset: FFFFFFFF
class PlatformAchievementsModelSO::UnlockAchievementCompletionHandler : public System::MulticastDelegate {
public:
// Creating value type constructor for type: UnlockAchievementCompletionHandler
UnlockAchievementCompletionHandler() noexcept {}
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x1F4E56C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PlatformAchievementsModelSO::UnlockAchievementCompletionHandler* New_ctor(::Il2CppObject* object, System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PlatformAchievementsModelSO::UnlockAchievementCompletionHandler*, creationType>(object, method)));
}
// public System.Void Invoke(PlatformAchievementsModelSO/UnlockAchievementResult result)
// Offset: 0x1F4DF48
void Invoke(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult result);
// public System.IAsyncResult BeginInvoke(PlatformAchievementsModelSO/UnlockAchievementResult result, System.AsyncCallback callback, System.Object object)
// Offset: 0x1F4E57C
System::IAsyncResult* BeginInvoke(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult result, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Void EndInvoke(System.IAsyncResult result)
// Offset: 0x1F4E608
void EndInvoke(System::IAsyncResult* result);
}; // PlatformAchievementsModelSO/UnlockAchievementCompletionHandler
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler*, "", "PlatformAchievementsModelSO/UnlockAchievementCompletionHandler");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::*)(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult)>(&GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::Invoke)> {
static const MethodInfo* get() {
static auto* result = &::il2cpp_utils::GetClassFromName("", "PlatformAchievementsModelSO/UnlockAchievementResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IAsyncResult* (GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::*)(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult, System::AsyncCallback*, ::Il2CppObject*)>(&GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::BeginInvoke)> {
static const MethodInfo* get() {
static auto* result = &::il2cpp_utils::GetClassFromName("", "PlatformAchievementsModelSO/UnlockAchievementResult")->byval_arg;
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, callback, object});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::*)(System::IAsyncResult*)>(&GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::EndInvoke)> {
static const MethodInfo* get() {
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result});
}
};
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "packing_arm.h"
#if __ARM_NEON
#include <arm_neon.h>
#endif // __ARM_NEON
namespace ncnn {
DEFINE_LAYER_CREATOR(Packing_arm)
Packing_arm::Packing_arm()
{
support_packing = true;
support_bf16_storage = true;
}
int Packing_arm::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
{
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
bool elemtype_is_bf16 = (elemsize == 2u && elempack == 1) || (elemsize == 8u && elempack == 4);
bool elemtype_is_fp32 = (elemsize == 4u && elempack == 1) || (elemsize == 16u && elempack == 4);
if (opt.use_bf16_storage && elemtype_is_bf16)
return forward_bf16s(bottom_blob, top_blob, opt);
if (use_padding)
{
return Packing::forward(bottom_blob, top_blob, opt);
}
if (!elemtype_is_fp32)
{
// non-fp32 type
return Packing::forward(bottom_blob, top_blob, opt);
}
if (elempack == out_elempack)
{
top_blob = bottom_blob;
return 0;
}
bool pack1to4 = elempack == 1 && out_elempack == 4;
bool pack4to1 = elempack == 4 && out_elempack == 1;
if (!pack1to4 && !pack4to1)
{
return Packing::forward(bottom_blob, top_blob, opt);
}
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
int dims = bottom_blob.dims;
if (!use_padding)
{
// identity if use_padding not allowed
if (dims == 1 && w * elempack % out_elempack != 0)
{
top_blob = bottom_blob;
return 0;
}
if (dims == 2 && h * elempack % out_elempack != 0)
{
top_blob = bottom_blob;
return 0;
}
if (dims == 3 && channels * elempack % out_elempack != 0)
{
top_blob = bottom_blob;
return 0;
}
}
if (dims == 1)
{
top_blob = bottom_blob;
top_blob.w = w * elempack / out_elempack;
top_blob.cstep = w * elempack / out_elempack;
top_blob.elemsize = elemsize / elempack * out_elempack;
top_blob.elempack = out_elempack;
return 0;
}
if (dims == 2)
{
int outh = h * elempack / out_elempack;
size_t out_elemsize = elemsize / elempack * out_elempack;
top_blob.create(w, outh, out_elemsize, out_elempack, opt.blob_allocator);
if (top_blob.empty())
return -100;
if (pack1to4)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = 0; i < outh; i++)
{
const float* r0 = bottom_blob.row(i * 4);
const float* r1 = bottom_blob.row(i * 4 + 1);
const float* r2 = bottom_blob.row(i * 4 + 2);
const float* r3 = bottom_blob.row(i * 4 + 3);
float* outptr = top_blob.row(i);
#if __ARM_NEON
int nn = w >> 2;
int remain = w & 3;
#else
int remain = w;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
float32x4x4_t _p;
_p.val[0] = vld1q_f32(r0);
_p.val[1] = vld1q_f32(r1);
_p.val[2] = vld1q_f32(r2);
_p.val[3] = vld1q_f32(r3);
vst4q_f32(outptr, _p);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
outptr += 16;
}
#endif
for (; remain > 0; remain--)
{
outptr[0] = *r0++;
outptr[1] = *r1++;
outptr[2] = *r2++;
outptr[3] = *r3++;
outptr += 4;
}
}
}
if (pack4to1)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = 0; i < h; i++)
{
const float* r0 = bottom_blob.row(i);
float* outptr0 = top_blob.row(i * 4);
float* outptr1 = top_blob.row(i * 4 + 1);
float* outptr2 = top_blob.row(i * 4 + 2);
float* outptr3 = top_blob.row(i * 4 + 3);
#if __ARM_NEON
int nn = w >> 2;
int remain = w & 3;
#else
int remain = w;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
float32x4x4_t _p = vld4q_f32(r0);
vst1q_f32(outptr0, _p.val[0]);
vst1q_f32(outptr1, _p.val[1]);
vst1q_f32(outptr2, _p.val[2]);
vst1q_f32(outptr3, _p.val[3]);
r0 += 16;
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
}
#endif
for (; remain > 0; remain--)
{
*outptr0++ = r0[0];
*outptr1++ = r0[1];
*outptr2++ = r0[2];
*outptr3++ = r0[3];
r0 += 4;
}
}
}
return 0;
}
if (dims == 3)
{
int size = w * h;
int outc = channels * elempack / out_elempack;
size_t out_elemsize = elemsize / elempack * out_elempack;
top_blob.create(w, h, outc, out_elemsize, out_elempack, opt.blob_allocator);
if (top_blob.empty())
return -100;
if (pack1to4)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < outc; q++)
{
const float* r0 = bottom_blob.channel(q * 4);
const float* r1 = bottom_blob.channel(q * 4 + 1);
const float* r2 = bottom_blob.channel(q * 4 + 2);
const float* r3 = bottom_blob.channel(q * 4 + 3);
float* outptr = top_blob.channel(q);
#if __ARM_NEON
int nn = size >> 2;
int remain = size & 3;
#else
int remain = size;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
float32x4x4_t _p;
_p.val[0] = vld1q_f32(r0);
_p.val[1] = vld1q_f32(r1);
_p.val[2] = vld1q_f32(r2);
_p.val[3] = vld1q_f32(r3);
vst4q_f32(outptr, _p);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
outptr += 16;
}
#endif
for (; remain > 0; remain--)
{
outptr[0] = *r0++;
outptr[1] = *r1++;
outptr[2] = *r2++;
outptr[3] = *r3++;
outptr += 4;
}
}
}
if (pack4to1)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* r0 = bottom_blob.channel(q);
float* outptr0 = top_blob.channel(q * 4);
float* outptr1 = top_blob.channel(q * 4 + 1);
float* outptr2 = top_blob.channel(q * 4 + 2);
float* outptr3 = top_blob.channel(q * 4 + 3);
#if __ARM_NEON
int nn = size >> 2;
int remain = size & 3;
#else
int remain = size;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
float32x4x4_t _p = vld4q_f32(r0);
vst1q_f32(outptr0, _p.val[0]);
vst1q_f32(outptr1, _p.val[1]);
vst1q_f32(outptr2, _p.val[2]);
vst1q_f32(outptr3, _p.val[3]);
r0 += 16;
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
}
#endif
for (; remain > 0; remain--)
{
*outptr0++ = r0[0];
*outptr1++ = r0[1];
*outptr2++ = r0[2];
*outptr3++ = r0[3];
r0 += 4;
}
}
}
return 0;
}
return 0;
}
int Packing_arm::forward_bf16s(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
{
if (use_padding)
{
return Packing::forward(bottom_blob, top_blob, opt);
}
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
if (elempack == out_elempack)
{
top_blob = bottom_blob;
return 0;
}
bool pack1to4 = elempack == 1 && out_elempack == 4;
bool pack4to1 = elempack == 4 && out_elempack == 1;
if (!pack1to4 && !pack4to1)
{
return Packing::forward(bottom_blob, top_blob, opt);
}
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
int dims = bottom_blob.dims;
if (!use_padding)
{
// identity if use_padding not allowed
if (dims == 1 && w * elempack % out_elempack != 0)
{
top_blob = bottom_blob;
return 0;
}
if (dims == 2 && h * elempack % out_elempack != 0)
{
top_blob = bottom_blob;
return 0;
}
if (dims == 3 && channels * elempack % out_elempack != 0)
{
top_blob = bottom_blob;
return 0;
}
}
if (dims == 1)
{
top_blob = bottom_blob;
top_blob.w = w * elempack / out_elempack;
top_blob.cstep = w * elempack / out_elempack;
top_blob.elemsize = elemsize / elempack * out_elempack;
top_blob.elempack = out_elempack;
return 0;
}
if (dims == 2)
{
int outh = h * elempack / out_elempack;
size_t out_elemsize = elemsize / elempack * out_elempack;
top_blob.create(w, outh, out_elemsize, out_elempack, opt.blob_allocator);
if (top_blob.empty())
return -100;
if (pack1to4)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = 0; i < outh; i++)
{
const unsigned short* r0 = bottom_blob.row<const unsigned short>(i * 4);
const unsigned short* r1 = bottom_blob.row<const unsigned short>(i * 4 + 1);
const unsigned short* r2 = bottom_blob.row<const unsigned short>(i * 4 + 2);
const unsigned short* r3 = bottom_blob.row<const unsigned short>(i * 4 + 3);
unsigned short* outptr = top_blob.row<unsigned short>(i);
#if __ARM_NEON
int nn = w >> 2;
int remain = w & 3;
#else
int remain = w;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
uint16x4x4_t _p;
_p.val[0] = vld1_u16(r0);
_p.val[1] = vld1_u16(r1);
_p.val[2] = vld1_u16(r2);
_p.val[3] = vld1_u16(r3);
vst4_u16(outptr, _p);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
outptr += 16;
}
#endif
for (; remain > 0; remain--)
{
outptr[0] = *r0++;
outptr[1] = *r1++;
outptr[2] = *r2++;
outptr[3] = *r3++;
outptr += 4;
}
}
}
if (pack4to1)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = 0; i < h; i++)
{
const unsigned short* r0 = bottom_blob.row<const unsigned short>(i);
unsigned short* outptr0 = top_blob.row<unsigned short>(i * 4);
unsigned short* outptr1 = top_blob.row<unsigned short>(i * 4 + 1);
unsigned short* outptr2 = top_blob.row<unsigned short>(i * 4 + 2);
unsigned short* outptr3 = top_blob.row<unsigned short>(i * 4 + 3);
#if __ARM_NEON
int nn = w >> 2;
int remain = w & 3;
#else
int remain = w;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
uint16x4x4_t _p = vld4_u16(r0);
vst1_u16(outptr0, _p.val[0]);
vst1_u16(outptr1, _p.val[1]);
vst1_u16(outptr2, _p.val[2]);
vst1_u16(outptr3, _p.val[3]);
r0 += 16;
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
}
#endif
for (; remain > 0; remain--)
{
*outptr0++ = r0[0];
*outptr1++ = r0[1];
*outptr2++ = r0[2];
*outptr3++ = r0[3];
r0 += 4;
}
}
}
return 0;
}
if (dims == 3)
{
int size = w * h;
int outc = channels * elempack / out_elempack;
size_t out_elemsize = elemsize / elempack * out_elempack;
top_blob.create(w, h, outc, out_elemsize, out_elempack, opt.blob_allocator);
if (top_blob.empty())
return -100;
if (pack1to4)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < outc; q++)
{
const unsigned short* r0 = bottom_blob.channel(q * 4);
const unsigned short* r1 = bottom_blob.channel(q * 4 + 1);
const unsigned short* r2 = bottom_blob.channel(q * 4 + 2);
const unsigned short* r3 = bottom_blob.channel(q * 4 + 3);
unsigned short* outptr = top_blob.channel(q);
#if __ARM_NEON
int nn = size >> 2;
int remain = size & 3;
#else
int remain = size;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
uint16x4x4_t _p;
_p.val[0] = vld1_u16(r0);
_p.val[1] = vld1_u16(r1);
_p.val[2] = vld1_u16(r2);
_p.val[3] = vld1_u16(r3);
vst4_u16(outptr, _p);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
outptr += 16;
}
#endif
for (; remain > 0; remain--)
{
outptr[0] = *r0++;
outptr[1] = *r1++;
outptr[2] = *r2++;
outptr[3] = *r3++;
outptr += 4;
}
}
}
if (pack4to1)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const unsigned short* r0 = bottom_blob.channel(q);
unsigned short* outptr0 = top_blob.channel(q * 4);
unsigned short* outptr1 = top_blob.channel(q * 4 + 1);
unsigned short* outptr2 = top_blob.channel(q * 4 + 2);
unsigned short* outptr3 = top_blob.channel(q * 4 + 3);
#if __ARM_NEON
int nn = size >> 2;
int remain = size & 3;
#else
int remain = size;
#endif
#if __ARM_NEON
for (; nn > 0; nn--)
{
uint16x4x4_t _p = vld4_u16(r0);
vst1_u16(outptr0, _p.val[0]);
vst1_u16(outptr1, _p.val[1]);
vst1_u16(outptr2, _p.val[2]);
vst1_u16(outptr3, _p.val[3]);
r0 += 16;
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
}
#endif
for (; remain > 0; remain--)
{
*outptr0++ = r0[0];
*outptr1++ = r0[1];
*outptr2++ = r0[2];
*outptr3++ = r0[3];
r0 += 4;
}
}
}
return 0;
}
return 0;
}
} // namespace ncnn
|
/*************************************************************************
> File Name: CountMember.cpp
> Author: Netcan
> Descripton: CountMember
> Blog: https://netcan.github.io/
> Mail: 1469709759@qq.com
> Created Time: 2020-11-09 22:23
************************************************************************/
#include <cstdio>
struct AnyType {
template <typename T> operator T();
};
template <typename T>
consteval size_t CountMember(auto&&... Args) {
if constexpr (requires { T{ Args... }; }) {
return CountMember<T>(Args..., AnyType{});
} else {
return sizeof...(Args) - 1;
}
}
struct Test { int a; int b; int c; int d; };
static_assert(CountMember<Test>() == 4);
int main(int argc, char** argv) {
}
|
//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang attribute processing code
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <algorithm>
#include <cctype>
#include <memory>
#include <set>
#include <sstream>
using namespace llvm;
namespace {
class FlattenedSpelling {
std::string V, N, NS;
bool K;
public:
FlattenedSpelling(const std::string &Variety, const std::string &Name,
const std::string &Namespace, bool KnownToGCC) :
V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
explicit FlattenedSpelling(const Record &Spelling) :
V(Spelling.getValueAsString("Variety")),
N(Spelling.getValueAsString("Name")) {
assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
"flattened!");
if (V == "CXX11" || V == "Pragma")
NS = Spelling.getValueAsString("Namespace");
bool Unset;
K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
}
const std::string &variety() const { return V; }
const std::string &name() const { return N; }
const std::string &nameSpace() const { return NS; }
bool knownToGCC() const { return K; }
};
} // end anonymous namespace
static std::vector<FlattenedSpelling>
GetFlattenedSpellings(const Record &Attr) {
std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
std::vector<FlattenedSpelling> Ret;
for (const auto &Spelling : Spellings) {
if (Spelling->getValueAsString("Variety") == "GCC") {
// Gin up two new spelling objects to add into the list.
Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true);
Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu",
true);
} else
Ret.push_back(FlattenedSpelling(*Spelling));
}
return Ret;
}
static std::string ReadPCHRecord(StringRef type) {
return StringSwitch<std::string>(type)
.EndsWith("Decl *", "GetLocalDeclAs<"
+ std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
.Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
.Case("Expr *", "ReadExpr(F)")
.Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
.Case("std::string", "ReadString(Record, Idx)")
.Default("Record[Idx++]");
}
// Assumes that the way to get the value is SA->getname()
static std::string WritePCHRecord(StringRef type, StringRef name) {
return StringSwitch<std::string>(type)
.EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
", Record);\n")
.Case("TypeSourceInfo *",
"AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
.Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
.Case("IdentifierInfo *",
"AddIdentifierRef(" + std::string(name) + ", Record);\n")
.Case("std::string", "AddString(" + std::string(name) + ", Record);\n")
.Default("Record.push_back(" + std::string(name) + ");\n");
}
// Normalize attribute name by removing leading and trailing
// underscores. For example, __foo, foo__, __foo__ would
// become foo.
static StringRef NormalizeAttrName(StringRef AttrName) {
if (AttrName.startswith("__"))
AttrName = AttrName.substr(2, AttrName.size());
if (AttrName.endswith("__"))
AttrName = AttrName.substr(0, AttrName.size() - 2);
return AttrName;
}
// Normalize the name by removing any and all leading and trailing underscores.
// This is different from NormalizeAttrName in that it also handles names like
// _pascal and __pascal.
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
return Name.trim("_");
}
// Normalize attribute spelling only if the spelling has both leading
// and trailing underscores. For example, __ms_struct__ will be
// normalized to "ms_struct"; __cdecl will remain intact.
static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
}
return AttrSpelling;
}
typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
ParsedAttrMap *Dupes = nullptr) {
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::set<std::string> Seen;
ParsedAttrMap R;
for (const auto *Attr : Attrs) {
if (Attr->getValueAsBit("SemaHandler")) {
std::string AN;
if (Attr->isSubClassOf("TargetSpecificAttr") &&
!Attr->isValueUnset("ParseKind")) {
AN = Attr->getValueAsString("ParseKind");
// If this attribute has already been handled, it does not need to be
// handled again.
if (Seen.find(AN) != Seen.end()) {
if (Dupes)
Dupes->push_back(std::make_pair(AN, Attr));
continue;
}
Seen.insert(AN);
} else
AN = NormalizeAttrName(Attr->getName()).str();
R.push_back(std::make_pair(AN, Attr));
}
}
return R;
}
namespace {
class Argument {
std::string lowerName, upperName;
StringRef attrName;
bool isOpt;
bool Fake;
public:
Argument(const Record &Arg, StringRef Attr)
: lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
attrName(Attr), isOpt(false), Fake(false) {
if (!lowerName.empty()) {
lowerName[0] = std::tolower(lowerName[0]);
upperName[0] = std::toupper(upperName[0]);
}
}
virtual ~Argument() = default;
StringRef getLowerName() const { return lowerName; }
StringRef getUpperName() const { return upperName; }
StringRef getAttrName() const { return attrName; }
bool isOptional() const { return isOpt; }
void setOptional(bool set) { isOpt = set; }
bool isFake() const { return Fake; }
void setFake(bool fake) { Fake = fake; }
// These functions print the argument contents formatted in different ways.
virtual void writeAccessors(raw_ostream &OS) const = 0;
virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
virtual void writeCloneArgs(raw_ostream &OS) const = 0;
virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
virtual void writeCtorBody(raw_ostream &OS) const {}
virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
virtual void writeCtorParameters(raw_ostream &OS) const = 0;
virtual void writeDeclarations(raw_ostream &OS) const = 0;
virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
virtual void writePCHWrite(raw_ostream &OS) const = 0;
virtual void writeValue(raw_ostream &OS) const = 0;
virtual void writeDump(raw_ostream &OS) const = 0;
virtual void writeDumpChildren(raw_ostream &OS) const {}
virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
virtual bool isEnumArg() const { return false; }
virtual bool isVariadicEnumArg() const { return false; }
virtual bool isVariadic() const { return false; }
virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
OS << getUpperName();
}
};
class SimpleArgument : public Argument {
std::string type;
public:
SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
: Argument(Arg, Attr), type(T)
{}
std::string getType() const { return type; }
void writeAccessors(raw_ostream &OS) const override {
OS << " " << type << " get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << getUpperName() << ")";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "()";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << type << " " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << type << " " << getLowerName() << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
std::string read = ReadPCHRecord(type);
OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " " << WritePCHRecord(type, "SA->get" +
std::string(getUpperName()) + "()");
}
void writeValue(raw_ostream &OS) const override {
if (type == "FunctionDecl *") {
OS << "\" << get" << getUpperName()
<< "()->getNameInfo().getAsString() << \"";
} else if (type == "IdentifierInfo *") {
OS << "\" << get" << getUpperName() << "()->getName() << \"";
} else if (type == "TypeSourceInfo *") {
OS << "\" << get" << getUpperName() << "().getAsString() << \"";
} else {
OS << "\" << get" << getUpperName() << "() << \"";
}
}
void writeDump(raw_ostream &OS) const override {
if (type == "FunctionDecl *") {
OS << " OS << \" \";\n";
OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
} else if (type == "IdentifierInfo *") {
if (isOptional())
OS << " if (SA->get" << getUpperName() << "())\n ";
OS << " OS << \" \" << SA->get" << getUpperName()
<< "()->getName();\n";
} else if (type == "TypeSourceInfo *") {
OS << " OS << \" \" << SA->get" << getUpperName()
<< "().getAsString();\n";
} else if (type == "bool") {
OS << " if (SA->get" << getUpperName() << "()) OS << \" "
<< getUpperName() << "\";\n";
} else if (type == "int" || type == "unsigned") {
OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
} else {
llvm_unreachable("Unknown SimpleArgument type!");
}
}
};
class DefaultSimpleArgument : public SimpleArgument {
int64_t Default;
public:
DefaultSimpleArgument(const Record &Arg, StringRef Attr,
std::string T, int64_t Default)
: SimpleArgument(Arg, Attr, T), Default(Default) {}
void writeAccessors(raw_ostream &OS) const override {
SimpleArgument::writeAccessors(OS);
OS << "\n\n static const " << getType() << " Default" << getUpperName()
<< " = " << Default << ";";
}
};
class StringArgument : public Argument {
public:
StringArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr)
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
OS << " return llvm::StringRef(" << getLowerName() << ", "
<< getLowerName() << "Length);\n";
OS << " }\n";
OS << " unsigned get" << getUpperName() << "Length() const {\n";
OS << " return " << getLowerName() << "Length;\n";
OS << " }\n";
OS << " void set" << getUpperName()
<< "(ASTContext &C, llvm::StringRef S) {\n";
OS << " " << getLowerName() << "Length = S.size();\n";
OS << " this->" << getLowerName() << " = new (C, 1) char ["
<< getLowerName() << "Length];\n";
OS << " if (!S.empty())\n";
OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
<< getLowerName() << "Length);\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << "get" << getUpperName() << "()";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorBody(raw_ostream &OS) const override {
OS << " if (!" << getUpperName() << ".empty())\n";
OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
<< ".data(), " << getLowerName() << "Length);";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
<< getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
<< "Length])";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << "llvm::StringRef " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << "unsigned " << getLowerName() << "Length;\n";
OS << "char *" << getLowerName() << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " std::string " << getLowerName()
<< "= ReadString(Record, Idx);\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " AddString(SA->get" << getUpperName() << "(), Record);\n";
}
void writeValue(raw_ostream &OS) const override {
OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
}
void writeDump(raw_ostream &OS) const override {
OS << " OS << \" \\\"\" << SA->get" << getUpperName()
<< "() << \"\\\"\";\n";
}
};
class AlignedArgument : public Argument {
public:
AlignedArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr)
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " bool is" << getUpperName() << "Dependent() const;\n";
OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
OS << " bool is" << getUpperName() << "Expr() const {\n";
OS << " return is" << getLowerName() << "Expr;\n";
OS << " }\n";
OS << " Expr *get" << getUpperName() << "Expr() const {\n";
OS << " assert(is" << getLowerName() << "Expr);\n";
OS << " return " << getLowerName() << "Expr;\n";
OS << " }\n";
OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
OS << " assert(!is" << getLowerName() << "Expr);\n";
OS << " return " << getLowerName() << "Type;\n";
OS << " }";
}
void writeAccessorDefinitions(raw_ostream &OS) const override {
OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
<< "Dependent() const {\n";
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " return " << getLowerName() << "Expr && (" << getLowerName()
<< "Expr->isValueDependent() || " << getLowerName()
<< "Expr->isTypeDependent());\n";
OS << " else\n";
OS << " return " << getLowerName()
<< "Type->getType()->isDependentType();\n";
OS << "}\n";
// FIXME: Do not do the calculation here
// FIXME: Handle types correctly
// A null pointer means maximum alignment
OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
<< "(ASTContext &Ctx) const {\n";
OS << " assert(!is" << getUpperName() << "Dependent());\n";
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " return " << getLowerName() << "Expr ? " << getLowerName()
<< "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
<< " * Ctx.getCharWidth() : "
<< "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
OS << " else\n";
OS << " return 0; // FIXME\n";
OS << "}\n";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr, is" << getLowerName()
<< "Expr ? static_cast<void*>(" << getLowerName()
<< "Expr) : " << getLowerName()
<< "Type";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
// FIXME: move the definition in Sema::InstantiateAttrs to here.
// In the meantime, aligned attributes are cloned.
}
void writeCtorBody(raw_ostream &OS) const override {
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
<< getUpperName() << ");\n";
OS << " else\n";
OS << " " << getLowerName()
<< "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
<< ");";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr(false)";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
}
void writeImplicitCtorArgs(raw_ostream &OS) const override {
OS << "Is" << getUpperName() << "Expr, " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << "bool is" << getLowerName() << "Expr;\n";
OS << "union {\n";
OS << "Expr *" << getLowerName() << "Expr;\n";
OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
OS << "};";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
OS << " void *" << getLowerName() << "Ptr;\n";
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
OS << " else\n";
OS << " " << getLowerName()
<< "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
OS << " if (SA->is" << getUpperName() << "Expr())\n";
OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n";
OS << " else\n";
OS << " AddTypeSourceInfo(SA->get" << getUpperName()
<< "Type(), Record);\n";
}
void writeValue(raw_ostream &OS) const override {
OS << "\";\n";
// The aligned attribute argument expression is optional.
OS << " if (is" << getLowerName() << "Expr && "
<< getLowerName() << "Expr)\n";
OS << " " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
OS << " OS << \"";
}
void writeDump(raw_ostream &OS) const override {
}
void writeDumpChildren(raw_ostream &OS) const override {
OS << " if (SA->is" << getUpperName() << "Expr())\n";
OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
OS << " else\n";
OS << " dumpType(SA->get" << getUpperName()
<< "Type()->getType());\n";
}
void writeHasChildren(raw_ostream &OS) const override {
OS << "SA->is" << getUpperName() << "Expr()";
}
};
class VariadicArgument : public Argument {
std::string Type, ArgName, ArgSizeName, RangeName;
protected:
// Assumed to receive a parameter: raw_ostream OS.
virtual void writeValueImpl(raw_ostream &OS) const {
OS << " OS << Val;\n";
}
public:
VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
: Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
std::string getType() const { return Type; }
bool isVariadic() const override { return true; }
void writeAccessors(raw_ostream &OS) const override {
std::string IteratorType = getLowerName().str() + "_iterator";
std::string BeginFn = getLowerName().str() + "_begin()";
std::string EndFn = getLowerName().str() + "_end()";
OS << " typedef " << Type << "* " << IteratorType << ";\n";
OS << " " << IteratorType << " " << BeginFn << " const {"
<< " return " << ArgName << "; }\n";
OS << " " << IteratorType << " " << EndFn << " const {"
<< " return " << ArgName << " + " << ArgSizeName << "; }\n";
OS << " unsigned " << getLowerName() << "_size() const {"
<< " return " << ArgSizeName << "; }\n";
OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
<< "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
<< "); }\n";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << ArgName << ", " << ArgSizeName;
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
// This isn't elegant, but we have to go through public methods...
OS << "A->" << getLowerName() << "_begin(), "
<< "A->" << getLowerName() << "_size()";
}
void writeCtorBody(raw_ostream &OS) const override {
OS << " std::copy(" << getUpperName() << ", " << getUpperName()
<< " + " << ArgSizeName << ", " << ArgName << ");";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << ArgSizeName << "(" << getUpperName() << "Size), "
<< ArgName << "(new (Ctx, 16) " << getType() << "["
<< ArgSizeName << "])";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << getType() << " *" << getUpperName() << ", unsigned "
<< getUpperName() << "Size";
}
void writeImplicitCtorArgs(raw_ostream &OS) const override {
OS << getUpperName() << ", " << getUpperName() << "Size";
}
void writeDeclarations(raw_ostream &OS) const override {
OS << " unsigned " << ArgSizeName << ";\n";
OS << " " << getType() << " *" << ArgName << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
OS << " SmallVector<" << Type << ", 4> " << getLowerName()
<< ";\n";
OS << " " << getLowerName() << ".reserve(" << getLowerName()
<< "Size);\n";
OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
std::string read = ReadPCHRecord(Type);
OS << " " << getLowerName() << ".push_back(" << read << ");\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName() << ".data(), " << getLowerName() << "Size";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
OS << " for (auto &Val : SA->" << RangeName << "())\n";
OS << " " << WritePCHRecord(Type, "Val");
}
void writeValue(raw_ostream &OS) const override {
OS << "\";\n";
OS << " bool isFirst = true;\n"
<< " for (const auto &Val : " << RangeName << "()) {\n"
<< " if (isFirst) isFirst = false;\n"
<< " else OS << \", \";\n";
writeValueImpl(OS);
OS << " }\n";
OS << " OS << \"";
}
void writeDump(raw_ostream &OS) const override {
OS << " for (const auto &Val : SA->" << RangeName << "())\n";
OS << " OS << \" \" << Val;\n";
}
};
// Unique the enums, but maintain the original declaration ordering.
std::vector<std::string>
uniqueEnumsInOrder(const std::vector<std::string> &enums) {
std::vector<std::string> uniques;
std::set<std::string> unique_set(enums.begin(), enums.end());
for (const auto &i : enums) {
auto set_i = unique_set.find(i);
if (set_i != unique_set.end()) {
uniques.push_back(i);
unique_set.erase(set_i);
}
}
return uniques;
}
class EnumArgument : public Argument {
std::string type;
std::vector<std::string> values, enums, uniques;
public:
EnumArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
values(Arg.getValueAsListOfStrings("Values")),
enums(Arg.getValueAsListOfStrings("Enums")),
uniques(uniqueEnumsInOrder(enums))
{
// FIXME: Emit a proper error
assert(!uniques.empty());
}
bool isEnumArg() const override { return true; }
void writeAccessors(raw_ostream &OS) const override {
OS << " " << type << " get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << getUpperName() << ")";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << type << "(0))";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << type << " " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
auto i = uniques.cbegin(), e = uniques.cend();
// The last one needs to not have a comma.
--e;
OS << "public:\n";
OS << " enum " << type << " {\n";
for (; i != e; ++i)
OS << " " << *i << ",\n";
OS << " " << *e << "\n";
OS << " };\n";
OS << "private:\n";
OS << " " << type << " " << getLowerName() << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
<< "(static_cast<" << getAttrName() << "Attr::" << type
<< ">(Record[Idx++]));\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
}
void writeValue(raw_ostream &OS) const override {
// FIXME: this isn't 100% correct -- some enum arguments require printing
// as a string literal, while others require printing as an identifier.
// Tablegen currently does not distinguish between the two forms.
OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
<< getUpperName() << "()) << \"\\\"";
}
void writeDump(raw_ostream &OS) const override {
OS << " switch(SA->get" << getUpperName() << "()) {\n";
for (const auto &I : uniques) {
OS << " case " << getAttrName() << "Attr::" << I << ":\n";
OS << " OS << \" " << I << "\";\n";
OS << " break;\n";
}
OS << " }\n";
}
void writeConversion(raw_ostream &OS) const {
OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
OS << type << " &Out) {\n";
OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
OS << type << ">>(Val)\n";
for (size_t I = 0; I < enums.size(); ++I) {
OS << " .Case(\"" << values[I] << "\", ";
OS << getAttrName() << "Attr::" << enums[I] << ")\n";
}
OS << " .Default(Optional<" << type << ">());\n";
OS << " if (R) {\n";
OS << " Out = *R;\n return true;\n }\n";
OS << " return false;\n";
OS << " }\n\n";
// Mapping from enumeration values back to enumeration strings isn't
// trivial because some enumeration values have multiple named
// enumerators, such as type_visibility(internal) and
// type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
OS << " static const char *Convert" << type << "ToStr("
<< type << " Val) {\n"
<< " switch(Val) {\n";
std::set<std::string> Uniques;
for (size_t I = 0; I < enums.size(); ++I) {
if (Uniques.insert(enums[I]).second)
OS << " case " << getAttrName() << "Attr::" << enums[I]
<< ": return \"" << values[I] << "\";\n";
}
OS << " }\n"
<< " llvm_unreachable(\"No enumerator with that value\");\n"
<< " }\n";
}
};
class VariadicEnumArgument: public VariadicArgument {
std::string type, QualifiedTypeName;
std::vector<std::string> values, enums, uniques;
protected:
void writeValueImpl(raw_ostream &OS) const override {
// FIXME: this isn't 100% correct -- some enum arguments require printing
// as a string literal, while others require printing as an identifier.
// Tablegen currently does not distinguish between the two forms.
OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
<< "ToStr(Val)" << "<< \"\\\"\";\n";
}
public:
VariadicEnumArgument(const Record &Arg, StringRef Attr)
: VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
type(Arg.getValueAsString("Type")),
values(Arg.getValueAsListOfStrings("Values")),
enums(Arg.getValueAsListOfStrings("Enums")),
uniques(uniqueEnumsInOrder(enums))
{
QualifiedTypeName = getAttrName().str() + "Attr::" + type;
// FIXME: Emit a proper error
assert(!uniques.empty());
}
bool isVariadicEnumArg() const override { return true; }
void writeDeclarations(raw_ostream &OS) const override {
auto i = uniques.cbegin(), e = uniques.cend();
// The last one needs to not have a comma.
--e;
OS << "public:\n";
OS << " enum " << type << " {\n";
for (; i != e; ++i)
OS << " " << *i << ",\n";
OS << " " << *e << "\n";
OS << " };\n";
OS << "private:\n";
VariadicArgument::writeDeclarations(OS);
}
void writeDump(raw_ostream &OS) const override {
OS << " for (" << getAttrName() << "Attr::" << getLowerName()
<< "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
<< getLowerName() << "_end(); I != E; ++I) {\n";
OS << " switch(*I) {\n";
for (const auto &UI : uniques) {
OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
OS << " OS << \" " << UI << "\";\n";
OS << " break;\n";
}
OS << " }\n";
OS << " }\n";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
<< ";\n";
OS << " " << getLowerName() << ".reserve(" << getLowerName()
<< "Size);\n";
OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
OS << " " << getLowerName() << ".push_back(" << "static_cast<"
<< QualifiedTypeName << ">(Record[Idx++]));\n";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
OS << " for (" << getAttrName() << "Attr::" << getLowerName()
<< "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
<< getLowerName() << "_end(); i != e; ++i)\n";
OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
}
void writeConversion(raw_ostream &OS) const {
OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
OS << type << " &Out) {\n";
OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
OS << type << ">>(Val)\n";
for (size_t I = 0; I < enums.size(); ++I) {
OS << " .Case(\"" << values[I] << "\", ";
OS << getAttrName() << "Attr::" << enums[I] << ")\n";
}
OS << " .Default(Optional<" << type << ">());\n";
OS << " if (R) {\n";
OS << " Out = *R;\n return true;\n }\n";
OS << " return false;\n";
OS << " }\n\n";
OS << " static const char *Convert" << type << "ToStr("
<< type << " Val) {\n"
<< " switch(Val) {\n";
std::set<std::string> Uniques;
for (size_t I = 0; I < enums.size(); ++I) {
if (Uniques.insert(enums[I]).second)
OS << " case " << getAttrName() << "Attr::" << enums[I]
<< ": return \"" << values[I] << "\";\n";
}
OS << " }\n"
<< " llvm_unreachable(\"No enumerator with that value\");\n"
<< " }\n";
}
};
class VersionArgument : public Argument {
public:
VersionArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr)
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " VersionTuple get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }\n";
OS << " void set" << getUpperName()
<< "(ASTContext &C, VersionTuple V) {\n";
OS << " " << getLowerName() << " = V;\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << "get" << getUpperName() << "()";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << getUpperName() << ")";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "()";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << "VersionTuple " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << "VersionTuple " << getLowerName() << ";\n";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " VersionTuple " << getLowerName()
<< "= ReadVersionTuple(Record, Idx);\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
}
void writeValue(raw_ostream &OS) const override {
OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
}
void writeDump(raw_ostream &OS) const override {
OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
}
};
class ExprArgument : public SimpleArgument {
public:
ExprArgument(const Record &Arg, StringRef Attr)
: SimpleArgument(Arg, Attr, "Expr *")
{}
void writeASTVisitorTraversal(raw_ostream &OS) const override {
OS << " if (!"
<< "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
OS << " return false;\n";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "tempInst" << getUpperName();
}
void writeTemplateInstantiation(raw_ostream &OS) const override {
OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
OS << " {\n";
OS << " EnterExpressionEvaluationContext "
<< "Unevaluated(S, Sema::Unevaluated);\n";
OS << " ExprResult " << "Result = S.SubstExpr("
<< "A->get" << getUpperName() << "(), TemplateArgs);\n";
OS << " tempInst" << getUpperName() << " = "
<< "Result.getAs<Expr>();\n";
OS << " }\n";
}
void writeDump(raw_ostream &OS) const override {}
void writeDumpChildren(raw_ostream &OS) const override {
OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
}
void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
};
class VariadicExprArgument : public VariadicArgument {
public:
VariadicExprArgument(const Record &Arg, StringRef Attr)
: VariadicArgument(Arg, Attr, "Expr *")
{}
void writeASTVisitorTraversal(raw_ostream &OS) const override {
OS << " {\n";
OS << " " << getType() << " *I = A->" << getLowerName()
<< "_begin();\n";
OS << " " << getType() << " *E = A->" << getLowerName()
<< "_end();\n";
OS << " for (; I != E; ++I) {\n";
OS << " if (!getDerived().TraverseStmt(*I))\n";
OS << " return false;\n";
OS << " }\n";
OS << " }\n";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "tempInst" << getUpperName() << ", "
<< "A->" << getLowerName() << "_size()";
}
void writeTemplateInstantiation(raw_ostream &OS) const override {
OS << " auto *tempInst" << getUpperName()
<< " = new (C, 16) " << getType()
<< "[A->" << getLowerName() << "_size()];\n";
OS << " {\n";
OS << " EnterExpressionEvaluationContext "
<< "Unevaluated(S, Sema::Unevaluated);\n";
OS << " " << getType() << " *TI = tempInst" << getUpperName()
<< ";\n";
OS << " " << getType() << " *I = A->" << getLowerName()
<< "_begin();\n";
OS << " " << getType() << " *E = A->" << getLowerName()
<< "_end();\n";
OS << " for (; I != E; ++I, ++TI) {\n";
OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
OS << " *TI = Result.getAs<Expr>();\n";
OS << " }\n";
OS << " }\n";
}
void writeDump(raw_ostream &OS) const override {}
void writeDumpChildren(raw_ostream &OS) const override {
OS << " for (" << getAttrName() << "Attr::" << getLowerName()
<< "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
<< getLowerName() << "_end(); I != E; ++I)\n";
OS << " dumpStmt(*I);\n";
}
void writeHasChildren(raw_ostream &OS) const override {
OS << "SA->" << getLowerName() << "_begin() != "
<< "SA->" << getLowerName() << "_end()";
}
};
class VariadicStringArgument : public VariadicArgument {
public:
VariadicStringArgument(const Record &Arg, StringRef Attr)
: VariadicArgument(Arg, Attr, "std::string")
{}
void writeValueImpl(raw_ostream &OS) const override {
OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
}
};
class TypeArgument : public SimpleArgument {
public:
TypeArgument(const Record &Arg, StringRef Attr)
: SimpleArgument(Arg, Attr, "TypeSourceInfo *")
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " QualType get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << "->getType();\n";
OS << " }";
OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "Loc()";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " " << WritePCHRecord(
getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
}
};
} // end anonymous namespace
static std::unique_ptr<Argument>
createArgument(const Record &Arg, StringRef Attr,
const Record *Search = nullptr) {
if (!Search)
Search = &Arg;
std::unique_ptr<Argument> Ptr;
llvm::StringRef ArgName = Search->getName();
if (ArgName == "AlignedArgument")
Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
else if (ArgName == "EnumArgument")
Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
else if (ArgName == "ExprArgument")
Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
else if (ArgName == "FunctionArgument")
Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
else if (ArgName == "IdentifierArgument")
Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
else if (ArgName == "DefaultBoolArgument")
Ptr = llvm::make_unique<DefaultSimpleArgument>(
Arg, Attr, "bool", Arg.getValueAsBit("Default"));
else if (ArgName == "BoolArgument")
Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
else if (ArgName == "DefaultIntArgument")
Ptr = llvm::make_unique<DefaultSimpleArgument>(
Arg, Attr, "int", Arg.getValueAsInt("Default"));
else if (ArgName == "IntArgument")
Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
else if (ArgName == "StringArgument")
Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
else if (ArgName == "TypeArgument")
Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
else if (ArgName == "UnsignedArgument")
Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
else if (ArgName == "VariadicUnsignedArgument")
Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
else if (ArgName == "VariadicStringArgument")
Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
else if (ArgName == "VariadicEnumArgument")
Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
else if (ArgName == "VariadicExprArgument")
Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
else if (ArgName == "VersionArgument")
Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
if (!Ptr) {
// Search in reverse order so that the most-derived type is handled first.
ArrayRef<Record*> Bases = Search->getSuperClasses();
for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
if ((Ptr = createArgument(Arg, Attr, Base)))
break;
}
}
if (Ptr && Arg.getValueAsBit("Optional"))
Ptr->setOptional(true);
if (Ptr && Arg.getValueAsBit("Fake"))
Ptr->setFake(true);
return Ptr;
}
static void writeAvailabilityValue(raw_ostream &OS) {
OS << "\" << getPlatform()->getName();\n"
<< " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
<< " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
<< " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
<< " if (getUnavailable()) OS << \", unavailable\";\n"
<< " OS << \"";
}
static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
if (Spellings.empty()) {
OS << " return \"(No spelling)\";\n}\n\n";
return;
}
OS << " switch (SpellingListIndex) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute spelling!\");\n"
" return \"(No spelling)\";\n";
for (unsigned I = 0; I < Spellings.size(); ++I)
OS << " case " << I << ":\n"
" return \"" << Spellings[I].name() << "\";\n";
// End of the switch statement.
OS << " }\n";
// End of the getSpelling function.
OS << "}\n\n";
}
static void
writePrettyPrintFunction(Record &R,
const std::vector<std::unique_ptr<Argument>> &Args,
raw_ostream &OS) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
OS << "void " << R.getName() << "Attr::printPretty("
<< "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
if (Spellings.empty()) {
OS << "}\n\n";
return;
}
OS <<
" switch (SpellingListIndex) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute spelling!\");\n"
" break;\n";
for (unsigned I = 0; I < Spellings.size(); ++ I) {
llvm::SmallString<16> Prefix;
llvm::SmallString<8> Suffix;
// The actual spelling of the name and namespace (if applicable)
// of an attribute without considering prefix and suffix.
llvm::SmallString<64> Spelling;
std::string Name = Spellings[I].name();
std::string Variety = Spellings[I].variety();
if (Variety == "GNU") {
Prefix = " __attribute__((";
Suffix = "))";
} else if (Variety == "CXX11") {
Prefix = " [[";
Suffix = "]]";
std::string Namespace = Spellings[I].nameSpace();
if (!Namespace.empty()) {
Spelling += Namespace;
Spelling += "::";
}
} else if (Variety == "Declspec") {
Prefix = " __declspec(";
Suffix = ")";
} else if (Variety == "Keyword") {
Prefix = " ";
Suffix = "";
} else if (Variety == "Pragma") {
Prefix = "#pragma ";
Suffix = "\n";
std::string Namespace = Spellings[I].nameSpace();
if (!Namespace.empty()) {
Spelling += Namespace;
Spelling += " ";
}
} else {
llvm_unreachable("Unknown attribute syntax variety!");
}
Spelling += Name;
OS <<
" case " << I << " : {\n"
" OS << \"" << Prefix << Spelling;
if (Variety == "Pragma") {
OS << " \";\n";
OS << " printPrettyPragma(OS, Policy);\n";
OS << " OS << \"\\n\";";
OS << " break;\n";
OS << " }\n";
continue;
}
// Fake arguments aren't part of the parsed form and should not be
// pretty-printed.
bool hasNonFakeArgs = false;
for (const auto &arg : Args) {
if (arg->isFake()) continue;
hasNonFakeArgs = true;
}
// FIXME: always printing the parenthesis isn't the correct behavior for
// attributes which have optional arguments that were not provided. For
// instance: __attribute__((aligned)) will be pretty printed as
// __attribute__((aligned())). The logic should check whether there is only
// a single argument, and if it is optional, whether it has been provided.
if (hasNonFakeArgs)
OS << "(";
if (Spelling == "availability") {
writeAvailabilityValue(OS);
} else {
unsigned index = 0;
for (const auto &arg : Args) {
if (arg->isFake()) continue;
if (index++) OS << ", ";
arg->writeValue(OS);
}
}
if (hasNonFakeArgs)
OS << ")";
OS << Suffix + "\";\n";
OS <<
" break;\n"
" }\n";
}
// End of the switch statement.
OS << "}\n";
// End of the print function.
OS << "}\n\n";
}
/// \brief Return the index of a spelling in a spelling list.
static unsigned
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
const FlattenedSpelling &Spelling) {
assert(!SpellingList.empty() && "Spelling list is empty!");
for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
const FlattenedSpelling &S = SpellingList[Index];
if (S.variety() != Spelling.variety())
continue;
if (S.nameSpace() != Spelling.nameSpace())
continue;
if (S.name() != Spelling.name())
continue;
return Index;
}
llvm_unreachable("Unknown spelling!");
}
static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
for (const auto *Accessor : Accessors) {
std::string Name = Accessor->getValueAsString("Name");
std::vector<FlattenedSpelling> Spellings =
GetFlattenedSpellings(*Accessor);
std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
assert(!SpellingList.empty() &&
"Attribute with empty spelling list can't have accessors!");
OS << " bool " << Name << "() const { return SpellingListIndex == ";
for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
OS << getSpellingListIndex(SpellingList, Spellings[Index]);
if (Index != Spellings.size() -1)
OS << " ||\n SpellingListIndex == ";
else
OS << "; }\n";
}
}
}
static bool
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
assert(!Spellings.empty() && "An empty list of spellings was provided");
std::string FirstName = NormalizeNameForSpellingComparison(
Spellings.front().name());
for (const auto &Spelling :
llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
if (Name != FirstName)
return false;
}
return true;
}
typedef std::map<unsigned, std::string> SemanticSpellingMap;
static std::string
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
SemanticSpellingMap &Map) {
// The enumerants are automatically generated based on the variety,
// namespace (if present) and name for each attribute spelling. However,
// care is taken to avoid trampling on the reserved namespace due to
// underscores.
std::string Ret(" enum Spelling {\n");
std::set<std::string> Uniques;
unsigned Idx = 0;
for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
const FlattenedSpelling &S = *I;
std::string Variety = S.variety();
std::string Spelling = S.name();
std::string Namespace = S.nameSpace();
std::string EnumName = "";
EnumName += (Variety + "_");
if (!Namespace.empty())
EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
"_");
EnumName += NormalizeNameForSpellingComparison(Spelling);
// Even if the name is not unique, this spelling index corresponds to a
// particular enumerant name that we've calculated.
Map[Idx] = EnumName;
// Since we have been stripping underscores to avoid trampling on the
// reserved namespace, we may have inadvertently created duplicate
// enumerant names. These duplicates are not considered part of the
// semantic spelling, and can be elided.
if (Uniques.find(EnumName) != Uniques.end())
continue;
Uniques.insert(EnumName);
if (I != Spellings.begin())
Ret += ",\n";
// Duplicate spellings are not considered part of the semantic spelling
// enumeration, but the spelling index and semantic spelling values are
// meant to be equivalent, so we must specify a concrete value for each
// enumerator.
Ret += " " + EnumName + " = " + llvm::utostr(Idx);
}
Ret += "\n };\n\n";
return Ret;
}
void WriteSemanticSpellingSwitch(const std::string &VarName,
const SemanticSpellingMap &Map,
raw_ostream &OS) {
OS << " switch (" << VarName << ") {\n default: "
<< "llvm_unreachable(\"Unknown spelling list index\");\n";
for (const auto &I : Map)
OS << " case " << I.first << ": return " << I.second << ";\n";
OS << " }\n";
}
// Emits the LateParsed property for attributes.
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
bool LateParsed = Attr->getValueAsBit("LateParsed");
if (LateParsed) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
// FIXME: Handle non-GNU attributes
for (const auto &I : Spellings) {
if (I.variety() != "GNU")
continue;
OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
}
}
}
OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
}
/// \brief Emits the first-argument-is-type property for attributes.
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
// Determine whether the first argument is a type.
std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
if (Args.empty())
continue;
if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
continue;
// All these spellings take a single type argument.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
std::set<std::string> Emitted;
for (const auto &S : Spellings) {
if (Emitted.insert(S.name()).second)
OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
}
}
OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
}
/// \brief Emits the parse-arguments-in-unevaluated-context property for
/// attributes.
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
ParsedAttrMap Attrs = getParsedAttrList(Records);
for (const auto &I : Attrs) {
const Record &Attr = *I.second;
if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
continue;
// All these spellings take are parsed unevaluated.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
std::set<std::string> Emitted;
for (const auto &S : Spellings) {
if (Emitted.insert(S.name()).second)
OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
}
}
OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
}
static bool isIdentifierArgument(Record *Arg) {
return !Arg->getSuperClasses().empty() &&
llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
.Case("IdentifierArgument", true)
.Case("EnumArgument", true)
.Case("VariadicEnumArgument", true)
.Default(false);
}
// Emits the first-argument-is-identifier property for attributes.
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
// Determine whether the first argument is an identifier.
std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
if (Args.empty() || !isIdentifierArgument(Args[0]))
continue;
// All these spellings take an identifier argument.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
std::set<std::string> Emitted;
for (const auto &S : Spellings) {
if (Emitted.insert(S.name()).second)
OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
}
}
OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
}
namespace clang {
// Emits the class definitions for attributes.
void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute classes' definitions", OS);
OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
// FIXME: Currently, documentation is generated as-needed due to the fact
// that there is no way to allow a generated project "reach into" the docs
// directory (for instance, it may be an out-of-tree build). However, we want
// to ensure that every attribute has a Documentation field, and produce an
// error if it has been neglected. Otherwise, the on-demand generation which
// happens server-side will fail. This code is ensuring that functionality,
// even though this Emitter doesn't technically need the documentation.
// When attribute documentation can be generated as part of the build
// itself, this code can be removed.
(void)R.getValueAsListOfDefs("Documentation");
if (!R.getValueAsBit("ASTNode"))
continue;
ArrayRef<Record *> Supers = R.getSuperClasses();
assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
std::string SuperName;
for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
const Record &R = *Super;
if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
SuperName = R.getName();
}
OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
std::vector<std::unique_ptr<Argument>> Args;
Args.reserve(ArgRecords.size());
bool HasOptArg = false;
bool HasFakeArg = false;
for (const auto *ArgRecord : ArgRecords) {
Args.emplace_back(createArgument(*ArgRecord, R.getName()));
Args.back()->writeDeclarations(OS);
OS << "\n\n";
// For these purposes, fake takes priority over optional.
if (Args.back()->isFake()) {
HasFakeArg = true;
} else if (Args.back()->isOptional()) {
HasOptArg = true;
}
}
OS << "\npublic:\n";
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
// If there are zero or one spellings, all spelling-related functionality
// can be elided. If all of the spellings share the same name, the spelling
// functionality can also be elided.
bool ElideSpelling = (Spellings.size() <= 1) ||
SpellingNamesAreCommon(Spellings);
// This maps spelling index values to semantic Spelling enumerants.
SemanticSpellingMap SemanticToSyntacticMap;
if (!ElideSpelling)
OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
// Emit CreateImplicit factory methods.
auto emitCreateImplicit = [&](bool emitFake) {
OS << " static " << R.getName() << "Attr *CreateImplicit(";
OS << "ASTContext &Ctx";
if (!ElideSpelling)
OS << ", Spelling S";
for (auto const &ai : Args) {
if (ai->isFake() && !emitFake) continue;
OS << ", ";
ai->writeCtorParameters(OS);
}
OS << ", SourceRange Loc = SourceRange()";
OS << ") {\n";
OS << " auto *A = new (Ctx) " << R.getName();
OS << "Attr(Loc, Ctx, ";
for (auto const &ai : Args) {
if (ai->isFake() && !emitFake) continue;
ai->writeImplicitCtorArgs(OS);
OS << ", ";
}
OS << (ElideSpelling ? "0" : "S") << ");\n";
OS << " A->setImplicit(true);\n";
OS << " return A;\n }\n\n";
};
// Emit a CreateImplicit that takes all the arguments.
emitCreateImplicit(true);
// Emit a CreateImplicit that takes all the non-fake arguments.
if (HasFakeArg) {
emitCreateImplicit(false);
}
// Emit constructors.
auto emitCtor = [&](bool emitOpt, bool emitFake) {
auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
if (arg->isFake()) return emitFake;
if (arg->isOptional()) return emitOpt;
return true;
};
OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
for (auto const &ai : Args) {
if (!shouldEmitArg(ai)) continue;
OS << " , ";
ai->writeCtorParameters(OS);
OS << "\n";
}
OS << " , ";
OS << "unsigned SI\n";
OS << " )\n";
OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
<< R.getValueAsBit("LateParsed") << ", "
<< R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
for (auto const &ai : Args) {
OS << " , ";
if (!shouldEmitArg(ai)) {
ai->writeCtorDefaultInitializers(OS);
} else {
ai->writeCtorInitializers(OS);
}
OS << "\n";
}
OS << " {\n";
for (auto const &ai : Args) {
if (!shouldEmitArg(ai)) continue;
ai->writeCtorBody(OS);
OS << "\n";
}
OS << " }\n\n";
};
// Emit a constructor that includes all the arguments.
// This is necessary for cloning.
emitCtor(true, true);
// Emit a constructor that takes all the non-fake arguments.
if (HasFakeArg) {
emitCtor(true, false);
}
// Emit a constructor that takes all the non-fake, non-optional arguments.
if (HasOptArg) {
emitCtor(false, false);
}
OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
OS << " void printPretty(raw_ostream &OS,\n"
<< " const PrintingPolicy &Policy) const;\n";
OS << " const char *getSpelling() const;\n";
if (!ElideSpelling) {
assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
OS << " Spelling getSemanticSpelling() const {\n";
WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
OS);
OS << " }\n";
}
writeAttrAccessorDefinition(R, OS);
for (auto const &ai : Args) {
ai->writeAccessors(OS);
OS << "\n\n";
// Don't write conversion routines for fake arguments.
if (ai->isFake()) continue;
if (ai->isEnumArg())
static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
else if (ai->isVariadicEnumArg())
static_cast<const VariadicEnumArgument *>(ai.get())
->writeConversion(OS);
}
OS << R.getValueAsString("AdditionalMembers");
OS << "\n\n";
OS << " static bool classof(const Attr *A) { return A->getKind() == "
<< "attr::" << R.getName() << "; }\n";
OS << "};\n\n";
}
OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
}
// Emits the class method definitions for attributes.
void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute classes' member function definitions", OS);
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (auto *Attr : Attrs) {
Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
std::vector<std::unique_ptr<Argument>> Args;
for (const auto *Arg : ArgRecords)
Args.emplace_back(createArgument(*Arg, R.getName()));
for (auto const &ai : Args)
ai->writeAccessorDefinitions(OS);
OS << R.getName() << "Attr *" << R.getName()
<< "Attr::clone(ASTContext &C) const {\n";
OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
for (auto const &ai : Args) {
OS << ", ";
ai->writeCloneArgs(OS);
}
OS << ", getSpellingListIndex());\n";
OS << " A->Inherited = Inherited;\n";
OS << " A->IsPackExpansion = IsPackExpansion;\n";
OS << " A->Implicit = Implicit;\n";
OS << " return A;\n}\n\n";
writePrettyPrintFunction(R, Args, OS);
writeGetSpellingFunction(R, OS);
}
// Instead of relying on virtual dispatch we just create a huge dispatch
// switch. This is both smaller and faster than virtual functions.
auto EmitFunc = [&](const char *Method) {
OS << " switch (getKind()) {\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ":\n";
OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
<< ";\n";
}
OS << " case attr::NUM_ATTRS:\n";
OS << " break;\n";
OS << " }\n";
OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
OS << "}\n\n";
};
OS << "const char *Attr::getSpelling() const {\n";
EmitFunc("getSpelling()");
OS << "Attr *Attr::clone(ASTContext &C) const {\n";
EmitFunc("clone(C)");
OS << "void Attr::printPretty(raw_ostream &OS, "
"const PrintingPolicy &Policy) const {\n";
EmitFunc("printPretty(OS, Policy)");
}
} // end namespace clang
static void EmitAttrList(raw_ostream &OS, StringRef Class,
const std::vector<Record*> &AttrList) {
auto i = AttrList.cbegin(), e = AttrList.cend();
if (i != e) {
// Move the end iterator back to emit the last attribute.
for(--e; i != e; ++i) {
if (!(*i)->getValueAsBit("ASTNode"))
continue;
OS << Class << "(" << (*i)->getName() << ")\n";
}
OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
}
}
// Determines if an attribute has a Pragma spelling.
static bool AttrHasPragmaSpelling(const Record *R) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
return std::find_if(Spellings.begin(), Spellings.end(),
[](const FlattenedSpelling &S) {
return S.variety() == "Pragma";
}) != Spellings.end();
}
namespace clang {
// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
OS << "#ifndef LAST_ATTR\n";
OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef INHERITABLE_ATTR\n";
OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef LAST_INHERITABLE_ATTR\n";
OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
" INHERITABLE_PARAM_ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
OS << "#endif\n\n";
Record *InhClass = Records.getClass("InheritableAttr");
Record *InhParamClass = Records.getClass("InheritableParamAttr");
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
for (auto *Attr : Attrs) {
if (!Attr->getValueAsBit("ASTNode"))
continue;
if (AttrHasPragmaSpelling(Attr))
PragmaAttrs.push_back(Attr);
if (Attr->isSubClassOf(InhParamClass))
InhParamAttrs.push_back(Attr);
else if (Attr->isSubClassOf(InhClass))
InhAttrs.push_back(Attr);
else
NonInhAttrs.push_back(Attr);
}
EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
EmitAttrList(OS, "ATTR", NonInhAttrs);
OS << "#undef LAST_ATTR\n";
OS << "#undef INHERITABLE_ATTR\n";
OS << "#undef LAST_INHERITABLE_ATTR\n";
OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
OS << "#undef LAST_PRAGMA_ATTR\n";
OS << "#undef PRAGMA_SPELLING_ATTR\n";
OS << "#undef ATTR\n";
}
// Emits the code to read an attribute from a precompiled header.
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute deserialization code", OS);
Record *InhClass = Records.getClass("InheritableAttr");
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
ArgRecords;
std::vector<std::unique_ptr<Argument>> Args;
OS << " switch (Kind) {\n";
OS << " default:\n";
OS << " llvm_unreachable(\"Unknown attribute!\");\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
if (R.isSubClassOf(InhClass))
OS << " bool isInherited = Record[Idx++];\n";
OS << " bool isImplicit = Record[Idx++];\n";
OS << " unsigned Spelling = Record[Idx++];\n";
ArgRecords = R.getValueAsListOfDefs("Args");
Args.clear();
for (const auto *Arg : ArgRecords) {
Args.emplace_back(createArgument(*Arg, R.getName()));
Args.back()->writePCHReadDecls(OS);
}
OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
for (auto const &ri : Args) {
OS << ", ";
ri->writePCHReadArgs(OS);
}
OS << ", Spelling);\n";
if (R.isSubClassOf(InhClass))
OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
OS << " New->setImplicit(isImplicit);\n";
OS << " break;\n";
OS << " }\n";
}
OS << " }\n";
}
// Emits the code to write an attribute to a precompiled header.
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute serialization code", OS);
Record *InhClass = Records.getClass("InheritableAttr");
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
OS << " switch (A->getKind()) {\n";
OS << " default:\n";
OS << " llvm_unreachable(\"Unknown attribute kind!\");\n";
OS << " break;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
Args = R.getValueAsListOfDefs("Args");
if (R.isSubClassOf(InhClass) || !Args.empty())
OS << " const auto *SA = cast<" << R.getName()
<< "Attr>(A);\n";
if (R.isSubClassOf(InhClass))
OS << " Record.push_back(SA->isInherited());\n";
OS << " Record.push_back(A->isImplicit());\n";
OS << " Record.push_back(A->getSpellingListIndex());\n";
for (const auto *Arg : Args)
createArgument(*Arg, R.getName())->writePCHWrite(OS);
OS << " break;\n";
OS << " }\n";
}
OS << " }\n";
}
// Generate a conditional expression to check if the current target satisfies
// the conditions for a TargetSpecificAttr record, and append the code for
// those checks to the Test string. If the FnName string pointer is non-null,
// append a unique suffix to distinguish this set of target checks from other
// TargetSpecificAttr records.
static void GenerateTargetSpecificAttrChecks(const Record *R,
std::vector<std::string> &Arches,
std::string &Test,
std::string *FnName) {
// It is assumed that there will be an llvm::Triple object
// named "T" and a TargetInfo object named "Target" within
// scope that can be used to determine whether the attribute exists in
// a given target.
Test += "(";
for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
std::string Part = *I;
Test += "T.getArch() == llvm::Triple::" + Part;
if (I + 1 != E)
Test += " || ";
if (FnName)
*FnName += Part;
}
Test += ")";
// If the attribute is specific to particular OSes, check those.
if (!R->isValueUnset("OSes")) {
// We know that there was at least one arch test, so we need to and in the
// OS tests.
Test += " && (";
std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
std::string Part = *I;
Test += "T.getOS() == llvm::Triple::" + Part;
if (I + 1 != E)
Test += " || ";
if (FnName)
*FnName += Part;
}
Test += ")";
}
// If one or more CXX ABIs are specified, check those as well.
if (!R->isValueUnset("CXXABIs")) {
Test += " && (";
std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
std::string Part = *I;
Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part;
if (I + 1 != E)
Test += " || ";
if (FnName)
*FnName += Part;
}
Test += ")";
}
}
static void GenerateHasAttrSpellingStringSwitch(
const std::vector<Record *> &Attrs, raw_ostream &OS,
const std::string &Variety = "", const std::string &Scope = "") {
for (const auto *Attr : Attrs) {
// C++11-style attributes have specific version information associated with
// them. If the attribute has no scope, the version information must not
// have the default value (1), as that's incorrect. Instead, the unscoped
// attribute version information should be taken from the SD-6 standing
// document, which can be found at:
// https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
int Version = 1;
if (Variety == "CXX11") {
std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
for (const auto &Spelling : Spellings) {
if (Spelling->getValueAsString("Variety") == "CXX11") {
Version = static_cast<int>(Spelling->getValueAsInt("Version"));
if (Scope.empty() && Version == 1)
PrintError(Spelling->getLoc(), "C++ standard attributes must "
"have valid version information.");
break;
}
}
}
std::string Test;
if (Attr->isSubClassOf("TargetSpecificAttr")) {
const Record *R = Attr->getValueAsDef("Target");
std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
// If this is the C++11 variety, also add in the LangOpts test.
if (Variety == "CXX11")
Test += " && LangOpts.CPlusPlus11";
} else if (Variety == "CXX11")
// C++11 mode should be checked against LangOpts, which is presumed to be
// present in the caller.
Test = "LangOpts.CPlusPlus11";
std::string TestStr =
!Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
for (const auto &S : Spellings)
if (Variety.empty() || (Variety == S.variety() &&
(Scope.empty() || Scope == S.nameSpace())))
OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
}
OS << " .Default(0);\n";
}
// Emits the list of spellings for attributes.
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
// Separate all of the attributes out into four group: generic, C++11, GNU,
// and declspecs. Then generate a big switch statement for each of them.
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::vector<Record *> Declspec, GNU, Pragma;
std::map<std::string, std::vector<Record *>> CXX;
// Walk over the list of all attributes, and split them out based on the
// spelling variety.
for (auto *R : Attrs) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
for (const auto &SI : Spellings) {
std::string Variety = SI.variety();
if (Variety == "GNU")
GNU.push_back(R);
else if (Variety == "Declspec")
Declspec.push_back(R);
else if (Variety == "CXX11")
CXX[SI.nameSpace()].push_back(R);
else if (Variety == "Pragma")
Pragma.push_back(R);
}
}
OS << "const llvm::Triple &T = Target.getTriple();\n";
OS << "switch (Syntax) {\n";
OS << "case AttrSyntax::GNU:\n";
OS << " return llvm::StringSwitch<int>(Name)\n";
GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
OS << "case AttrSyntax::Declspec:\n";
OS << " return llvm::StringSwitch<int>(Name)\n";
GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
OS << "case AttrSyntax::Pragma:\n";
OS << " return llvm::StringSwitch<int>(Name)\n";
GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
OS << "case AttrSyntax::CXX: {\n";
// C++11-style attributes are further split out based on the Scope.
for (auto I = CXX.cbegin(), E = CXX.cend(); I != E; ++I) {
if (I != CXX.begin())
OS << " else ";
if (I->first.empty())
OS << "if (!Scope || Scope->getName() == \"\") {\n";
else
OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
OS << " return llvm::StringSwitch<int>(Name)\n";
GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
OS << "}";
}
OS << "\n}\n";
OS << "}\n";
}
void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Code to translate different attribute spellings "
"into internal identifiers", OS);
OS <<
" switch (AttrKind) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute kind!\");\n"
" break;\n";
ParsedAttrMap Attrs = getParsedAttrList(Records);
for (const auto &I : Attrs) {
const Record &R = *I.second;
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
OS << " case AT_" << I.first << ": {\n";
for (unsigned I = 0; I < Spellings.size(); ++ I) {
OS << " if (Name == \"" << Spellings[I].name() << "\" && "
<< "SyntaxUsed == "
<< StringSwitch<unsigned>(Spellings[I].variety())
.Case("GNU", 0)
.Case("CXX11", 1)
.Case("Declspec", 2)
.Case("Keyword", 3)
.Case("Pragma", 4)
.Default(0)
<< " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
<< " return " << I << ";\n";
}
OS << " break;\n";
OS << " }\n";
}
OS << " }\n";
OS << " return 0;\n";
}
// Emits code used by RecursiveASTVisitor to visit attributes
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
// Write method declarations for Traverse* methods.
// We emit this here because we only generate methods for attributes that
// are declared as ASTNodes.
OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " bool Traverse"
<< R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
OS << " bool Visit"
<< R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
<< " return true; \n"
<< " }\n";
}
OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
// Write individual Traverse* methods for each attribute class.
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << "template <typename Derived>\n"
<< "bool VISITORCLASS<Derived>::Traverse"
<< R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
<< " if (!getDerived().VisitAttr(A))\n"
<< " return false;\n"
<< " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
<< " return false;\n";
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
for (const auto *Arg : ArgRecords)
createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
OS << " return true;\n";
OS << "}\n\n";
}
// Write generic Traverse routine
OS << "template <typename Derived>\n"
<< "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
<< " if (!A)\n"
<< " return true;\n"
<< "\n"
<< " switch (A->getKind()) {\n"
<< " default:\n"
<< " return true;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ":\n"
<< " return getDerived().Traverse" << R.getName() << "Attr("
<< "cast<" << R.getName() << "Attr>(A));\n";
}
OS << " }\n"; // end case
OS << "}\n"; // end function
OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
}
// Emits code to instantiate dependent attributes on templates.
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Template instantiation code for attributes", OS);
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
OS << "namespace clang {\n"
<< "namespace sema {\n\n"
<< "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
<< "Sema &S,\n"
<< " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
<< " switch (At->getKind()) {\n"
<< " default:\n"
<< " break;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
bool ShouldClone = R.getValueAsBit("Clone");
if (!ShouldClone) {
OS << " return nullptr;\n";
OS << " }\n";
continue;
}
OS << " const auto *A = cast<"
<< R.getName() << "Attr>(At);\n";
bool TDependent = R.getValueAsBit("TemplateDependent");
if (!TDependent) {
OS << " return A->clone(C);\n";
OS << " }\n";
continue;
}
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
std::vector<std::unique_ptr<Argument>> Args;
Args.reserve(ArgRecords.size());
for (const auto *ArgRecord : ArgRecords)
Args.emplace_back(createArgument(*ArgRecord, R.getName()));
for (auto const &ai : Args)
ai->writeTemplateInstantiation(OS);
OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
for (auto const &ai : Args) {
OS << ", ";
ai->writeTemplateInstantiationArgs(OS);
}
OS << ", A->getSpellingListIndex());\n }\n";
}
OS << " } // end switch\n"
<< " llvm_unreachable(\"Unknown attribute!\");\n"
<< " return nullptr;\n"
<< "}\n\n"
<< "} // end namespace sema\n"
<< "} // end namespace clang\n";
}
// Emits the list of parsed attributes.
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
OS << "#ifndef PARSED_ATTR\n";
OS << "#define PARSED_ATTR(NAME) NAME\n";
OS << "#endif\n\n";
ParsedAttrMap Names = getParsedAttrList(Records);
for (const auto &I : Names) {
OS << "PARSED_ATTR(" << I.first << ")\n";
}
}
static bool isArgVariadic(const Record &R, StringRef AttrName) {
return createArgument(R, AttrName)->isVariadic();
}
static void emitArgInfo(const Record &R, std::stringstream &OS) {
// This function will count the number of arguments specified for the
// attribute and emit the number of required arguments followed by the
// number of optional arguments.
std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
unsigned ArgCount = 0, OptCount = 0;
bool HasVariadic = false;
for (const auto *Arg : Args) {
Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
HasVariadic = true;
}
// If there is a variadic argument, we will set the optional argument count
// to its largest value. Since it's currently a 4-bit number, we set it to 15.
OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
}
static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
OS << "const Decl *) {\n";
OS << " return true;\n";
OS << "}\n\n";
}
static std::string CalculateDiagnostic(const Record &S) {
// If the SubjectList object has a custom diagnostic associated with it,
// return that directly.
std::string CustomDiag = S.getValueAsString("CustomDiag");
if (!CustomDiag.empty())
return CustomDiag;
// Given the list of subjects, determine what diagnostic best fits.
enum {
Func = 1U << 0,
Var = 1U << 1,
ObjCMethod = 1U << 2,
Param = 1U << 3,
Class = 1U << 4,
GenericRecord = 1U << 5,
Type = 1U << 6,
ObjCIVar = 1U << 7,
ObjCProp = 1U << 8,
ObjCInterface = 1U << 9,
Block = 1U << 10,
Namespace = 1U << 11,
Field = 1U << 12,
CXXMethod = 1U << 13,
ObjCProtocol = 1U << 14,
Enum = 1U << 15
};
uint32_t SubMask = 0;
std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
for (const auto *Subject : Subjects) {
const Record &R = *Subject;
std::string Name;
if (R.isSubClassOf("SubsetSubject")) {
PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
// As a fallback, look through the SubsetSubject to see what its base
// type is, and use that. This needs to be updated if SubsetSubjects
// are allowed within other SubsetSubjects.
Name = R.getValueAsDef("Base")->getName();
} else
Name = R.getName();
uint32_t V = StringSwitch<uint32_t>(Name)
.Case("Function", Func)
.Case("Var", Var)
.Case("ObjCMethod", ObjCMethod)
.Case("ParmVar", Param)
.Case("TypedefName", Type)
.Case("ObjCIvar", ObjCIVar)
.Case("ObjCProperty", ObjCProp)
.Case("Record", GenericRecord)
.Case("ObjCInterface", ObjCInterface)
.Case("ObjCProtocol", ObjCProtocol)
.Case("Block", Block)
.Case("CXXRecord", Class)
.Case("Namespace", Namespace)
.Case("Field", Field)
.Case("CXXMethod", CXXMethod)
.Case("Enum", Enum)
.Default(0);
if (!V) {
// Something wasn't in our mapping, so be helpful and let the developer
// know about it.
PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
return "";
}
SubMask |= V;
}
switch (SubMask) {
// For the simple cases where there's only a single entry in the mask, we
// don't have to resort to bit fiddling.
case Func: return "ExpectedFunction";
case Var: return "ExpectedVariable";
case Param: return "ExpectedParameter";
case Class: return "ExpectedClass";
case Enum: return "ExpectedEnum";
case CXXMethod:
// FIXME: Currently, this maps to ExpectedMethod based on existing code,
// but should map to something a bit more accurate at some point.
case ObjCMethod: return "ExpectedMethod";
case Type: return "ExpectedType";
case ObjCInterface: return "ExpectedObjectiveCInterface";
case ObjCProtocol: return "ExpectedObjectiveCProtocol";
// "GenericRecord" means struct, union or class; check the language options
// and if not compiling for C++, strip off the class part. Note that this
// relies on the fact that the context for this declares "Sema &S".
case GenericRecord:
return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
"ExpectedStructOrUnion)";
case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
case Func | Param:
case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
case Func | Var: return "ExpectedVariableOrFunction";
// If not compiling for C++, the class portion does not apply.
case Func | Var | Class:
return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
"ExpectedVariableOrFunction)";
case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
case ObjCProtocol | ObjCInterface:
return "ExpectedObjectiveCInterfaceOrProtocol";
case Field | Var: return "ExpectedFieldOrGlobalVar";
}
PrintFatalError(S.getLoc(),
"Could not deduce diagnostic argument for Attr subjects");
return "";
}
static std::string GetSubjectWithSuffix(const Record *R) {
std::string B = R->getName();
if (B == "DeclBase")
return "Decl";
return B + "Decl";
}
static std::string GenerateCustomAppertainsTo(const Record &Subject,
raw_ostream &OS) {
std::string FnName = "is" + Subject.getName();
// If this code has already been generated, simply return the previous
// instance of it.
static std::set<std::string> CustomSubjectSet;
auto I = CustomSubjectSet.find(FnName);
if (I != CustomSubjectSet.end())
return *I;
Record *Base = Subject.getValueAsDef("Base");
// Not currently support custom subjects within custom subjects.
if (Base->isSubClassOf("SubsetSubject")) {
PrintFatalError(Subject.getLoc(),
"SubsetSubjects within SubsetSubjects is not supported");
return "";
}
OS << "static bool " << FnName << "(const Decl *D) {\n";
OS << " if (const auto *S = dyn_cast<";
OS << GetSubjectWithSuffix(Base);
OS << ">(D))\n";
OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
OS << " return false;\n";
OS << "}\n\n";
CustomSubjectSet.insert(FnName);
return FnName;
}
static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
// If the attribute does not contain a Subjects definition, then use the
// default appertainsTo logic.
if (Attr.isValueUnset("Subjects"))
return "defaultAppertainsTo";
const Record *SubjectObj = Attr.getValueAsDef("Subjects");
std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
// If the list of subjects is empty, it is assumed that the attribute
// appertains to everything.
if (Subjects.empty())
return "defaultAppertainsTo";
bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
// Otherwise, generate an appertainsTo check specific to this attribute which
// checks all of the given subjects against the Decl passed in. Return the
// name of that check to the caller.
std::string FnName = "check" + Attr.getName() + "AppertainsTo";
std::stringstream SS;
SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
SS << "const Decl *D) {\n";
SS << " if (";
for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
// If the subject has custom code associated with it, generate a function
// for it. The function cannot be inlined into this check (yet) because it
// requires the subject to be of a specific type, and were that information
// inlined here, it would not support an attribute with multiple custom
// subjects.
if ((*I)->isSubClassOf("SubsetSubject")) {
SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
} else {
SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
}
if (I + 1 != E)
SS << " && ";
}
SS << ") {\n";
SS << " S.Diag(Attr.getLoc(), diag::";
SS << (Warn ? "warn_attribute_wrong_decl_type" :
"err_attribute_wrong_decl_type");
SS << ")\n";
SS << " << Attr.getName() << ";
SS << CalculateDiagnostic(*SubjectObj) << ";\n";
SS << " return false;\n";
SS << " }\n";
SS << " return true;\n";
SS << "}\n\n";
OS << SS.str();
return FnName;
}
static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
OS << "const AttributeList &) {\n";
OS << " return true;\n";
OS << "}\n\n";
}
static std::string GenerateLangOptRequirements(const Record &R,
raw_ostream &OS) {
// If the attribute has an empty or unset list of language requirements,
// return the default handler.
std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
if (LangOpts.empty())
return "defaultDiagnoseLangOpts";
// Generate the test condition, as well as a unique function name for the
// diagnostic test. The list of options should usually be short (one or two
// options), and the uniqueness isn't strictly necessary (it is just for
// codegen efficiency).
std::string FnName = "check", Test;
for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
std::string Part = (*I)->getValueAsString("Name");
if ((*I)->getValueAsBit("Negated"))
Test += "!";
Test += "S.LangOpts." + Part;
if (I + 1 != E)
Test += " || ";
FnName += Part;
}
FnName += "LangOpts";
// If this code has already been generated, simply return the previous
// instance of it.
static std::set<std::string> CustomLangOptsSet;
auto I = CustomLangOptsSet.find(FnName);
if (I != CustomLangOptsSet.end())
return *I;
OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
OS << " if (" << Test << ")\n";
OS << " return true;\n\n";
OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
OS << "<< Attr.getName();\n";
OS << " return false;\n";
OS << "}\n\n";
CustomLangOptsSet.insert(FnName);
return FnName;
}
static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
OS << " return true;\n";
OS << "}\n\n";
}
static std::string GenerateTargetRequirements(const Record &Attr,
const ParsedAttrMap &Dupes,
raw_ostream &OS) {
// If the attribute is not a target specific attribute, return the default
// target handler.
if (!Attr.isSubClassOf("TargetSpecificAttr"))
return "defaultTargetRequirements";
// Get the list of architectures to be tested for.
const Record *R = Attr.getValueAsDef("Target");
std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
if (Arches.empty()) {
PrintError(Attr.getLoc(), "Empty list of target architectures for a "
"target-specific attr");
return "defaultTargetRequirements";
}
// If there are other attributes which share the same parsed attribute kind,
// such as target-specific attributes with a shared spelling, collapse the
// duplicate architectures. This is required because a shared target-specific
// attribute has only one AttributeList::Kind enumeration value, but it
// applies to multiple target architectures. In order for the attribute to be
// considered valid, all of its architectures need to be included.
if (!Attr.isValueUnset("ParseKind")) {
std::string APK = Attr.getValueAsString("ParseKind");
for (const auto &I : Dupes) {
if (I.first == APK) {
std::vector<std::string> DA = I.second->getValueAsDef("Target")
->getValueAsListOfStrings("Arches");
std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
}
}
}
std::string FnName = "isTarget";
std::string Test;
GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
// If this code has already been generated, simply return the previous
// instance of it.
static std::set<std::string> CustomTargetSet;
auto I = CustomTargetSet.find(FnName);
if (I != CustomTargetSet.end())
return *I;
OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
OS << " const llvm::Triple &T = Target.getTriple();\n";
OS << " return " << Test << ";\n";
OS << "}\n\n";
CustomTargetSet.insert(FnName);
return FnName;
}
static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
<< "const AttributeList &Attr) {\n";
OS << " return UINT_MAX;\n";
OS << "}\n\n";
}
static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
raw_ostream &OS) {
// If the attribute does not have a semantic form, we can bail out early.
if (!Attr.getValueAsBit("ASTNode"))
return "defaultSpellingIndexToSemanticSpelling";
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
// If there are zero or one spellings, or all of the spellings share the same
// name, we can also bail out early.
if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
return "defaultSpellingIndexToSemanticSpelling";
// Generate the enumeration we will use for the mapping.
SemanticSpellingMap SemanticToSyntacticMap;
std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
std::string Name = Attr.getName() + "AttrSpellingMap";
OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
OS << Enum;
OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
OS << "}\n\n";
return Name;
}
static bool IsKnownToGCC(const Record &Attr) {
// Look at the spellings for this subject; if there are any spellings which
// claim to be known to GCC, the attribute is known to GCC.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
for (const auto &I : Spellings) {
if (I.knownToGCC())
return true;
}
return false;
}
/// Emits the parsed attribute helpers
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Parsed attribute helpers", OS);
// Get the list of parsed attributes, and accept the optional list of
// duplicates due to the ParseKind.
ParsedAttrMap Dupes;
ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
// Generate the default appertainsTo, target and language option diagnostic,
// and spelling list index mapping methods.
GenerateDefaultAppertainsTo(OS);
GenerateDefaultLangOptRequirements(OS);
GenerateDefaultTargetRequirements(OS);
GenerateDefaultSpellingIndexToSemanticSpelling(OS);
// Generate the appertainsTo diagnostic methods and write their names into
// another mapping. At the same time, generate the AttrInfoMap object
// contents. Due to the reliance on generated code, use separate streams so
// that code will not be interleaved.
std::stringstream SS;
for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
// TODO: If the attribute's kind appears in the list of duplicates, that is
// because it is a target-specific attribute that appears multiple times.
// It would be beneficial to test whether the duplicates are "similar
// enough" to each other to not cause problems. For instance, check that
// the spellings are identical, and custom parsing rules match, etc.
// We need to generate struct instances based off ParsedAttrInfo from
// AttributeList.cpp.
SS << " { ";
emitArgInfo(*I->second, SS);
SS << ", " << I->second->getValueAsBit("HasCustomParsing");
SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
SS << ", " << I->second->isSubClassOf("TypeAttr");
SS << ", " << IsKnownToGCC(*I->second);
SS << ", " << GenerateAppertainsTo(*I->second, OS);
SS << ", " << GenerateLangOptRequirements(*I->second, OS);
SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
SS << " }";
if (I + 1 != E)
SS << ",";
SS << " // AT_" << I->first << "\n";
}
OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
OS << SS.str();
OS << "};\n\n";
}
// Emits the kind list of parsed attributes
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute name matcher", OS);
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
std::set<std::string> Seen;
for (const auto *A : Attrs) {
const Record &Attr = *A;
bool SemaHandler = Attr.getValueAsBit("SemaHandler");
bool Ignored = Attr.getValueAsBit("Ignored");
if (SemaHandler || Ignored) {
// Attribute spellings can be shared between target-specific attributes,
// and can be shared between syntaxes for the same attribute. For
// instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
// specific attribute, or MSP430-specific attribute. Additionally, an
// attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
// for the same semantic attribute. Ultimately, we need to map each of
// these to a single AttributeList::Kind value, but the StringMatcher
// class cannot handle duplicate match strings. So we generate a list of
// string to match based on the syntax, and emit multiple string matchers
// depending on the syntax used.
std::string AttrName;
if (Attr.isSubClassOf("TargetSpecificAttr") &&
!Attr.isValueUnset("ParseKind")) {
AttrName = Attr.getValueAsString("ParseKind");
if (Seen.find(AttrName) != Seen.end())
continue;
Seen.insert(AttrName);
} else
AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
for (const auto &S : Spellings) {
std::string RawSpelling = S.name();
std::vector<StringMatcher::StringPair> *Matches = nullptr;
std::string Spelling, Variety = S.variety();
if (Variety == "CXX11") {
Matches = &CXX11;
Spelling += S.nameSpace();
Spelling += "::";
} else if (Variety == "GNU")
Matches = &GNU;
else if (Variety == "Declspec")
Matches = &Declspec;
else if (Variety == "Keyword")
Matches = &Keywords;
else if (Variety == "Pragma")
Matches = &Pragma;
assert(Matches && "Unsupported spelling variety found");
Spelling += NormalizeAttrSpelling(RawSpelling);
if (SemaHandler)
Matches->push_back(StringMatcher::StringPair(Spelling,
"return AttributeList::AT_" + AttrName + ";"));
else
Matches->push_back(StringMatcher::StringPair(Spelling,
"return AttributeList::IgnoredAttribute;"));
}
}
}
OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
OS << "AttributeList::Syntax Syntax) {\n";
OS << " if (AttributeList::AS_GNU == Syntax) {\n";
StringMatcher("Name", GNU, OS).Emit();
OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
StringMatcher("Name", Declspec, OS).Emit();
OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
StringMatcher("Name", CXX11, OS).Emit();
OS << " } else if (AttributeList::AS_Keyword == Syntax || ";
OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
StringMatcher("Name", Keywords, OS).Emit();
OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
StringMatcher("Name", Pragma, OS).Emit();
OS << " }\n";
OS << " return AttributeList::UnknownAttribute;\n"
<< "}\n";
}
// Emits the code to dump an attribute.
void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute dumper", OS);
OS <<
" switch (A->getKind()) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute kind!\");\n"
" break;\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
// If the attribute has a semantically-meaningful name (which is determined
// by whether there is a Spelling enumeration for it), then write out the
// spelling used for the attribute.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
OS << " OS << \" \" << A->getSpelling();\n";
Args = R.getValueAsListOfDefs("Args");
if (!Args.empty()) {
OS << " const auto *SA = cast<" << R.getName()
<< "Attr>(A);\n";
for (const auto *Arg : Args)
createArgument(*Arg, R.getName())->writeDump(OS);
for (const auto *AI : Args)
createArgument(*AI, R.getName())->writeDumpChildren(OS);
}
OS <<
" break;\n"
" }\n";
}
OS << " }\n";
}
void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
raw_ostream &OS) {
emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
emitClangAttrArgContextList(Records, OS);
emitClangAttrIdentifierArgList(Records, OS);
emitClangAttrTypeArgList(Records, OS);
emitClangAttrLateParsedList(Records, OS);
}
class DocumentationData {
public:
const Record *Documentation;
const Record *Attribute;
DocumentationData(const Record &Documentation, const Record &Attribute)
: Documentation(&Documentation), Attribute(&Attribute) {}
};
static void WriteCategoryHeader(const Record *DocCategory,
raw_ostream &OS) {
const std::string &Name = DocCategory->getValueAsString("Name");
OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
// If there is content, print that as well.
std::string ContentStr = DocCategory->getValueAsString("Content");
// Trim leading and trailing newlines and spaces.
OS << StringRef(ContentStr).trim();
OS << "\n\n";
}
enum SpellingKind {
GNU = 1 << 0,
CXX11 = 1 << 1,
Declspec = 1 << 2,
Keyword = 1 << 3,
Pragma = 1 << 4
};
static void WriteDocumentation(const DocumentationData &Doc,
raw_ostream &OS) {
// FIXME: there is no way to have a per-spelling category for the attribute
// documentation. This may not be a limiting factor since the spellings
// should generally be consistently applied across the category.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
// Determine the heading to be used for this attribute.
std::string Heading = Doc.Documentation->getValueAsString("Heading");
bool CustomHeading = !Heading.empty();
if (Heading.empty()) {
// If there's only one spelling, we can simply use that.
if (Spellings.size() == 1)
Heading = Spellings.begin()->name();
else {
std::set<std::string> Uniques;
for (auto I = Spellings.begin(), E = Spellings.end();
I != E && Uniques.size() <= 1; ++I) {
std::string Spelling = NormalizeNameForSpellingComparison(I->name());
Uniques.insert(Spelling);
}
// If the semantic map has only one spelling, that is sufficient for our
// needs.
if (Uniques.size() == 1)
Heading = *Uniques.begin();
}
}
// If the heading is still empty, it is an error.
if (Heading.empty())
PrintFatalError(Doc.Attribute->getLoc(),
"This attribute requires a heading to be specified");
// Gather a list of unique spellings; this is not the same as the semantic
// spelling for the attribute. Variations in underscores and other non-
// semantic characters are still acceptable.
std::vector<std::string> Names;
unsigned SupportedSpellings = 0;
for (const auto &I : Spellings) {
SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
.Case("GNU", GNU)
.Case("CXX11", CXX11)
.Case("Declspec", Declspec)
.Case("Keyword", Keyword)
.Case("Pragma", Pragma);
// Mask in the supported spelling.
SupportedSpellings |= Kind;
std::string Name;
if (Kind == CXX11 && !I.nameSpace().empty())
Name = I.nameSpace() + "::";
Name += I.name();
// If this name is the same as the heading, do not add it.
if (Name != Heading)
Names.push_back(Name);
}
// Print out the heading for the attribute. If there are alternate spellings,
// then display those after the heading.
if (!CustomHeading && !Names.empty()) {
Heading += " (";
for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
if (I != Names.begin())
Heading += ", ";
Heading += *I;
}
Heading += ")";
}
OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
if (!SupportedSpellings)
PrintFatalError(Doc.Attribute->getLoc(),
"Attribute has no supported spellings; cannot be "
"documented");
// List what spelling syntaxes the attribute supports.
OS << ".. csv-table:: Supported Syntaxes\n";
OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
OS << " \"Pragma\"\n\n";
OS << " \"";
if (SupportedSpellings & GNU) OS << "X";
OS << "\",\"";
if (SupportedSpellings & CXX11) OS << "X";
OS << "\",\"";
if (SupportedSpellings & Declspec) OS << "X";
OS << "\",\"";
if (SupportedSpellings & Keyword) OS << "X";
OS << "\", \"";
if (SupportedSpellings & Pragma) OS << "X";
OS << "\"\n\n";
// If the attribute is deprecated, print a message about it, and possibly
// provide a replacement attribute.
if (!Doc.Documentation->isValueUnset("Deprecated")) {
OS << "This attribute has been deprecated, and may be removed in a future "
<< "version of Clang.";
const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
std::string Replacement = Deprecated.getValueAsString("Replacement");
if (!Replacement.empty())
OS << " This attribute has been superseded by ``"
<< Replacement << "``.";
OS << "\n\n";
}
std::string ContentStr = Doc.Documentation->getValueAsString("Content");
// Trim leading and trailing newlines and spaces.
OS << StringRef(ContentStr).trim();
OS << "\n\n\n";
}
void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
// Get the documentation introduction paragraph.
const Record *Documentation = Records.getDef("GlobalDocumentation");
if (!Documentation) {
PrintFatalError("The Documentation top-level definition is missing, "
"no documentation will be generated.");
return;
}
OS << Documentation->getValueAsString("Intro") << "\n";
// Gather the Documentation lists from each of the attributes, based on the
// category provided.
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
for (const auto *A : Attrs) {
const Record &Attr = *A;
std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
for (const auto *D : Docs) {
const Record &Doc = *D;
const Record *Category = Doc.getValueAsDef("Category");
// If the category is "undocumented", then there cannot be any other
// documentation categories (otherwise, the attribute would become
// documented).
std::string Cat = Category->getValueAsString("Name");
bool Undocumented = Cat == "Undocumented";
if (Undocumented && Docs.size() > 1)
PrintFatalError(Doc.getLoc(),
"Attribute is \"Undocumented\", but has multiple "
"documentation categories");
if (!Undocumented)
SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
}
}
// Having split the attributes out based on what documentation goes where,
// we can begin to generate sections of documentation.
for (const auto &I : SplitDocs) {
WriteCategoryHeader(I.first, OS);
// Walk over each of the attributes in the category and write out their
// documentation.
for (const auto &Doc : I.second)
WriteDocumentation(Doc, OS);
}
}
} // end namespace clang
|
#include <float.h>
#include <sys/stat.h>
#include "perf.h"
#include "SeisppError.h"
#include "TimeSeries.h"
#include "ensemble.h"
#include "GenericFileHandle.h"
using namespace std;
using namespace SEISPP;
namespace SEISPP
{
/* This is a small (private) helper function common to both of
the following constructors. It initializes the data file
handles stored internally in read or write mode.
The one argument is obvious */
void GenericFileHandle::initialize_iohandle(string filename, bool read_only)
{
const string base_error("GenericFileHandle::iohandle procedure called by constructor: ");
// There are contexts we need to make sure this is set
readmode=read_only;
if(read_only)
{
fp=fopen(filename.c_str(),"r");
if(fp==NULL) throw SeisppError(base_error
+ "Cannot open file "
+ filename
+ " for reading");
fsize=this->filesize();
current_file_position=0;
}
else
{
outstrm.sync_with_stdio();
outstrm.open(filename.c_str(),ios::out
| ios::app | ios::binary);
if(outstrm.fail()) throw SeisppError(base_error
+ "Cannot open file "
+ filename
+ " for output in append mode");
current_file_position=outstrm.tellp();
fp=NULL;
}
}
GenericFileHandle::GenericFileHandle(string filename,
string tracetype, AttributeCrossReference& namemap,
list<string> okeys, list<string> ensmdlist, list<string> tmdlist,
bool read_only, string nskey, string dt_key, double dtscl,
bool using_sample_interval,bool nowrit)
: xref(namemap), dbuffer(tracetype), fname(filename)
{
const string base_error("GenericFileHandle constructor: ");
handle_not_ready=true;
readmode=read_only;
nsamp_keyword=nskey;
dt_keyword=dt_key;
dtscale=dtscl;
key_is_dt=using_sample_interval;
no_write_dead=nowrit;
/* These probably should be variable, but frozen for now */
retry_limit=50;
sleep_interval=1;
/* We must require the orderkeys to be loaded for each trace
as changes in keys is the signal to mark a new ensemble.
Note that is not as general as it could be (e.g. it doesn't
allow for interval tests) but is sufficient for now. This
is research code after all. */
list<string>::iterator okptr;
for(okptr=okeys.begin();okptr!=okeys.end();++okptr)
{
try{
string exttest=xref.external(*okptr);
}catch(SeisppError& serr) {
throw SeisppError(base_error
+ "ensemble metdata key="
+ *okptr
+ " is not defind in cross reference map\nAdd to definitions");
}
}
orderkeys=okeys;
ensemble_mdlist=ensmdlist;
trace_mdlist=tmdlist;
// Cache external names for these keywords for efficiency
// and to avoid later error traps
try {
dtkey_ext=xref.external(dt_keyword);
} catch (...)
{
throw SeisppError(base_error
+ "Required metadata keyword ="
+ dt_keyword
+ " does not have a cross reference for file format "
+tracetype);
}
try {
nskey_ext=xref.external(nsamp_keyword);
} catch (...)
{
throw SeisppError(base_error
+ "Required metadata keyword ="
+ nsamp_keyword
+ " does not have a cross reference for file format "
+ tracetype);
}
try {
initialize_iohandle(filename,readmode);
}catch(...){throw;};
handle_not_ready=false;
}
void GenericFileHandle::set_required(AttributeCrossReference& namemap,
list<string> okeys,
list<string> ensmdlist,
list<string> tmdlist,
string ns_key,
string dt_key,
double dtscl,
bool using_sample_interval,
bool nowritedead)
{
const string base_error("GenericFileHandle::set_required: ");
xref=namemap;
orderkeys=okeys;
ensemble_mdlist=ensmdlist;
trace_mdlist=tmdlist;
nsamp_keyword=ns_key;
dt_keyword=dt_key;
dtscale=dtscl;
key_is_dt=using_sample_interval;
no_write_dead=nowritedead;
handle_not_ready=false;
// frozen for now
retry_limit=50;
// Cache external names for these keywords for efficiency
// and to avoid later error traps
try {
dtkey_ext=xref.external(dt_keyword);
} catch (...)
{
throw SeisppError(base_error
+ "Required metadata keyword ="
+ dt_keyword
+ " does not have a cross reference for this format");
}
try {
nskey_ext=xref.external(nsamp_keyword);
} catch (...)
{
throw SeisppError(base_error
+ "Required metadata keyword ="
+ nsamp_keyword
+ " does not have a cross reference for this format");
}
}
GenericFileHandle::GenericFileHandle(string filename, string tracetype,
bool read_only) : dbuffer(tracetype), fname(filename)
{
handle_not_ready=true;
try {
initialize_iohandle(filename,read_only);
}catch(...){throw;};
}
GenericFileHandle::GenericFileHandle(const GenericFileHandle& parent)
{
throw SeisppError(string("GenericFileHandle: coding error\n")
+ "Copying a GenericFileHandle is not allowed in this implementation. Try using a shared_pointer\n");
}
GenericFileHandle::~GenericFileHandle()
{
if(fp!=NULL)
fclose(fp);
// Needs similar test to check outstrm
if(outstrm.is_open())
{
this->unlock();
outstrm.close();
}
}
const string notreadyerror("GenericFileHandle: Attempt to use incomplete file handle - marked not ready\nCoding error");
long GenericFileHandle::filesize()
{
long result;
if(readmode)
{
if(fp==NULL)
return 0L;
else
{
long current=ftell(fp);
fseek(fp,0L,SEEK_END);
result=ftell(fp);
fseek(fp,current,SEEK_SET);
}
}
else
{
try {
long current=outstrm.tellp();
outstrm.seekp(0L,ios_base::end);
result=outstrm.tellp();
outstrm.seekp(current,ios_base::beg);
} catch(exception& excpt)
{
throw SeisppError(string("GenericFileHandle::filesize: ")
+ string("IO error trying to determine file size.\nSystem Message: ")
+excpt.what());
}
}
fsize=result;
return(result);
}
bool GenericFileHandle::eof()
{
if(readmode)
{
long current=ftell(fp);
if(current==fsize)
return true;
else
return false;
}
else
/* Always respond true for writing */
return true;
}
/* This is common code used in get methods below for loading
metadata. Used for both global (ensemble) Metadata and individual
Metadata. All involve loading from headers in FixedFormatTrace
objects. All should dynamic_cast to a Metadata reference to use
this private method. Note carefully that mdlist is a name of
internal names to be extracted. */
void GenericFileHandle::LoadMetadata(FixedFormatTrace& dext,
Metadata& d,list<string> mdlist)
{
if(handle_not_ready)
throw SeisppError(notreadyerror+" when calling LoadMetadata method");
try {
string extkey;
list<string>::iterator mdlptr;
MDtype keydatatype;
for(mdlptr=trace_mdlist.begin();mdlptr!=trace_mdlist.end();
++mdlptr)
{
extkey=xref.external(*mdlptr);
keydatatype=xref.type(*mdlptr);
int ival;
double dval;
string sval;
bool bval;
switch(keydatatype)
{
case MDint:
ival=dext.get<int>(extkey);
d.put(*mdlptr,ival);
break;
case MDreal:
dval=dext.get<double>(extkey);
d.put(*mdlptr,dval);
break;
case MDboolean:
bval=dext.get<bool>(extkey);
d.put(*mdlptr,bval);
break;
case MDstring:
sval=dext.get_string(extkey);
d.put(*mdlptr,sval);
break;
case MDinvalid:
default:
//Silently do nothing if invalid or something else
continue;
}
}
}catch(...){throw;};
}
/* This private method standardizes loading of core attributes of
the BasicTimeSeries object. Useful becasue both TimeSeries
and ThreeComponentSeismogram objects are children of this
base. In a different design this could have been made a
constructor, but since this handle is essentially an add on
this is done this way - common code as a private method.
d is the current FixedFormatTrace buffer. The base variable
should always be received as a dynamic_cat from the higher
order object (i.e. TimeSeries or ThreeComponentSeismogram). */
void GenericFileHandle::LoadCommonAttributes(FixedFormatTrace& d,
BasicTimeSeries& base)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+" when calling LoadCommonAttributes method");
try {
int nsext=d.get<int>(nskey_ext);
base.ns=nsext;
double dtext=d.get<double>(dtkey_ext);
if(!key_is_dt) dtext=1.0/dtext;
/* Required because some formats like segy use time in microsecond*/
dtext *= dtscale;
base.dt=dtext;
/* Two required metadata entries. For no abort if these aren't
defined. A bit dogmatic, but for now assume we will always
be writing these as working files from some other source
like a datascope database.*/
string extkey;
base.t0=d.tstart();
base.tref=d.tref;
/* Always mark data live. If format allows this is then
overridden. */
base.live=true;
}catch(...){throw;};
}
TimeSeries GenericFileHandle::GetNextSeismogram()
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling GetNextSeismogram method");
const string base_error("GenericFileHandle::GetNextSeismogram: ");
if(!readmode) throw SeisppError(base_error
+ "Coding error. Trying to read when handle is in write mode");
if(dbuffer.data_are_3c) throw SeisppError(base_error
+ "Error trying to read 3C\nData format="
+ dbuffer.format_description()
+ " does not support three component data");
if(this->eof()) throw SeisppError(base_error
+ "Attempt to read past end of file. Check caller program logic.");
try {
FixedFormatTrace NextSeis(dbuffer,fp,nskey_ext,dtkey_ext,
key_is_dt);
TimeSeries result(NextSeis.ns);
LoadCommonAttributes(NextSeis,
dynamic_cast<BasicTimeSeries&> (result));
LoadMetadata(NextSeis,
dynamic_cast<Metadata&> (result), trace_mdlist);
result.s=NextSeis.data();
current_file_position=ftell(fp);
return(result);
}catch(...){throw;};
}
/* Private method used by the GetNextEnsemble method below */
bool GenericFileHandle::keys_match(Metadata& d1, Metadata& d2)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling keys_match method");
list<string>::iterator nmptr;
for(nmptr=orderkeys.begin();nmptr!=orderkeys.end();++nmptr)
{
/* Constructor guaranteeds that orderkeys are in the set of
metadata loaded with each time series so we do not need to
trap that possible error condition */
MDtype thiskeytype=xref.type(*nmptr);
int ival;
double dval,dtest;
bool bval;
string sval;
switch(thiskeytype)
{
case MDint:
ival=d1.get_int(*nmptr);
if(ival!=(d2.get_int(*nmptr))) return(false);
break;
case MDreal:
dval=d1.get_double(*nmptr);
dtest=(dval-d2.get_double(*nmptr))/dval;
dtest=fabs(dtest);
if(dtest>DBL_EPSILON) return(false);
break;
case MDboolean:
// This is kind of irrational as a key, but will code it anyway
bval=d1.get_bool(*nmptr);
if(bval || d2.get_bool(*nmptr)) return(false);
break;
case MDstring:
sval=d1.get_string(*nmptr);
if(sval!=(d2.get_string(*nmptr))) return(false);
break;
case MDinvalid:
default:
throw SeisppError(
string("GenericFileHandle::keys_match private method:")
+ "Ensemble key = "
+ *nmptr
+ "used to define ensemble boundary has invalid type");
}
}
return(true);
}
auto_ptr<TimeSeriesEnsemble> GenericFileHandle::GetNextEnsemble()
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling GetNextEnsemble method");
const string base_error("GenericFileHandle::GetNextEnsemble: ");
if(!readmode) throw SeisppError(base_error
+ "Coding error. Trying to read when handle is in write mode");
if(this->eof()) throw SeisppError(base_error
+ "Attempt to read past end of file. Fix calling program logic.");
if(dbuffer.data_are_3c) throw SeisppError(base_error
+ "Error trying to read 3C\nData format="
+ dbuffer.format_description()
+ " does not support three component data");
/* When reading an ensemble we assume all the traces have the same
value for ensemble attributes. Thus we assume we can read them
from the first trace in each ensemble */
try {
// Save this to insulate against changes in behaviour of
// FixedFormatTrace object
long last_offset=current_file_position;
auto_ptr<TimeSeriesEnsemble> result(new TimeSeriesEnsemble());
FixedFormatTrace NextSeis(dbuffer,fp,nskey_ext,dtkey_ext,
key_is_dt);
LoadMetadata(NextSeis,dynamic_cast<Metadata&>(*result),
ensemble_mdlist);
/* Minor inefficiency but we back up to read the last trace
again. This is necessary so we can just call the
GetNextSeismogram method to load the whole thing. */
fseek(fp,last_offset,SEEK_SET);
/* Now we load data until the key attributes change or we
hit eof */
TimeSeries d,dlast;
int tracecount(0);
do {
last_offset=current_file_position;
d=this->GetNextSeismogram();
if(tracecount==0) dlast=d;
if(this->keys_match(d,dlast))
{
result->member.push_back(d);
current_file_position=ftell(fp);
++tracecount;
}
else
{
/*If keys do not match we already read the next seismogram
so we have to then back the file pointer so
the next read will be from the right position.*/
fseek(fp,last_offset,SEEK_SET);
current_file_position=last_offset;
// this is the loop break except at eof
break;
}
dlast=d;
}while(!this->eof());
return(result);
}catch(...){throw;};
}
/* This code was modeled closely after GetNextSeismogram (scalar data) */
ThreeComponentSeismogram GenericFileHandle::GetNext3CSeismogram()
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling GetNext3CSeismogram method");
const string base_error("GenericFileHandle::GetNext3CSeismogram: ");
if(!readmode) throw SeisppError(base_error
+ "Coding error. Trying to read when handle is in write mode");
if(!dbuffer.data_are_3c) throw SeisppError(base_error
+ "Error trying to read 3C\nData format="
+ dbuffer.format_description()
+ " does not support three component data");
if(this->eof()) throw SeisppError(base_error
+ "Attempt to read past end of file. Check caller program logic.");
try {
FixedFormatTrace NextSeis(dbuffer,fp,nskey_ext,dtkey_ext,
key_is_dt);
ThreeComponentSeismogram result(NextSeis.ns);
LoadCommonAttributes(NextSeis,
dynamic_cast<BasicTimeSeries&> (result));
LoadMetadata(NextSeis,
dynamic_cast<Metadata&> (result), trace_mdlist);
/* For 3c data we assume the data are stored in a single
large vector. The data method of FixedFormatTrace returns
this as a stl vector container */
vector<double> rawsamples=NextSeis.data();
/* Constructor above is assumed to have allocated data matrix u*/
int nsamp=result.ns;
if(NextSeis.channel_order)
dcopy(3*nsamp,&(rawsamples[0]),1,result.u.get_address(0,0),1);
else
for(int k=0;k<3;++k) dcopy(nsamp,&(rawsamples[k*nsamp]),1,
result.u.get_address(k,0),3);
current_file_position=ftell(fp);
return(result);
}catch(...){throw;};
}
/* This code was derived from GetNextEnsemble (scalar data version) above*/
auto_ptr<ThreeComponentEnsemble> GenericFileHandle::GetNext3CEnsemble()
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling GetNext3CEnsemble method");
const string base_error("GenericFileHandle::GetNextEnsemble: ");
if(!readmode) throw SeisppError(base_error
+ "Coding error. Trying to read when handle is in write mode");
if(this->eof()) throw SeisppError(base_error
+ "Attempt to read past end of file. Fix calling program logic.");
/* When reading an ensemble we assume all the traces have the same
value for ensemble attributes. Thus we assume we can read them
from the first trace in each ensemble */
try {
// Save this to insulate against changes in behaviour of
// FixedFormatTrace object
long last_offset=current_file_position;
auto_ptr<ThreeComponentEnsemble> result(new ThreeComponentEnsemble());
FixedFormatTrace NextSeis(dbuffer,fp,nskey_ext,dtkey_ext,
key_is_dt);
LoadMetadata(NextSeis,dynamic_cast<Metadata&>(*result),
ensemble_mdlist);
/* Minor inefficiency but we back up to read the last trace
again. This is necessary so we can just call the
GetNextSeismogram method to load the whole thing. */
fseek(fp,last_offset,SEEK_SET);
/* Now we load data until the key attributes change or we
hit eof */
ThreeComponentSeismogram d,dlast;
int tracecount(0);
do {
last_offset=current_file_position;
d=this->GetNext3CSeismogram();
if(tracecount==0) dlast=d;
if(this->keys_match(d,dlast))
{
result->member.push_back(d);
current_file_position=ftell(fp);
++tracecount;
}
else
{
/*If keys do not match we already read the next seismogram
so we have to then back the file pointer so
the next read will be from the right position.*/
fseek(fp,last_offset,SEEK_SET);
// Not really required, but best made explicit
current_file_position=last_offset;
// this is the loop break except at eof
break;
}
dlast=d;
}while(!this->eof());
return(result);
}catch(...){throw;};
}
void GenericFileHandle::put_metadata_to_dbuffer(Metadata& d,
list<string>& metanm)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put_metadata_to_dbuffer method");
list<string>::iterator mdlptr;
try{
for(mdlptr=metanm.begin();mdlptr!=metanm.end();++mdlptr)
{
int ival;
double dval;
bool bval;
string sval;
string extkey;
MDtype thiskey=xref.type(*mdlptr);
switch(thiskey)
{
case MDint:
ival=d.get_int(*mdlptr);
extkey=xref.external(*mdlptr);
dbuffer.put<int>(extkey,ival);
break;
case MDreal:
dval=d.get_double(*mdlptr);
extkey=xref.external(*mdlptr);
dbuffer.put<double>(extkey,dval);
break;
case MDboolean:
bval=d.get_bool(*mdlptr);
extkey=xref.external(*mdlptr);
dbuffer.put<bool>(extkey,bval);
break;
case MDstring:
sval=d.get_string(*mdlptr);
extkey=xref.external(*mdlptr);
dbuffer.put_string(extkey,sval);
break;
default:
cerr << "Warning: undefined attribute "
<< *mdlptr << " found in list of output metadata"
<<endl
<< "Output will not be useful if this attribute"
<< " is essential"<<endl;
}
}
}catch(...){throw;};
}
void GenericFileHandle::put_sample_interval(BasicTimeSeries& d)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put_sample_interval method");
double dtout;
if(key_is_dt)
{
dtout=d.dt*dtscale;
}
else
{
dtout=dtscale*(1.0/d.dt);
}
MDtype mdt=xref.type(dt_keyword);
switch(mdt)
{
case MDint:
dbuffer.put<int>(dtkey_ext,dtout);
case MDreal:
default:
dbuffer.put<double>(dtkey_ext,dtout);
}
}
int GenericFileHandle::put(TimeSeries& d)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put for TimeSeries method");
/* To be stateless one might want to always force a seek to eof,
but I do not do that on purpose for efficiency. Instead
all we really need to do is copy the required metadata to
the FixedFormatTrace object and then call operator >>.
So first we have a loop to post all the required metadata.*/
try {
if(no_write_dead && (!d.live)) return(0);
// Assume constructor already defined dbuffer
// Ensemble metadata will be written to every output
// trace along with the individual trace attributes.
// allow every trace to have a different sample size
dbuffer.resize(d.ns);
dbuffer.ns=d.ns;
dbuffer.put(0,d.s);
this->put_metadata_to_dbuffer(d,ensemble_mdlist);
this->put_metadata_to_dbuffer(d,trace_mdlist);
this->put_sample_interval(d);
this->lock();
dbuffer.write(outstrm);
this->unlock();
} catch(...){throw;};
return(1);
}
int GenericFileHandle::put(TimeSeriesEnsemble& d)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put for TimeSeriesEnsemble method");
int tracecount;
vector<TimeSeries>::iterator dptr;
try {
/* This loop could use the put(TimeSeries method but we
repeat the code there to avoid repeated locks. */
this->lock();
for(dptr=d.member.begin(),tracecount=0;dptr!=d.member.end();
++dptr,++tracecount)
{
if(no_write_dead && !(dptr->live)) continue;
// Allow each trace to have a different number of samples
dbuffer.resize(dptr->ns);
dbuffer.ns=dptr->ns;
dbuffer.put(0,dptr->s);
this->put_metadata_to_dbuffer(*dptr,trace_mdlist);
/* write these second so if attributes are duplicated in
trace and ensemble lists the ensemble versions override.
This uses the model that ensemble metadata are common
to all members*/
this->put_metadata_to_dbuffer(d,ensemble_mdlist);
this->put_sample_interval(*dptr);
dbuffer.write(outstrm);
}
this->unlock();
} catch(...){
//Make sure we unlock the file if it got locked and we had a failure
this->unlock();
throw;
};
return(tracecount);
}
/* Now similar code for ThreeComponentSeismogram and ensemble */
int GenericFileHandle::put(ThreeComponentSeismogram& d)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put for ThreeComponentSeismogram method");
const string base_error("GenericFileHandle::put method for 3c seismogram: ");
/* To be stateless one might want to always force a seek to eof,
but I do not do that on purpose for efficiency. Instead
all we really need to do is copy the required metadata to
the FixedFormatTrace object and then call operator >>.
So first we have a loop to post all the required metadata.*/
try {
if(no_write_dead && (!d.live)) return(0);
/* The put methods below will cause a seg fault if we didn't
test for this condition so an exception is essential */
if(!dbuffer.data_are_3c) throw SeisppError(base_error
+ "trying to put 3c data to requested format is illegal\n"
+ "Definition does not defines this as a 3c format.");
/* Assume constructor already defined dbuffer. As for
TimeSeries we write ensemble metadata to each trace and
trace headers for each 3c block. */
dbuffer.resize(d.ns);
dbuffer.ns=d.ns;
int ntotal=3*dbuffer.ns;
if(dbuffer.channel_order)
{
// channel order is the transpose of the u matrix
dmatrix ut=tr(d.u);
dbuffer.put(0,ntotal,ut.get_address(0,0));
}
else
{
dbuffer.put(0,ntotal,d.u.get_address(0,0));
}
this->put_metadata_to_dbuffer(d,ensemble_mdlist);
this->put_metadata_to_dbuffer(d,trace_mdlist);
this->put_sample_interval(d);
this->lock();
dbuffer.write(outstrm);
this->unlock();
} catch(...){throw;};
return(1);
}
int GenericFileHandle::put(ThreeComponentEnsemble& d)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put for ThreeComponentEnsemble method");
const string base_error("GenericFileHandle::put method for 3c ensemble: ");
if(!dbuffer.data_are_3c) throw SeisppError(base_error
+ "3c ensemble put method called for a format that is not 3c\n"
+ "Check format selected and/or definition of this format");
int tracecount;
vector<ThreeComponentSeismogram>::iterator dptr;
try {
/* This loop could use the put(ThreeComponentSeismogram method but we
repeat the code there to avoid repeated locks. */
this->lock();
for(dptr=d.member.begin(),tracecount=0;dptr!=d.member.end();
++dptr,++tracecount)
{
if(no_write_dead && !(dptr->live)) continue;
// Allow each trace to have a different number of samples
dbuffer.resize(dptr->ns);
dbuffer.ns=dptr->ns;
int ntotal=3*dbuffer.ns;
if(dbuffer.channel_order)
{
// Channel order is the transpose of the data matrix
dmatrix ut=tr(dptr->u);
dbuffer.put(0,ntotal,ut.get_address(0,0));
}
else
{
dbuffer.put(0,ntotal,dptr->u.get_address(0,0));
}
this->put_metadata_to_dbuffer(*dptr,trace_mdlist);
/* write these second so if attributes are duplicated in
trace and ensemble lists the ensemble versions override.
This uses the model that ensemble metadata are common
to all members*/
this->put_metadata_to_dbuffer(d,ensemble_mdlist);
this->put_sample_interval(*dptr);
dbuffer.write(outstrm);
}
this->unlock();
} catch(...){
//Make sure we unlock the file if it got locked and we had a failure
this->unlock();
throw;
};
return(tracecount);
}
int GenericFileHandle::put(const char *b, int nb)
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling put for raw buffer of unsigned char");
const string base_error("GenericFileHandle::put method for generic buffer: ");
if(b==NULL)
throw SeisppError(base_error + "Received a nill pointer");
try{
this->lock();
outstrm.write(b,nb);
this->unlock();
} catch(...){
//Make sure we unlock the file if it got locked and we had a failure
this->unlock();
throw;
};
/* Here always return nb. Perhaps should check stream for an error */
return(nb);
}
/* Copied from the web from url http://www.techbytes.ca/techbyte103.html */
bool FileExists(string strFilename) {
struct stat stFileInfo;
bool blnReturn;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
if(intStat == 0) {
// We were able to get the file attributes
// so the file obviously exists.
blnReturn = true;
} else {
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
blnReturn = false;
}
return(blnReturn);
}
string lockfilename(string base)
{
return(base + ".lock");
}
void GenericFileHandle::lock()
{
string lockfname=lockfilename(fname);
int i;
for(i=0;i<retry_limit;++i)
{
if(FileExists(lockfname))
sleep(sleep_interval);
else
{
FILE *fp;
fp=fopen(lockfname.c_str(),"w");
fclose(fp);
return;
}
}
throw SeisppError(string("GenericFileHandle::lock ")
+ "Cannot obtain a lock for output file "+fname);
}
void GenericFileHandle::unlock()
{
/* Intentionally do nothing if lock file does not exist.
This allows destructor to clear a lock in the event of an error. */
string lockfname=lockfilename(fname);
if(FileExists(lockfname))
{
if(remove(lockfname.c_str()))
{
throw SeisppError(string("GenericFileHandle::unlock: ")
+ string("Could not remove lock file=")
+ lockfname
+"\nRemove manually and beware deadlocks if caller blunders on");
}
}
}
void GenericFileHandle::rewind()
{
if(handle_not_ready)
throw SeisppError(notreadyerror
+ " when calling rewind method");
if(readmode)
{
std::rewind(this->fp);
}
else
{
outstrm.seekp(0L);
if(SEISPP_verbose) cerr << "WARNING: "
"GenericFileHandle.rewind called on an output file"<<endl;
}
current_file_position=0;
}
} // end SEISPP namespace encapsulation
|
#include <bits/stdc++.h>
#include <omp.h>
#include <sys/time.h>
using namespace std;
//
namespace {
static const int MAXN = 8;
static int Cn[MAXN], CnBase[MAXN][MAXN];
struct T {
char v[MAXN][MAXN];
} _mem[1<<16];
static T *LCA[MAXN];
void printTidInfo(int l, int i) {
int lsz, rsz, lid, rid;
{
int sum = 0;
for (rsz = 0; sum + Cn[rsz]*Cn[i-1-rsz] <= l; rsz++)
sum += Cn[rsz]*Cn[i-1-rsz];
lsz = i-1-rsz;
lid = (l - sum) / Cn[rsz];
rid = (l - sum) % Cn[rsz];
}
fprintf(stderr, "size[%2d], id[%2d], subid<%2d %2d>, sub<%2d %2d>\n", i, l, lid, rid, lsz, rsz);
for (int p = 0; p < i; p++) {
for (int q = 0; q < i; q++)
fprintf(stderr, "%2d ", LCA[i][l].v[p][q]);
fputs("\n", stderr);
}
}
void buildLCA() {
const int P = 4;
omp_set_num_threads(P);
LCA[0] = _mem;
LCA[1] = _mem+1;
for (int i = 2, off = 1; i < MAXN; i++) {
off += Cn[i-1];
LCA[i] = _mem + off;
int chunk = (Cn[i]+P-1)/P;
// for (int j = 0; j < Cn[i]; j++)
#pragma omp parallel firstprivate(i)
{
// prepare
int tid = omp_get_thread_num();
int l = tid * chunk;
int r = min(l + chunk, Cn[i]);
int lsz, rsz, lid, rid;
// #pragma omp critical
if (l < r)
{
int sum = 0;
for (lsz = 0; CnBase[i][lsz] > l; lsz++);
sum = CnBase[i][lsz];
rsz = i-1-lsz;
lid = (l - sum) / Cn[rsz];
rid = (l - sum) % Cn[rsz];
}
// start
T *store = LCA[i];
for (int j = l; j < r; j++) {
for (int p = 0; p < lsz; p++)
for (int q = p; q < lsz; q++)
store[j].v[p][q] = LCA[lsz][lid].v[p][q];
for (int p = lsz+1; p < i; p++)
for (int q = p; q < i; q++)
store[j].v[p][q] = LCA[rsz][rid].v[p-lsz-1][q-lsz-1]+lsz+1;
for (int p = 0; p <= lsz; p++)
for (int q = lsz; q < i; q++)
store[j].v[p][q] = lsz;
// printTidInfo(j, i);
rid++;
if (rid == Cn[rsz]) {
rid = 0, lid++;
if (lid == Cn[lsz])
lid = 0, lsz--, rsz++;
}
}
}
}
// fprintf(stderr, "Run Success\n");
}
void ballotTlb() {
Cn[0] = 1, Cn[1] = 1;
CnBase[1][1] = 1;
for (int i = 1; i < MAXN; i++) {
int ret = 0;
for (int j = 0; j < i; j++)
CnBase[i][i-j-1] = ret, ret += Cn[j]*Cn[i-1-j];
CnBase[i][i] = Cn[i] = ret;
}
}
int tid(int lsz, int lid, int rsz, int rid) {
if (rsz == 0) return lid;
int base = CnBase[lsz+rsz+1][lsz];
int offset = rid + lid*Cn[rsz];
return base + offset;
}
int typeOfCartesian(int A[], int s) {
int D[s+1], Dp = 0;
int I[s+1][2];
D[0] = 0x3f3f3f3f;
for (int i = 1; i <= s; i++) {
int v = *A;
int lsz = 0, lid = 0;
while (D[Dp] < v) {
lid = tid(I[Dp][0], I[Dp][1], lsz, lid);
lsz += I[Dp][0]+1;
Dp--;
}
Dp++, A++;
D[Dp] = v;
I[Dp][0] = lsz, I[Dp][1] = lid;
}
int lsz = 0, lid = 0;
while (Dp) {
lid = tid(I[Dp][0], I[Dp][1], lsz, lid);
lsz += I[Dp][0]+1;
Dp--;
}
return lid;
}
struct State {
int i, s, tid;
int D[MAXN+1][4], Dp;
};
int typeOfCartesian(State &state, int v) {
int Dp = state.Dp;
int lsz = 0, lid = 0;
int bsz = state.s-state.i+1, bid = Cn[state.s-state.i+1]-1;
while (state.D[Dp][0] < v) {
lid = tid(state.D[Dp][1], state.D[Dp][2], lsz, lid);
lsz += state.D[Dp][1]+1;
bid = tid(state.D[Dp][1], state.D[Dp][2], bsz, bid);
bsz += state.D[Dp][1]+1;
Dp--;
}
Dp++;
int ins = bid;
int _tid = tid(lsz, lid, state.s-state.i, Cn[state.s-state.i]-1);
// fprintf(stderr, "ins %d -> %d\n", ins, _tid);
ins = _tid - ins;
state.D[Dp][0] = v, state.D[Dp][1] = lsz, state.D[Dp][2] = lid, state.D[Dp][3] = _tid;
state.i++;
state.Dp = Dp;
state.tid += ins;
return state.tid;
}
}
int test(int A[], int n) {
int tid = typeOfCartesian(A, n);
for (int l = 0; l < n; l++) {
for (int r = l; r < n; r++) {
int mx = A[l];
for (int k = l; k <= r; k++)
mx = max(mx, A[k]);
if (mx != A[LCA[n][tid].v[l][r]])
return 0;
}
}
State t;
t.i = 1, t.s = n, t.tid = Cn[n]-1;
t.D[0][0] = 0x3f3f3f3f, t.Dp = 0;
for (int i = 0; i < n; i++) {
typeOfCartesian(t, A[i]);
int c_tid = t.tid;
for (int p = 0; p <= i; p++) {
for (int q = p; q <= i; q++) {
int mx = A[p];
for (int k = p; k <= q; k++)
mx = max(mx, A[k]);
assert(mx == A[LCA[n][c_tid].v[p][q]]);
}
}
}
if (tid != t.tid) {
for (int i = 0; i < n; i++)
fprintf(stderr, "%d ", A[i]);
fprintf(stderr, "\n");
fprintf(stderr, "Expect %d, Coroutine %d\n", tid, t.tid);
}
return 1;
}
void testAll() {
fprintf(stderr, "Run Test All\n");
// generate all permutations of input
for (int i = 1; i < MAXN; i++) {
int A[MAXN] = {};
for (int j = 0; j < i; j++)
A[j] = j;
int testcase = 0;
fprintf(stderr, "#Node %d\n", i);
do {
if (test(A, i)) {
// if (testcase % 1000 == 0)
// printf("n[%d] Testcase #%3d: PASS\n", i, ++testcase);
} else {
for (int k = 0; k < i; k++)
printf("%d ", A[k]);
puts("");
assert(false && "Failed");
}
} while (next_permutation(A, A+i));
}
/*
for (int i = 0; i < 10000000; i++) {
int A[MAXN] = {};
int n = MAXN-1;
for (int j = 0; j < n; j++)
A[j] = rand()%n;
if (test(A, n)) {
} else {
for (int k = 0; k < n; k++)
printf("%d ", A[k]);
puts("");
assert(false && "Failed");
}
}
*/
fprintf(stderr, "PASS ALL\n\n");
}
int nativeQuery(int A[], int n) {
int sum = 0;
for (int l = 0; l < n; l++) {
for (int r = l; r < n; r++) {
int mx = A[l];
for (int k = l; k <= r; k++)
mx = max(mx, A[k]);
sum += mx;
}
}
return sum;
}
int fastQuery(int A[], int n) {
int tid = typeOfCartesian(A, n);
int sum = 0;
for (int l = 0; l < n; l++) {
for (int r = l; r < n; r++) {
sum += A[LCA[n][tid].v[l][r]];
}
}
return sum;
}
void testExp() {
// generate all permutations of input
fprintf(stderr, "Compute Time\n");
for (int i = 1; i < MAXN; i++) {
fprintf(stderr, "#Node %d\n", i);
{
struct timeval t1, t2;
double elapsedTime = 0;
int avBase = 50;
int checksum = 0;
for (int it = 0; it < avBase; it++) {
int A[MAXN] = {};
for (int j = 0; j < i; j++)
A[j] = j;
int testcase = 0;
do {
gettimeofday(&t1, NULL);
checksum += fastQuery(A, i);
gettimeofday(&t2, NULL);
elapsedTime += (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
} while (next_permutation(A, A+i));
}
fprintf(stderr, "Fast Time %lf ms. Checksum %X\n", elapsedTime/avBase/(i*(i+1)/2), checksum);
}
{
struct timeval t1, t2;
double elapsedTime = 0;
int avBase = 50;
int checksum = 0;
for (int it = 0; it < avBase; it++) {
int A[MAXN] = {};
for (int j = 0; j < i; j++)
A[j] = j;
int testcase = 0;
do {
gettimeofday(&t1, NULL);
checksum += nativeQuery(A, i);
gettimeofday(&t2, NULL);
elapsedTime += (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
} while (next_permutation(A, A+i));
}
fprintf(stderr, "Native Time %lf ms. Checksum %X\n", elapsedTime/avBase/(i*(i+1)/2), checksum);
}
}
fprintf(stderr, "PASS ALL\n\n");
}
int main() {
{
struct timeval t1, t2;
double elapsedTime;
gettimeofday(&t1, NULL);
ballotTlb();
int avBase = 1000;
for (int i = 0; i < avBase; i++)
buildLCA();
gettimeofday(&t2, NULL);
// compute and print the elapsed time in millisec
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
fprintf(stderr, "Build Table Time %lf ms.\n", elapsedTime/avBase);
}
// testAll
testAll();
// expr
testExp();
// char line[128];
// while (fgets(line, 100, stdin)) {
// stringstream sin(line);
// int n = 0, x;
// int A[16] = {0};
// while (sin >> x)
// A[n++] = x;
//
// int tid = typeOfCartesian(A, n);
// printf("tid = %d\n", tid);
// printTidInfo(tid, n);
// for (int l = 0; l < n; l++) {
// for (int r = l; r < n; r++) {
// int mx = A[l];
// for (int k = l; k <= r; k++)
// mx = max(mx, A[k]);
// if (mx != A[LCA[n][tid].v[l][r]])
// printf("max(A[%d, %d]) = %d\n", l, r, mx);
// }
// }
// }
return 0;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new vDinar address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current vDinar address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <vdinaraddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid vDinar address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <vdinaraddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid vDinar address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <vdinaraddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid vDinar address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <vdinaraddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <vdinaraddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <vdinaraddress> [minconf=1]\n"
"Returns the total amount received by <vdinaraddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid vDinar address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsConfirmed())
continue;
int64 allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <tovdinaraddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid vDinar address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid vDinar address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
//
// Used by addmultisigaddress / createmultisig:
//
static CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: vDinar address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a vDinar address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : vdinar address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
struct tallyitem
{
int64 nAmount;
int nConf;
vector<uint256> txids;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
Array transactions;
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included\n"
" \"txids\" : list of transactions with outputs to the address\n");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; vDinar server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <vdinaraddress>\n"
"Return information about <vdinaraddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock? [array-of-Objects]\n"
"Updates list of temporarily unspendable outputs.");
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH(Value& output, outputs)
{
if (output.type() != obj_type)
throw JSONRPCError(-8, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"Returns list of temporarily unspendable outputs.");
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
|
//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements extra semantic analysis beyond what is enforced
// by the C type system.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExprOpenMP.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Analysis/Analyses/FormatString.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/TargetBuiltins.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Locale.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/raw_ostream.h"
#include <limits>
using namespace clang;
using namespace sema;
SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const {
return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
Context.getTargetInfo());
}
/// Checks that a call expression's argument count is the desired number.
/// This is useful when doing custom type-checking. Returns true on error.
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
unsigned argCount = call->getNumArgs();
if (argCount == desiredArgCount) return false;
if (argCount < desiredArgCount)
return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
<< 0 /*function call*/ << desiredArgCount << argCount
<< call->getSourceRange();
// Highlight all the excess arguments.
SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
call->getArg(argCount - 1)->getLocEnd());
return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
<< 0 /*function call*/ << desiredArgCount << argCount
<< call->getArg(1)->getSourceRange();
}
/// Check that the first argument to __builtin_annotation is an integer
/// and the second argument is a non-wide string literal.
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 2))
return true;
// First argument should be an integer.
Expr *ValArg = TheCall->getArg(0);
QualType Ty = ValArg->getType();
if (!Ty->isIntegerType()) {
S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
<< ValArg->getSourceRange();
return true;
}
// Second argument should be a constant string.
Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
if (!Literal || !Literal->isAscii()) {
S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
<< StrArg->getSourceRange();
return true;
}
TheCall->setType(Ty);
return false;
}
/// Check that the argument to __builtin_addressof is a glvalue, and set the
/// result type to the corresponding pointer type.
static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 1))
return true;
ExprResult Arg(TheCall->getArg(0));
QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
if (ResultType.isNull())
return true;
TheCall->setArg(0, Arg.get());
TheCall->setType(ResultType);
return false;
}
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 3))
return true;
// First two arguments should be integers.
for (unsigned I = 0; I < 2; ++I) {
Expr *Arg = TheCall->getArg(I);
QualType Ty = Arg->getType();
if (!Ty->isIntegerType()) {
S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
<< Ty << Arg->getSourceRange();
return true;
}
}
// Third argument should be a pointer to a non-const integer.
// IRGen correctly handles volatile, restrict, and address spaces, and
// the other qualifiers aren't possible.
{
Expr *Arg = TheCall->getArg(2);
QualType Ty = Arg->getType();
const auto *PtrTy = Ty->getAs<PointerType>();
if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
!PtrTy->getPointeeType().isConstQualified())) {
S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
<< Ty << Arg->getSourceRange();
return true;
}
}
return false;
}
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
CallExpr *TheCall, unsigned SizeIdx,
unsigned DstSizeIdx) {
if (TheCall->getNumArgs() <= SizeIdx ||
TheCall->getNumArgs() <= DstSizeIdx)
return;
const Expr *SizeArg = TheCall->getArg(SizeIdx);
const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
llvm::APSInt Size, DstSize;
// find out if both sizes are known at compile time
if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
!DstSizeArg->EvaluateAsInt(DstSize, S.Context))
return;
if (Size.ule(DstSize))
return;
// confirmed overflow so generate the diagnostic.
IdentifierInfo *FnName = FDecl->getIdentifier();
SourceLocation SL = TheCall->getLocStart();
SourceRange SR = TheCall->getSourceRange();
S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
}
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
if (checkArgCount(S, BuiltinCall, 2))
return true;
SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
Expr *Call = BuiltinCall->getArg(0);
Expr *Chain = BuiltinCall->getArg(1);
if (Call->getStmtClass() != Stmt::CallExprClass) {
S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
<< Call->getSourceRange();
return true;
}
auto CE = cast<CallExpr>(Call);
if (CE->getCallee()->getType()->isBlockPointerType()) {
S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
<< Call->getSourceRange();
return true;
}
const Decl *TargetDecl = CE->getCalleeDecl();
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
if (FD->getBuiltinID()) {
S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
<< Call->getSourceRange();
return true;
}
if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
<< Call->getSourceRange();
return true;
}
ExprResult ChainResult = S.UsualUnaryConversions(Chain);
if (ChainResult.isInvalid())
return true;
if (!ChainResult.get()->getType()->isPointerType()) {
S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
<< Chain->getSourceRange();
return true;
}
QualType ReturnTy = CE->getCallReturnType(S.Context);
QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
QualType BuiltinTy = S.Context.getFunctionType(
ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
Builtin =
S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
BuiltinCall->setType(CE->getType());
BuiltinCall->setValueKind(CE->getValueKind());
BuiltinCall->setObjectKind(CE->getObjectKind());
BuiltinCall->setCallee(Builtin);
BuiltinCall->setArg(1, ChainResult.get());
return false;
}
static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
Scope::ScopeFlags NeededScopeFlags,
unsigned DiagID) {
// Scopes aren't available during instantiation. Fortunately, builtin
// functions cannot be template args so they cannot be formed through template
// instantiation. Therefore checking once during the parse is sufficient.
if (!SemaRef.ActiveTemplateInstantiations.empty())
return false;
Scope *S = SemaRef.getCurScope();
while (S && !S->isSEHExceptScope())
S = S->getParent();
if (!S || !(S->getFlags() & NeededScopeFlags)) {
auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
SemaRef.Diag(TheCall->getExprLoc(), DiagID)
<< DRE->getDecl()->getIdentifier();
return true;
}
return false;
}
/// Returns OpenCL access qual.
static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
return D->getAttr<OpenCLAccessAttr>();
}
/// Returns true if pipe element type is different from the pointer.
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
const Expr *Arg0 = Call->getArg(0);
// First argument type should always be pipe.
if (!Arg0->getType()->isPipeType()) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
<< Call->getDirectCallee() << Arg0->getSourceRange();
return true;
}
OpenCLAccessAttr *AccessQual =
getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
// Validates the access qualifier is compatible with the call.
// OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
// read_only and write_only, and assumed to be read_only if no qualifier is
// specified.
switch (Call->getDirectCallee()->getBuiltinID()) {
case Builtin::BIread_pipe:
case Builtin::BIreserve_read_pipe:
case Builtin::BIcommit_read_pipe:
case Builtin::BIwork_group_reserve_read_pipe:
case Builtin::BIsub_group_reserve_read_pipe:
case Builtin::BIwork_group_commit_read_pipe:
case Builtin::BIsub_group_commit_read_pipe:
if (!(!AccessQual || AccessQual->isReadOnly())) {
S.Diag(Arg0->getLocStart(),
diag::err_opencl_builtin_pipe_invalid_access_modifier)
<< "read_only" << Arg0->getSourceRange();
return true;
}
break;
case Builtin::BIwrite_pipe:
case Builtin::BIreserve_write_pipe:
case Builtin::BIcommit_write_pipe:
case Builtin::BIwork_group_reserve_write_pipe:
case Builtin::BIsub_group_reserve_write_pipe:
case Builtin::BIwork_group_commit_write_pipe:
case Builtin::BIsub_group_commit_write_pipe:
if (!(AccessQual && AccessQual->isWriteOnly())) {
S.Diag(Arg0->getLocStart(),
diag::err_opencl_builtin_pipe_invalid_access_modifier)
<< "write_only" << Arg0->getSourceRange();
return true;
}
break;
default:
break;
}
return false;
}
/// Returns true if pipe element type is different from the pointer.
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
const Expr *Arg0 = Call->getArg(0);
const Expr *ArgIdx = Call->getArg(Idx);
const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
const QualType EltTy = PipeTy->getElementType();
const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
// The Idx argument should be a pointer and the type of the pointer and
// the type of pipe element should also be the same.
if (!ArgTy ||
!S.Context.hasSameType(
EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.getPointerType(EltTy)
<< ArgIdx->getType() << ArgIdx->getSourceRange();
return true;
}
return false;
}
// \brief Performs semantic analysis for the read/write_pipe call.
// \param S Reference to the semantic analyzer.
// \param Call A pointer to the builtin call.
// \return True if a semantic error has been found, false otherwise.
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
// OpenCL v2.0 s6.13.16.2 - The built-in read/write
// functions have two forms.
switch (Call->getNumArgs()) {
case 2: {
if (checkOpenCLPipeArg(S, Call))
return true;
// The call with 2 arguments should be
// read/write_pipe(pipe T, T*).
// Check packet type T.
if (checkOpenCLPipePacketType(S, Call, 1))
return true;
} break;
case 4: {
if (checkOpenCLPipeArg(S, Call))
return true;
// The call with 4 arguments should be
// read/write_pipe(pipe T, reserve_id_t, uint, T*).
// Check reserve_id_t.
if (!Call->getArg(1)->getType()->isReserveIDT()) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.OCLReserveIDTy
<< Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
return true;
}
// Check the index.
const Expr *Arg2 = Call->getArg(2);
if (!Arg2->getType()->isIntegerType() &&
!Arg2->getType()->isUnsignedIntegerType()) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.UnsignedIntTy
<< Arg2->getType() << Arg2->getSourceRange();
return true;
}
// Check packet type T.
if (checkOpenCLPipePacketType(S, Call, 3))
return true;
} break;
default:
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
<< Call->getDirectCallee() << Call->getSourceRange();
return true;
}
return false;
}
// \brief Performs a semantic analysis on the {work_group_/sub_group_
// /_}reserve_{read/write}_pipe
// \param S Reference to the semantic analyzer.
// \param Call The call to the builtin function to be analyzed.
// \return True if a semantic error was found, false otherwise.
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
if (checkArgCount(S, Call, 2))
return true;
if (checkOpenCLPipeArg(S, Call))
return true;
// Check the reserve size.
if (!Call->getArg(1)->getType()->isIntegerType() &&
!Call->getArg(1)->getType()->isUnsignedIntegerType()) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.UnsignedIntTy
<< Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
return true;
}
return false;
}
// \brief Performs a semantic analysis on {work_group_/sub_group_
// /_}commit_{read/write}_pipe
// \param S Reference to the semantic analyzer.
// \param Call The call to the builtin function to be analyzed.
// \return True if a semantic error was found, false otherwise.
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
if (checkArgCount(S, Call, 2))
return true;
if (checkOpenCLPipeArg(S, Call))
return true;
// Check reserve_id_t.
if (!Call->getArg(1)->getType()->isReserveIDT()) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.OCLReserveIDTy
<< Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
return true;
}
return false;
}
// \brief Performs a semantic analysis on the call to built-in Pipe
// Query Functions.
// \param S Reference to the semantic analyzer.
// \param Call The call to the builtin function to be analyzed.
// \return True if a semantic error was found, false otherwise.
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
if (checkArgCount(S, Call, 1))
return true;
if (!Call->getArg(0)->getType()->isPipeType()) {
S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
<< Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
return true;
}
return false;
}
ExprResult
Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
CallExpr *TheCall) {
ExprResult TheCallResult(TheCall);
// Find out if any arguments are required to be integer constant expressions.
unsigned ICEArguments = 0;
ASTContext::GetBuiltinTypeError Error;
Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
if (Error != ASTContext::GE_None)
ICEArguments = 0; // Don't diagnose previously diagnosed errors.
// If any arguments are required to be ICE's, check and diagnose.
for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
// Skip arguments not required to be ICE's.
if ((ICEArguments & (1 << ArgNo)) == 0) continue;
llvm::APSInt Result;
if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
return true;
ICEArguments &= ~(1 << ArgNo);
}
switch (BuiltinID) {
case Builtin::BI__builtin___CFStringMakeConstantString:
assert(TheCall->getNumArgs() == 1 &&
"Wrong # arguments to builtin CFStringMakeConstantString");
if (CheckObjCString(TheCall->getArg(0)))
return ExprError();
break;
case Builtin::BI__builtin_stdarg_start:
case Builtin::BI__builtin_va_start:
if (SemaBuiltinVAStart(TheCall))
return ExprError();
break;
case Builtin::BI__va_start: {
switch (Context.getTargetInfo().getTriple().getArch()) {
case llvm::Triple::arm:
case llvm::Triple::thumb:
if (SemaBuiltinVAStartARM(TheCall))
return ExprError();
break;
default:
if (SemaBuiltinVAStart(TheCall))
return ExprError();
break;
}
break;
}
case Builtin::BI__builtin_isgreater:
case Builtin::BI__builtin_isgreaterequal:
case Builtin::BI__builtin_isless:
case Builtin::BI__builtin_islessequal:
case Builtin::BI__builtin_islessgreater:
case Builtin::BI__builtin_isunordered:
if (SemaBuiltinUnorderedCompare(TheCall))
return ExprError();
break;
case Builtin::BI__builtin_fpclassify:
if (SemaBuiltinFPClassification(TheCall, 6))
return ExprError();
break;
case Builtin::BI__builtin_isfinite:
case Builtin::BI__builtin_isinf:
case Builtin::BI__builtin_isinf_sign:
case Builtin::BI__builtin_isnan:
case Builtin::BI__builtin_isnormal:
if (SemaBuiltinFPClassification(TheCall, 1))
return ExprError();
break;
case Builtin::BI__builtin_shufflevector:
return SemaBuiltinShuffleVector(TheCall);
// TheCall will be freed by the smart pointer here, but that's fine, since
// SemaBuiltinShuffleVector guts it, but then doesn't release it.
case Builtin::BI__builtin_prefetch:
if (SemaBuiltinPrefetch(TheCall))
return ExprError();
break;
case Builtin::BI__assume:
case Builtin::BI__builtin_assume:
if (SemaBuiltinAssume(TheCall))
return ExprError();
break;
case Builtin::BI__builtin_assume_aligned:
if (SemaBuiltinAssumeAligned(TheCall))
return ExprError();
break;
case Builtin::BI__builtin_object_size:
if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
return ExprError();
break;
case Builtin::BI__builtin_longjmp:
if (SemaBuiltinLongjmp(TheCall))
return ExprError();
break;
case Builtin::BI__builtin_setjmp:
if (SemaBuiltinSetjmp(TheCall))
return ExprError();
break;
case Builtin::BI_setjmp:
case Builtin::BI_setjmpex:
if (checkArgCount(*this, TheCall, 1))
return true;
break;
case Builtin::BI__builtin_classify_type:
if (checkArgCount(*this, TheCall, 1)) return true;
TheCall->setType(Context.IntTy);
break;
case Builtin::BI__builtin_constant_p:
if (checkArgCount(*this, TheCall, 1)) return true;
TheCall->setType(Context.IntTy);
break;
case Builtin::BI__sync_fetch_and_add:
case Builtin::BI__sync_fetch_and_add_1:
case Builtin::BI__sync_fetch_and_add_2:
case Builtin::BI__sync_fetch_and_add_4:
case Builtin::BI__sync_fetch_and_add_8:
case Builtin::BI__sync_fetch_and_add_16:
case Builtin::BI__sync_fetch_and_sub:
case Builtin::BI__sync_fetch_and_sub_1:
case Builtin::BI__sync_fetch_and_sub_2:
case Builtin::BI__sync_fetch_and_sub_4:
case Builtin::BI__sync_fetch_and_sub_8:
case Builtin::BI__sync_fetch_and_sub_16:
case Builtin::BI__sync_fetch_and_or:
case Builtin::BI__sync_fetch_and_or_1:
case Builtin::BI__sync_fetch_and_or_2:
case Builtin::BI__sync_fetch_and_or_4:
case Builtin::BI__sync_fetch_and_or_8:
case Builtin::BI__sync_fetch_and_or_16:
case Builtin::BI__sync_fetch_and_and:
case Builtin::BI__sync_fetch_and_and_1:
case Builtin::BI__sync_fetch_and_and_2:
case Builtin::BI__sync_fetch_and_and_4:
case Builtin::BI__sync_fetch_and_and_8:
case Builtin::BI__sync_fetch_and_and_16:
case Builtin::BI__sync_fetch_and_xor:
case Builtin::BI__sync_fetch_and_xor_1:
case Builtin::BI__sync_fetch_and_xor_2:
case Builtin::BI__sync_fetch_and_xor_4:
case Builtin::BI__sync_fetch_and_xor_8:
case Builtin::BI__sync_fetch_and_xor_16:
case Builtin::BI__sync_fetch_and_nand:
case Builtin::BI__sync_fetch_and_nand_1:
case Builtin::BI__sync_fetch_and_nand_2:
case Builtin::BI__sync_fetch_and_nand_4:
case Builtin::BI__sync_fetch_and_nand_8:
case Builtin::BI__sync_fetch_and_nand_16:
case Builtin::BI__sync_add_and_fetch:
case Builtin::BI__sync_add_and_fetch_1:
case Builtin::BI__sync_add_and_fetch_2:
case Builtin::BI__sync_add_and_fetch_4:
case Builtin::BI__sync_add_and_fetch_8:
case Builtin::BI__sync_add_and_fetch_16:
case Builtin::BI__sync_sub_and_fetch:
case Builtin::BI__sync_sub_and_fetch_1:
case Builtin::BI__sync_sub_and_fetch_2:
case Builtin::BI__sync_sub_and_fetch_4:
case Builtin::BI__sync_sub_and_fetch_8:
case Builtin::BI__sync_sub_and_fetch_16:
case Builtin::BI__sync_and_and_fetch:
case Builtin::BI__sync_and_and_fetch_1:
case Builtin::BI__sync_and_and_fetch_2:
case Builtin::BI__sync_and_and_fetch_4:
case Builtin::BI__sync_and_and_fetch_8:
case Builtin::BI__sync_and_and_fetch_16:
case Builtin::BI__sync_or_and_fetch:
case Builtin::BI__sync_or_and_fetch_1:
case Builtin::BI__sync_or_and_fetch_2:
case Builtin::BI__sync_or_and_fetch_4:
case Builtin::BI__sync_or_and_fetch_8:
case Builtin::BI__sync_or_and_fetch_16:
case Builtin::BI__sync_xor_and_fetch:
case Builtin::BI__sync_xor_and_fetch_1:
case Builtin::BI__sync_xor_and_fetch_2:
case Builtin::BI__sync_xor_and_fetch_4:
case Builtin::BI__sync_xor_and_fetch_8:
case Builtin::BI__sync_xor_and_fetch_16:
case Builtin::BI__sync_nand_and_fetch:
case Builtin::BI__sync_nand_and_fetch_1:
case Builtin::BI__sync_nand_and_fetch_2:
case Builtin::BI__sync_nand_and_fetch_4:
case Builtin::BI__sync_nand_and_fetch_8:
case Builtin::BI__sync_nand_and_fetch_16:
case Builtin::BI__sync_val_compare_and_swap:
case Builtin::BI__sync_val_compare_and_swap_1:
case Builtin::BI__sync_val_compare_and_swap_2:
case Builtin::BI__sync_val_compare_and_swap_4:
case Builtin::BI__sync_val_compare_and_swap_8:
case Builtin::BI__sync_val_compare_and_swap_16:
case Builtin::BI__sync_bool_compare_and_swap:
case Builtin::BI__sync_bool_compare_and_swap_1:
case Builtin::BI__sync_bool_compare_and_swap_2:
case Builtin::BI__sync_bool_compare_and_swap_4:
case Builtin::BI__sync_bool_compare_and_swap_8:
case Builtin::BI__sync_bool_compare_and_swap_16:
case Builtin::BI__sync_lock_test_and_set:
case Builtin::BI__sync_lock_test_and_set_1:
case Builtin::BI__sync_lock_test_and_set_2:
case Builtin::BI__sync_lock_test_and_set_4:
case Builtin::BI__sync_lock_test_and_set_8:
case Builtin::BI__sync_lock_test_and_set_16:
case Builtin::BI__sync_lock_release:
case Builtin::BI__sync_lock_release_1:
case Builtin::BI__sync_lock_release_2:
case Builtin::BI__sync_lock_release_4:
case Builtin::BI__sync_lock_release_8:
case Builtin::BI__sync_lock_release_16:
case Builtin::BI__sync_swap:
case Builtin::BI__sync_swap_1:
case Builtin::BI__sync_swap_2:
case Builtin::BI__sync_swap_4:
case Builtin::BI__sync_swap_8:
case Builtin::BI__sync_swap_16:
return SemaBuiltinAtomicOverloaded(TheCallResult);
case Builtin::BI__builtin_nontemporal_load:
case Builtin::BI__builtin_nontemporal_store:
return SemaBuiltinNontemporalOverloaded(TheCallResult);
#define BUILTIN(ID, TYPE, ATTRS)
#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
case Builtin::BI##ID: \
return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
#include "clang/Basic/Builtins.def"
case Builtin::BI__builtin_annotation:
if (SemaBuiltinAnnotation(*this, TheCall))
return ExprError();
break;
case Builtin::BI__builtin_addressof:
if (SemaBuiltinAddressof(*this, TheCall))
return ExprError();
break;
case Builtin::BI__builtin_add_overflow:
case Builtin::BI__builtin_sub_overflow:
case Builtin::BI__builtin_mul_overflow:
if (SemaBuiltinOverflow(*this, TheCall))
return ExprError();
break;
case Builtin::BI__builtin_operator_new:
case Builtin::BI__builtin_operator_delete:
if (!getLangOpts().CPlusPlus) {
Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
<< (BuiltinID == Builtin::BI__builtin_operator_new
? "__builtin_operator_new"
: "__builtin_operator_delete")
<< "C++";
return ExprError();
}
// CodeGen assumes it can find the global new and delete to call,
// so ensure that they are declared.
DeclareGlobalNewDelete();
break;
// check secure string manipulation functions where overflows
// are detectable at compile time
case Builtin::BI__builtin___memcpy_chk:
case Builtin::BI__builtin___memmove_chk:
case Builtin::BI__builtin___memset_chk:
case Builtin::BI__builtin___strlcat_chk:
case Builtin::BI__builtin___strlcpy_chk:
case Builtin::BI__builtin___strncat_chk:
case Builtin::BI__builtin___strncpy_chk:
case Builtin::BI__builtin___stpncpy_chk:
SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
break;
case Builtin::BI__builtin___memccpy_chk:
SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
break;
case Builtin::BI__builtin___snprintf_chk:
case Builtin::BI__builtin___vsnprintf_chk:
SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
break;
case Builtin::BI__builtin_call_with_static_chain:
if (SemaBuiltinCallWithStaticChain(*this, TheCall))
return ExprError();
break;
case Builtin::BI__exception_code:
case Builtin::BI_exception_code:
if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
diag::err_seh___except_block))
return ExprError();
break;
case Builtin::BI__exception_info:
case Builtin::BI_exception_info:
if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
diag::err_seh___except_filter))
return ExprError();
break;
case Builtin::BI__GetExceptionInfo:
if (checkArgCount(*this, TheCall, 1))
return ExprError();
if (CheckCXXThrowOperand(
TheCall->getLocStart(),
Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
TheCall))
return ExprError();
TheCall->setType(Context.VoidPtrTy);
break;
case Builtin::BIread_pipe:
case Builtin::BIwrite_pipe:
// Since those two functions are declared with var args, we need a semantic
// check for the argument.
if (SemaBuiltinRWPipe(*this, TheCall))
return ExprError();
break;
case Builtin::BIreserve_read_pipe:
case Builtin::BIreserve_write_pipe:
case Builtin::BIwork_group_reserve_read_pipe:
case Builtin::BIwork_group_reserve_write_pipe:
case Builtin::BIsub_group_reserve_read_pipe:
case Builtin::BIsub_group_reserve_write_pipe:
if (SemaBuiltinReserveRWPipe(*this, TheCall))
return ExprError();
// Since return type of reserve_read/write_pipe built-in function is
// reserve_id_t, which is not defined in the builtin def file , we used int
// as return type and need to override the return type of these functions.
TheCall->setType(Context.OCLReserveIDTy);
break;
case Builtin::BIcommit_read_pipe:
case Builtin::BIcommit_write_pipe:
case Builtin::BIwork_group_commit_read_pipe:
case Builtin::BIwork_group_commit_write_pipe:
case Builtin::BIsub_group_commit_read_pipe:
case Builtin::BIsub_group_commit_write_pipe:
if (SemaBuiltinCommitRWPipe(*this, TheCall))
return ExprError();
break;
case Builtin::BIget_pipe_num_packets:
case Builtin::BIget_pipe_max_packets:
if (SemaBuiltinPipePackets(*this, TheCall))
return ExprError();
break;
}
// Since the target specific builtins for each arch overlap, only check those
// of the arch we are compiling for.
if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
switch (Context.getTargetInfo().getTriple().getArch()) {
case llvm::Triple::arm:
case llvm::Triple::armeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb:
if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
return ExprError();
break;
case llvm::Triple::aarch64:
case llvm::Triple::aarch64_be:
if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
return ExprError();
break;
case llvm::Triple::mips:
case llvm::Triple::mipsel:
case llvm::Triple::mips64:
case llvm::Triple::mips64el:
if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
return ExprError();
break;
case llvm::Triple::systemz:
if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
return ExprError();
break;
case llvm::Triple::x86:
case llvm::Triple::x86_64:
if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
return ExprError();
break;
case llvm::Triple::ppc:
case llvm::Triple::ppc64:
case llvm::Triple::ppc64le:
if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
return ExprError();
break;
default:
break;
}
}
return TheCallResult;
}
// Get the valid immediate range for the specified NEON type code.
static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
NeonTypeFlags Type(t);
int IsQuad = ForceQuad ? true : Type.isQuad();
switch (Type.getEltType()) {
case NeonTypeFlags::Int8:
case NeonTypeFlags::Poly8:
return shift ? 7 : (8 << IsQuad) - 1;
case NeonTypeFlags::Int16:
case NeonTypeFlags::Poly16:
return shift ? 15 : (4 << IsQuad) - 1;
case NeonTypeFlags::Int32:
return shift ? 31 : (2 << IsQuad) - 1;
case NeonTypeFlags::Int64:
case NeonTypeFlags::Poly64:
return shift ? 63 : (1 << IsQuad) - 1;
case NeonTypeFlags::Poly128:
return shift ? 127 : (1 << IsQuad) - 1;
case NeonTypeFlags::Float16:
assert(!shift && "cannot shift float types!");
return (4 << IsQuad) - 1;
case NeonTypeFlags::Float32:
assert(!shift && "cannot shift float types!");
return (2 << IsQuad) - 1;
case NeonTypeFlags::Float64:
assert(!shift && "cannot shift float types!");
return (1 << IsQuad) - 1;
}
llvm_unreachable("Invalid NeonTypeFlag!");
}
/// getNeonEltType - Return the QualType corresponding to the elements of
/// the vector type specified by the NeonTypeFlags. This is used to check
/// the pointer arguments for Neon load/store intrinsics.
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
bool IsPolyUnsigned, bool IsInt64Long) {
switch (Flags.getEltType()) {
case NeonTypeFlags::Int8:
return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
case NeonTypeFlags::Int16:
return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
case NeonTypeFlags::Int32:
return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
case NeonTypeFlags::Int64:
if (IsInt64Long)
return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
else
return Flags.isUnsigned() ? Context.UnsignedLongLongTy
: Context.LongLongTy;
case NeonTypeFlags::Poly8:
return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
case NeonTypeFlags::Poly16:
return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
case NeonTypeFlags::Poly64:
if (IsInt64Long)
return Context.UnsignedLongTy;
else
return Context.UnsignedLongLongTy;
case NeonTypeFlags::Poly128:
break;
case NeonTypeFlags::Float16:
return Context.HalfTy;
case NeonTypeFlags::Float32:
return Context.FloatTy;
case NeonTypeFlags::Float64:
return Context.DoubleTy;
}
llvm_unreachable("Invalid NeonTypeFlag!");
}
bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
llvm::APSInt Result;
uint64_t mask = 0;
unsigned TV = 0;
int PtrArgNum = -1;
bool HasConstPtr = false;
switch (BuiltinID) {
#define GET_NEON_OVERLOAD_CHECK
#include "clang/Basic/arm_neon.inc"
#undef GET_NEON_OVERLOAD_CHECK
}
// For NEON intrinsics which are overloaded on vector element type, validate
// the immediate which specifies which variant to emit.
unsigned ImmArg = TheCall->getNumArgs()-1;
if (mask) {
if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
return true;
TV = Result.getLimitedValue(64);
if ((TV > 63) || (mask & (1ULL << TV)) == 0)
return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
<< TheCall->getArg(ImmArg)->getSourceRange();
}
if (PtrArgNum >= 0) {
// Check that pointer arguments have the specified type.
Expr *Arg = TheCall->getArg(PtrArgNum);
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
Arg = ICE->getSubExpr();
ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
QualType RHSTy = RHS.get()->getType();
llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
bool IsInt64Long =
Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
QualType EltTy =
getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
if (HasConstPtr)
EltTy = EltTy.withConst();
QualType LHSTy = Context.getPointerType(EltTy);
AssignConvertType ConvTy;
ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
if (RHS.isInvalid())
return true;
if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
RHS.get(), AA_Assigning))
return true;
}
// For NEON intrinsics which take an immediate value as part of the
// instruction, range check them here.
unsigned i = 0, l = 0, u = 0;
switch (BuiltinID) {
default:
return false;
#define GET_NEON_IMMEDIATE_CHECK
#include "clang/Basic/arm_neon.inc"
#undef GET_NEON_IMMEDIATE_CHECK
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
}
bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth) {
assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
BuiltinID == ARM::BI__builtin_arm_ldaex ||
BuiltinID == ARM::BI__builtin_arm_strex ||
BuiltinID == ARM::BI__builtin_arm_stlex ||
BuiltinID == AArch64::BI__builtin_arm_ldrex ||
BuiltinID == AArch64::BI__builtin_arm_ldaex ||
BuiltinID == AArch64::BI__builtin_arm_strex ||
BuiltinID == AArch64::BI__builtin_arm_stlex) &&
"unexpected ARM builtin");
bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
BuiltinID == ARM::BI__builtin_arm_ldaex ||
BuiltinID == AArch64::BI__builtin_arm_ldrex ||
BuiltinID == AArch64::BI__builtin_arm_ldaex;
DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
// Ensure that we have the proper number of arguments.
if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
return true;
// Inspect the pointer argument of the atomic builtin. This should always be
// a pointer type, whose element is an integral scalar or pointer type.
// Because it is a pointer type, we don't have to worry about any implicit
// casts here.
Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
if (PointerArgRes.isInvalid())
return true;
PointerArg = PointerArgRes.get();
const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
if (!pointerType) {
Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
<< PointerArg->getType() << PointerArg->getSourceRange();
return true;
}
// ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
// task is to insert the appropriate casts into the AST. First work out just
// what the appropriate type is.
QualType ValType = pointerType->getPointeeType();
QualType AddrType = ValType.getUnqualifiedType().withVolatile();
if (IsLdrex)
AddrType.addConst();
// Issue a warning if the cast is dodgy.
CastKind CastNeeded = CK_NoOp;
if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
CastNeeded = CK_BitCast;
Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
<< PointerArg->getType()
<< Context.getPointerType(AddrType)
<< AA_Passing << PointerArg->getSourceRange();
}
// Finally, do the cast and replace the argument with the corrected version.
AddrType = Context.getPointerType(AddrType);
PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
if (PointerArgRes.isInvalid())
return true;
PointerArg = PointerArgRes.get();
TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
// In general, we allow ints, floats and pointers to be loaded and stored.
if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
!ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
<< PointerArg->getType() << PointerArg->getSourceRange();
return true;
}
// But ARM doesn't have instructions to deal with 128-bit versions.
if (Context.getTypeSize(ValType) > MaxWidth) {
assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
<< PointerArg->getType() << PointerArg->getSourceRange();
return true;
}
switch (ValType.getObjCLifetime()) {
case Qualifiers::OCL_None:
case Qualifiers::OCL_ExplicitNone:
// okay
break;
case Qualifiers::OCL_Weak:
case Qualifiers::OCL_Strong:
case Qualifiers::OCL_Autoreleasing:
Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
<< ValType << PointerArg->getSourceRange();
return true;
}
if (IsLdrex) {
TheCall->setType(ValType);
return false;
}
// Initialize the argument to be stored.
ExprResult ValArg = TheCall->getArg(0);
InitializedEntity Entity = InitializedEntity::InitializeParameter(
Context, ValType, /*consume*/ false);
ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
if (ValArg.isInvalid())
return true;
TheCall->setArg(0, ValArg.get());
// __builtin_arm_strex always returns an int. It's marked as such in the .def,
// but the custom checker bypasses all default analysis.
TheCall->setType(Context.IntTy);
return false;
}
bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
llvm::APSInt Result;
if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
BuiltinID == ARM::BI__builtin_arm_ldaex ||
BuiltinID == ARM::BI__builtin_arm_strex ||
BuiltinID == ARM::BI__builtin_arm_stlex) {
return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
}
if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
}
if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
BuiltinID == ARM::BI__builtin_arm_wsr64)
return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
if (BuiltinID == ARM::BI__builtin_arm_rsr ||
BuiltinID == ARM::BI__builtin_arm_rsrp ||
BuiltinID == ARM::BI__builtin_arm_wsr ||
BuiltinID == ARM::BI__builtin_arm_wsrp)
return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
return true;
// For intrinsics which take an immediate value as part of the instruction,
// range check them here.
unsigned i = 0, l = 0, u = 0;
switch (BuiltinID) {
default: return false;
case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
case ARM::BI__builtin_arm_vcvtr_f:
case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
case ARM::BI__builtin_arm_dmb:
case ARM::BI__builtin_arm_dsb:
case ARM::BI__builtin_arm_isb:
case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
}
// FIXME: VFP Intrinsics should error if VFP not present.
return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
}
bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
CallExpr *TheCall) {
llvm::APSInt Result;
if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
BuiltinID == AArch64::BI__builtin_arm_ldaex ||
BuiltinID == AArch64::BI__builtin_arm_strex ||
BuiltinID == AArch64::BI__builtin_arm_stlex) {
return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
}
if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
}
if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
BuiltinID == AArch64::BI__builtin_arm_wsr64)
return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
BuiltinID == AArch64::BI__builtin_arm_rsrp ||
BuiltinID == AArch64::BI__builtin_arm_wsr ||
BuiltinID == AArch64::BI__builtin_arm_wsrp)
return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
return true;
// For intrinsics which take an immediate value as part of the instruction,
// range check them here.
unsigned i = 0, l = 0, u = 0;
switch (BuiltinID) {
default: return false;
case AArch64::BI__builtin_arm_dmb:
case AArch64::BI__builtin_arm_dsb:
case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
}
bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
unsigned i = 0, l = 0, u = 0;
switch (BuiltinID) {
default: return false;
case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u);
}
bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
unsigned i = 0, l = 0, u = 0;
bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
BuiltinID == PPC::BI__builtin_divdeu ||
BuiltinID == PPC::BI__builtin_bpermd;
bool IsTarget64Bit = Context.getTargetInfo()
.getTypeWidth(Context
.getTargetInfo()
.getIntPtrType()) == 64;
bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
BuiltinID == PPC::BI__builtin_divweu ||
BuiltinID == PPC::BI__builtin_divde ||
BuiltinID == PPC::BI__builtin_divdeu;
if (Is64BitBltin && !IsTarget64Bit)
return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
<< TheCall->getSourceRange();
if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
(BuiltinID == PPC::BI__builtin_bpermd &&
!Context.getTargetInfo().hasFeature("bpermd")))
return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
<< TheCall->getSourceRange();
switch (BuiltinID) {
default: return false;
case PPC::BI__builtin_altivec_crypto_vshasigmaw:
case PPC::BI__builtin_altivec_crypto_vshasigmad:
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
case PPC::BI__builtin_tbegin:
case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
case PPC::BI__builtin_tabortwc:
case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
case PPC::BI__builtin_tabortwci:
case PPC::BI__builtin_tabortdci:
return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u);
}
bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
CallExpr *TheCall) {
if (BuiltinID == SystemZ::BI__builtin_tabort) {
Expr *Arg = TheCall->getArg(0);
llvm::APSInt AbortCode(32);
if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
<< Arg->getSourceRange();
}
// For intrinsics which take an immediate value as part of the instruction,
// range check them here.
unsigned i = 0, l = 0, u = 0;
switch (BuiltinID) {
default: return false;
case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_verimb:
case SystemZ::BI__builtin_s390_verimh:
case SystemZ::BI__builtin_s390_verimf:
case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
case SystemZ::BI__builtin_s390_vfaeb:
case SystemZ::BI__builtin_s390_vfaeh:
case SystemZ::BI__builtin_s390_vfaef:
case SystemZ::BI__builtin_s390_vfaebs:
case SystemZ::BI__builtin_s390_vfaehs:
case SystemZ::BI__builtin_s390_vfaefs:
case SystemZ::BI__builtin_s390_vfaezb:
case SystemZ::BI__builtin_s390_vfaezh:
case SystemZ::BI__builtin_s390_vfaezf:
case SystemZ::BI__builtin_s390_vfaezbs:
case SystemZ::BI__builtin_s390_vfaezhs:
case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_vfidb:
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_vstrcb:
case SystemZ::BI__builtin_s390_vstrch:
case SystemZ::BI__builtin_s390_vstrcf:
case SystemZ::BI__builtin_s390_vstrczb:
case SystemZ::BI__builtin_s390_vstrczh:
case SystemZ::BI__builtin_s390_vstrczf:
case SystemZ::BI__builtin_s390_vstrcbs:
case SystemZ::BI__builtin_s390_vstrchs:
case SystemZ::BI__builtin_s390_vstrcfs:
case SystemZ::BI__builtin_s390_vstrczbs:
case SystemZ::BI__builtin_s390_vstrczhs:
case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u);
}
/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
/// This checks that the target supports __builtin_cpu_supports and
/// that the string argument is constant and valid.
static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
Expr *Arg = TheCall->getArg(0);
// Check if the argument is a string literal.
if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
<< Arg->getSourceRange();
// Check the contents of the string.
StringRef Feature =
cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
<< Arg->getSourceRange();
return false;
}
bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
unsigned i = 0, l = 0, u = 0;
switch (BuiltinID) {
default:
return false;
case X86::BI__builtin_cpu_supports:
return SemaBuiltinCpuSupports(*this, TheCall);
case X86::BI__builtin_ms_va_start:
return SemaBuiltinMSVAStart(TheCall);
case X86::BI_mm_prefetch:
i = 1;
l = 0;
u = 3;
break;
case X86::BI__builtin_ia32_sha1rnds4:
i = 2;
l = 0;
u = 3;
break;
case X86::BI__builtin_ia32_vpermil2pd:
case X86::BI__builtin_ia32_vpermil2pd256:
case X86::BI__builtin_ia32_vpermil2ps:
case X86::BI__builtin_ia32_vpermil2ps256:
i = 3;
l = 0;
u = 3;
break;
case X86::BI__builtin_ia32_cmpb128_mask:
case X86::BI__builtin_ia32_cmpw128_mask:
case X86::BI__builtin_ia32_cmpd128_mask:
case X86::BI__builtin_ia32_cmpq128_mask:
case X86::BI__builtin_ia32_cmpb256_mask:
case X86::BI__builtin_ia32_cmpw256_mask:
case X86::BI__builtin_ia32_cmpd256_mask:
case X86::BI__builtin_ia32_cmpq256_mask:
case X86::BI__builtin_ia32_cmpb512_mask:
case X86::BI__builtin_ia32_cmpw512_mask:
case X86::BI__builtin_ia32_cmpd512_mask:
case X86::BI__builtin_ia32_cmpq512_mask:
case X86::BI__builtin_ia32_ucmpb128_mask:
case X86::BI__builtin_ia32_ucmpw128_mask:
case X86::BI__builtin_ia32_ucmpd128_mask:
case X86::BI__builtin_ia32_ucmpq128_mask:
case X86::BI__builtin_ia32_ucmpb256_mask:
case X86::BI__builtin_ia32_ucmpw256_mask:
case X86::BI__builtin_ia32_ucmpd256_mask:
case X86::BI__builtin_ia32_ucmpq256_mask:
case X86::BI__builtin_ia32_ucmpb512_mask:
case X86::BI__builtin_ia32_ucmpw512_mask:
case X86::BI__builtin_ia32_ucmpd512_mask:
case X86::BI__builtin_ia32_ucmpq512_mask:
i = 2;
l = 0;
u = 7;
break;
case X86::BI__builtin_ia32_roundps:
case X86::BI__builtin_ia32_roundpd:
case X86::BI__builtin_ia32_roundps256:
case X86::BI__builtin_ia32_roundpd256:
i = 1;
l = 0;
u = 15;
break;
case X86::BI__builtin_ia32_roundss:
case X86::BI__builtin_ia32_roundsd:
i = 2;
l = 0;
u = 15;
break;
case X86::BI__builtin_ia32_cmpps:
case X86::BI__builtin_ia32_cmpss:
case X86::BI__builtin_ia32_cmppd:
case X86::BI__builtin_ia32_cmpsd:
case X86::BI__builtin_ia32_cmpps256:
case X86::BI__builtin_ia32_cmppd256:
case X86::BI__builtin_ia32_cmpps512_mask:
case X86::BI__builtin_ia32_cmppd512_mask:
i = 2;
l = 0;
u = 31;
break;
case X86::BI__builtin_ia32_vpcomub:
case X86::BI__builtin_ia32_vpcomuw:
case X86::BI__builtin_ia32_vpcomud:
case X86::BI__builtin_ia32_vpcomuq:
case X86::BI__builtin_ia32_vpcomb:
case X86::BI__builtin_ia32_vpcomw:
case X86::BI__builtin_ia32_vpcomd:
case X86::BI__builtin_ia32_vpcomq:
i = 2;
l = 0;
u = 7;
break;
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u);
}
/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
/// parameter with the FormatAttr's correct format_idx and firstDataArg.
/// Returns true when the format fits the function and the FormatStringInfo has
/// been populated.
bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI) {
FSI->HasVAListArg = Format->getFirstArg() == 0;
FSI->FormatIdx = Format->getFormatIdx() - 1;
FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
// The way the format attribute works in GCC, the implicit this argument
// of member functions is counted. However, it doesn't appear in our own
// lists, so decrement format_idx in that case.
if (IsCXXMember) {
if(FSI->FormatIdx == 0)
return false;
--FSI->FormatIdx;
if (FSI->FirstDataArg != 0)
--FSI->FirstDataArg;
}
return true;
}
/// Checks if a the given expression evaluates to null.
///
/// \brief Returns true if the value evaluates to null.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
// If the expression has non-null type, it doesn't evaluate to null.
if (auto nullability
= Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
if (*nullability == NullabilityKind::NonNull)
return false;
}
// As a special case, transparent unions initialized with zero are
// considered null for the purposes of the nonnull attribute.
if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
if (const CompoundLiteralExpr *CLE =
dyn_cast<CompoundLiteralExpr>(Expr))
if (const InitListExpr *ILE =
dyn_cast<InitListExpr>(CLE->getInitializer()))
Expr = ILE->getInit(0);
}
bool Result;
return (!Expr->isValueDependent() &&
Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
!Result);
}
static void CheckNonNullArgument(Sema &S,
const Expr *ArgExpr,
SourceLocation CallSiteLoc) {
if (CheckNonNullExpr(S, ArgExpr))
S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
}
bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
FormatStringInfo FSI;
if ((GetFormatStringType(Format) == FST_NSString) &&
getFormatStringInfo(Format, false, &FSI)) {
Idx = FSI.FormatIdx;
return true;
}
return false;
}
/// \brief Diagnose use of %s directive in an NSString which is being passed
/// as formatting string to formatting method.
static void
DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
const NamedDecl *FDecl,
Expr **Args,
unsigned NumArgs) {
unsigned Idx = 0;
bool Format = false;
ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Idx = 2;
Format = true;
}
else
for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
if (S.GetFormatNSStringIdx(I, Idx)) {
Format = true;
break;
}
}
if (!Format || NumArgs <= Idx)
return;
const Expr *FormatExpr = Args[Idx];
if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
FormatExpr = CSCE->getSubExpr();
const StringLiteral *FormatString;
if (const ObjCStringLiteral *OSL =
dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
FormatString = OSL->getString();
else
FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
if (!FormatString)
return;
if (S.FormatStringHasSArg(FormatString)) {
S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
<< "%s" << 1 << 1;
S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
<< FDecl->getDeclName();
}
}
/// Determine whether the given type has a non-null nullability annotation.
static bool isNonNullType(ASTContext &ctx, QualType type) {
if (auto nullability = type->getNullability(ctx))
return *nullability == NullabilityKind::NonNull;
return false;
}
static void CheckNonNullArguments(Sema &S,
const NamedDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<const Expr *> Args,
SourceLocation CallSiteLoc) {
assert((FDecl || Proto) && "Need a function declaration or prototype");
// Check the attributes attached to the method/function itself.
llvm::SmallBitVector NonNullArgs;
if (FDecl) {
// Handle the nonnull attribute on the function/method declaration itself.
for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
if (!NonNull->args_size()) {
// Easy case: all pointer arguments are nonnull.
for (const auto *Arg : Args)
if (S.isValidPointerAttrType(Arg->getType()))
CheckNonNullArgument(S, Arg, CallSiteLoc);
return;
}
for (unsigned Val : NonNull->args()) {
if (Val >= Args.size())
continue;
if (NonNullArgs.empty())
NonNullArgs.resize(Args.size());
NonNullArgs.set(Val);
}
}
}
if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
// Handle the nonnull attribute on the parameters of the
// function/method.
ArrayRef<ParmVarDecl*> parms;
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
parms = FD->parameters();
else
parms = cast<ObjCMethodDecl>(FDecl)->parameters();
unsigned ParamIndex = 0;
for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
I != E; ++I, ++ParamIndex) {
const ParmVarDecl *PVD = *I;
if (PVD->hasAttr<NonNullAttr>() ||
isNonNullType(S.Context, PVD->getType())) {
if (NonNullArgs.empty())
NonNullArgs.resize(Args.size());
NonNullArgs.set(ParamIndex);
}
}
} else {
// If we have a non-function, non-method declaration but no
// function prototype, try to dig out the function prototype.
if (!Proto) {
if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
QualType type = VD->getType().getNonReferenceType();
if (auto pointerType = type->getAs<PointerType>())
type = pointerType->getPointeeType();
else if (auto blockType = type->getAs<BlockPointerType>())
type = blockType->getPointeeType();
// FIXME: data member pointers?
// Dig out the function prototype, if there is one.
Proto = type->getAs<FunctionProtoType>();
}
}
// Fill in non-null argument information from the nullability
// information on the parameter types (if we have them).
if (Proto) {
unsigned Index = 0;
for (auto paramType : Proto->getParamTypes()) {
if (isNonNullType(S.Context, paramType)) {
if (NonNullArgs.empty())
NonNullArgs.resize(Args.size());
NonNullArgs.set(Index);
}
++Index;
}
}
}
// Check for non-null arguments.
for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
ArgIndex != ArgIndexEnd; ++ArgIndex) {
if (NonNullArgs[ArgIndex])
CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
}
}
/// Handles the checks for format strings, non-POD arguments to vararg
/// functions, and NULL arguments passed to non-NULL parameters.
void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
ArrayRef<const Expr *> Args, bool IsMemberFunction,
SourceLocation Loc, SourceRange Range,
VariadicCallType CallType) {
// FIXME: We should check as much as we can in the template definition.
if (CurContext->isDependentContext())
return;
// Printf and scanf checking.
llvm::SmallBitVector CheckedVarArgs;
if (FDecl) {
for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
// Only create vector if there are format attributes.
CheckedVarArgs.resize(Args.size());
CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
CheckedVarArgs);
}
}
// Refuse POD arguments that weren't caught by the format string
// checks above.
if (CallType != VariadicDoesNotApply) {
unsigned NumParams = Proto ? Proto->getNumParams()
: FDecl && isa<FunctionDecl>(FDecl)
? cast<FunctionDecl>(FDecl)->getNumParams()
: FDecl && isa<ObjCMethodDecl>(FDecl)
? cast<ObjCMethodDecl>(FDecl)->param_size()
: 0;
for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
// Args[ArgIdx] can be null in malformed code.
if (const Expr *Arg = Args[ArgIdx]) {
if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
checkVariadicArgument(Arg, CallType);
}
}
}
if (FDecl || Proto) {
CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
// Type safety checking.
if (FDecl) {
for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
CheckArgumentWithTypeTag(I, Args.data());
}
}
}
/// CheckConstructorCall - Check a constructor call for correctness and safety
/// properties not enforced by the C type system.
void Sema::CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc) {
VariadicCallType CallType =
Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
CallType);
}
/// CheckFunctionCall - Check a direct function call for various correctness
/// and safety properties not strictly enforced by the C type system.
bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto) {
bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
isa<CXXMethodDecl>(FDecl);
bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
IsMemberOperatorCall;
VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
TheCall->getCallee());
Expr** Args = TheCall->getArgs();
unsigned NumArgs = TheCall->getNumArgs();
if (IsMemberOperatorCall) {
// If this is a call to a member operator, hide the first argument
// from checkCall.
// FIXME: Our choice of AST representation here is less than ideal.
++Args;
--NumArgs;
}
checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
IsMemberFunction, TheCall->getRParenLoc(),
TheCall->getCallee()->getSourceRange(), CallType);
IdentifierInfo *FnInfo = FDecl->getIdentifier();
// None of the checks below are needed for functions that don't have
// simple names (e.g., C++ conversion functions).
if (!FnInfo)
return false;
CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
if (getLangOpts().ObjC1)
DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
unsigned CMId = FDecl->getMemoryFunctionKind();
if (CMId == 0)
return false;
// Handle memory setting and copying functions.
if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
CheckStrlcpycatArguments(TheCall, FnInfo);
else if (CMId == Builtin::BIstrncat)
CheckStrncatArguments(TheCall, FnInfo);
else
CheckMemaccessArguments(TheCall, CMId, FnInfo);
return false;
}
bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
ArrayRef<const Expr *> Args) {
VariadicCallType CallType =
Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
checkCall(Method, nullptr, Args,
/*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
CallType);
return false;
}
bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto) {
QualType Ty;
if (const auto *V = dyn_cast<VarDecl>(NDecl))
Ty = V->getType().getNonReferenceType();
else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Ty = F->getType().getNonReferenceType();
else
return false;
if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
!Ty->isFunctionProtoType())
return false;
VariadicCallType CallType;
if (!Proto || !Proto->isVariadic()) {
CallType = VariadicDoesNotApply;
} else if (Ty->isBlockPointerType()) {
CallType = VariadicBlock;
} else { // Ty->isFunctionPointerType()
CallType = VariadicFunction;
}
checkCall(NDecl, Proto,
llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
/*IsMemberFunction=*/false, TheCall->getRParenLoc(),
TheCall->getCallee()->getSourceRange(), CallType);
return false;
}
/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
/// such as function pointers returned from functions.
bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
TheCall->getCallee());
checkCall(/*FDecl=*/nullptr, Proto,
llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
/*IsMemberFunction=*/false, TheCall->getRParenLoc(),
TheCall->getCallee()->getSourceRange(), CallType);
return false;
}
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
if (!llvm::isValidAtomicOrderingCABI(Ordering))
return false;
auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
switch (Op) {
case AtomicExpr::AO__c11_atomic_init:
llvm_unreachable("There is no ordering argument for an init");
case AtomicExpr::AO__c11_atomic_load:
case AtomicExpr::AO__atomic_load_n:
case AtomicExpr::AO__atomic_load:
return OrderingCABI != llvm::AtomicOrderingCABI::release &&
OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
case AtomicExpr::AO__c11_atomic_store:
case AtomicExpr::AO__atomic_store:
case AtomicExpr::AO__atomic_store_n:
return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
default:
return true;
}
}
ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op) {
CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
// All these operations take one of the following forms:
enum {
// C __c11_atomic_init(A *, C)
Init,
// C __c11_atomic_load(A *, int)
Load,
// void __atomic_load(A *, CP, int)
LoadCopy,
// void __atomic_store(A *, CP, int)
Copy,
// C __c11_atomic_add(A *, M, int)
Arithmetic,
// C __atomic_exchange_n(A *, CP, int)
Xchg,
// void __atomic_exchange(A *, C *, CP, int)
GNUXchg,
// bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
C11CmpXchg,
// bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
GNUCmpXchg
} Form = Init;
const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
// where:
// C is an appropriate type,
// A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
// CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
// M is C if C is an integer, and ptrdiff_t if C is a pointer, and
// the int parameters are for orderings.
static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
AtomicExpr::AO__atomic_load,
"need to update code for modified C11 atomics");
bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
Op == AtomicExpr::AO__atomic_store_n ||
Op == AtomicExpr::AO__atomic_exchange_n ||
Op == AtomicExpr::AO__atomic_compare_exchange_n;
bool IsAddSub = false;
switch (Op) {
case AtomicExpr::AO__c11_atomic_init:
Form = Init;
break;
case AtomicExpr::AO__c11_atomic_load:
case AtomicExpr::AO__atomic_load_n:
Form = Load;
break;
case AtomicExpr::AO__atomic_load:
Form = LoadCopy;
break;
case AtomicExpr::AO__c11_atomic_store:
case AtomicExpr::AO__atomic_store:
case AtomicExpr::AO__atomic_store_n:
Form = Copy;
break;
case AtomicExpr::AO__c11_atomic_fetch_add:
case AtomicExpr::AO__c11_atomic_fetch_sub:
case AtomicExpr::AO__atomic_fetch_add:
case AtomicExpr::AO__atomic_fetch_sub:
case AtomicExpr::AO__atomic_add_fetch:
case AtomicExpr::AO__atomic_sub_fetch:
IsAddSub = true;
// Fall through.
case AtomicExpr::AO__c11_atomic_fetch_and:
case AtomicExpr::AO__c11_atomic_fetch_or:
case AtomicExpr::AO__c11_atomic_fetch_xor:
case AtomicExpr::AO__atomic_fetch_and:
case AtomicExpr::AO__atomic_fetch_or:
case AtomicExpr::AO__atomic_fetch_xor:
case AtomicExpr::AO__atomic_fetch_nand:
case AtomicExpr::AO__atomic_and_fetch:
case AtomicExpr::AO__atomic_or_fetch:
case AtomicExpr::AO__atomic_xor_fetch:
case AtomicExpr::AO__atomic_nand_fetch:
Form = Arithmetic;
break;
case AtomicExpr::AO__c11_atomic_exchange:
case AtomicExpr::AO__atomic_exchange_n:
Form = Xchg;
break;
case AtomicExpr::AO__atomic_exchange:
Form = GNUXchg;
break;
case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Form = C11CmpXchg;
break;
case AtomicExpr::AO__atomic_compare_exchange:
case AtomicExpr::AO__atomic_compare_exchange_n:
Form = GNUCmpXchg;
break;
}
// Check we have the right number of arguments.
if (TheCall->getNumArgs() < NumArgs[Form]) {
Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
<< 0 << NumArgs[Form] << TheCall->getNumArgs()
<< TheCall->getCallee()->getSourceRange();
return ExprError();
} else if (TheCall->getNumArgs() > NumArgs[Form]) {
Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
diag::err_typecheck_call_too_many_args)
<< 0 << NumArgs[Form] << TheCall->getNumArgs()
<< TheCall->getCallee()->getSourceRange();
return ExprError();
}
// Inspect the first argument of the atomic operation.
Expr *Ptr = TheCall->getArg(0);
Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
if (!pointerType) {
Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
<< Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
// For a __c11 builtin, this should be a pointer to an _Atomic type.
QualType AtomTy = pointerType->getPointeeType(); // 'A'
QualType ValType = AtomTy; // 'C'
if (IsC11) {
if (!AtomTy->isAtomicType()) {
Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
<< Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if (AtomTy.isConstQualified()) {
Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
<< Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
ValType = AtomTy->getAs<AtomicType>()->getValueType();
} else if (Form != Load && Form != LoadCopy) {
if (ValType.isConstQualified()) {
Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
<< Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
}
// For an arithmetic operation, the implied arithmetic must be well-formed.
if (Form == Arithmetic) {
// gcc does not enforce these rules for GNU atomics, but we do so for sanity.
if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
<< IsC11 << Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if (!IsAddSub && !ValType->isIntegerType()) {
Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
<< IsC11 << Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if (IsC11 && ValType->isPointerType() &&
RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
diag::err_incomplete_type)) {
return ExprError();
}
} else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
// For __atomic_*_n operations, the value type must be a scalar integral or
// pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
<< IsC11 << Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
!AtomTy->isScalarType()) {
// For GNU atomics, require a trivially-copyable type. This is not part of
// the GNU atomics specification, but we enforce it for sanity.
Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
<< Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
switch (ValType.getObjCLifetime()) {
case Qualifiers::OCL_None:
case Qualifiers::OCL_ExplicitNone:
// okay
break;
case Qualifiers::OCL_Weak:
case Qualifiers::OCL_Strong:
case Qualifiers::OCL_Autoreleasing:
// FIXME: Can this happen? By this point, ValType should be known
// to be trivially copyable.
Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
<< ValType << Ptr->getSourceRange();
return ExprError();
}
// atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
// volatile-ness of the pointee-type inject itself into the result or the
// other operands. Similarly atomic_load can take a pointer to a const 'A'.
ValType.removeLocalVolatile();
ValType.removeLocalConst();
QualType ResultType = ValType;
if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
ResultType = Context.VoidTy;
else if (Form == C11CmpXchg || Form == GNUCmpXchg)
ResultType = Context.BoolTy;
// The type of a parameter passed 'by value'. In the GNU atomics, such
// arguments are actually passed as pointers.
QualType ByValType = ValType; // 'CP'
if (!IsC11 && !IsN)
ByValType = Ptr->getType();
// The first argument --- the pointer --- has a fixed type; we
// deduce the types of the rest of the arguments accordingly. Walk
// the remaining arguments, converting them to the deduced value type.
for (unsigned i = 1; i != NumArgs[Form]; ++i) {
QualType Ty;
if (i < NumVals[Form] + 1) {
switch (i) {
case 1:
// The second argument is the non-atomic operand. For arithmetic, this
// is always passed by value, and for a compare_exchange it is always
// passed by address. For the rest, GNU uses by-address and C11 uses
// by-value.
assert(Form != Load);
if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
Ty = ValType;
else if (Form == Copy || Form == Xchg)
Ty = ByValType;
else if (Form == Arithmetic)
Ty = Context.getPointerDiffType();
else {
Expr *ValArg = TheCall->getArg(i);
unsigned AS = 0;
// Keep address space of non-atomic pointer type.
if (const PointerType *PtrTy =
ValArg->getType()->getAs<PointerType>()) {
AS = PtrTy->getPointeeType().getAddressSpace();
}
Ty = Context.getPointerType(
Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
}
break;
case 2:
// The third argument to compare_exchange / GNU exchange is a
// (pointer to a) desired value.
Ty = ByValType;
break;
case 3:
// The fourth argument to GNU compare_exchange is a 'weak' flag.
Ty = Context.BoolTy;
break;
}
} else {
// The order(s) are always converted to int.
Ty = Context.IntTy;
}
InitializedEntity Entity =
InitializedEntity::InitializeParameter(Context, Ty, false);
ExprResult Arg = TheCall->getArg(i);
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (Arg.isInvalid())
return true;
TheCall->setArg(i, Arg.get());
}
// Permute the arguments into a 'consistent' order.
SmallVector<Expr*, 5> SubExprs;
SubExprs.push_back(Ptr);
switch (Form) {
case Init:
// Note, AtomicExpr::getVal1() has a special case for this atomic.
SubExprs.push_back(TheCall->getArg(1)); // Val1
break;
case Load:
SubExprs.push_back(TheCall->getArg(1)); // Order
break;
case LoadCopy:
case Copy:
case Arithmetic:
case Xchg:
SubExprs.push_back(TheCall->getArg(2)); // Order
SubExprs.push_back(TheCall->getArg(1)); // Val1
break;
case GNUXchg:
// Note, AtomicExpr::getVal2() has a special case for this atomic.
SubExprs.push_back(TheCall->getArg(3)); // Order
SubExprs.push_back(TheCall->getArg(1)); // Val1
SubExprs.push_back(TheCall->getArg(2)); // Val2
break;
case C11CmpXchg:
SubExprs.push_back(TheCall->getArg(3)); // Order
SubExprs.push_back(TheCall->getArg(1)); // Val1
SubExprs.push_back(TheCall->getArg(4)); // OrderFail
SubExprs.push_back(TheCall->getArg(2)); // Val2
break;
case GNUCmpXchg:
SubExprs.push_back(TheCall->getArg(4)); // Order
SubExprs.push_back(TheCall->getArg(1)); // Val1
SubExprs.push_back(TheCall->getArg(5)); // OrderFail
SubExprs.push_back(TheCall->getArg(2)); // Val2
SubExprs.push_back(TheCall->getArg(3)); // Weak
break;
}
if (SubExprs.size() >= 2 && Form != Init) {
llvm::APSInt Result(32);
if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
!isValidOrderingForOp(Result.getSExtValue(), Op))
Diag(SubExprs[1]->getLocStart(),
diag::warn_atomic_op_has_invalid_memory_order)
<< SubExprs[1]->getSourceRange();
}
AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
SubExprs, ResultType, Op,
TheCall->getRParenLoc());
if ((Op == AtomicExpr::AO__c11_atomic_load ||
(Op == AtomicExpr::AO__c11_atomic_store)) &&
Context.AtomicUsesUnsupportedLibcall(AE))
Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
return AE;
}
/// checkBuiltinArgument - Given a call to a builtin function, perform
/// normal type-checking on the given argument, updating the call in
/// place. This is useful when a builtin function requires custom
/// type-checking for some of its arguments but not necessarily all of
/// them.
///
/// Returns true on error.
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
FunctionDecl *Fn = E->getDirectCallee();
assert(Fn && "builtin call without direct callee!");
ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
InitializedEntity Entity =
InitializedEntity::InitializeParameter(S.Context, Param);
ExprResult Arg = E->getArg(0);
Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (Arg.isInvalid())
return true;
E->setArg(ArgIndex, Arg.get());
return false;
}
/// SemaBuiltinAtomicOverloaded - We have a call to a function like
/// __sync_fetch_and_add, which is an overloaded function based on the pointer
/// type of its first argument. The main ActOnCallExpr routines have already
/// promoted the types of arguments because all of these calls are prototyped as
/// void(...).
///
/// This function goes through and does final semantic checking for these
/// builtins,
ExprResult
Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
CallExpr *TheCall = (CallExpr *)TheCallResult.get();
DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
// Ensure that we have at least one argument to do type inference from.
if (TheCall->getNumArgs() < 1) {
Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
<< 0 << 1 << TheCall->getNumArgs()
<< TheCall->getCallee()->getSourceRange();
return ExprError();
}
// Inspect the first argument of the atomic builtin. This should always be
// a pointer type, whose element is an integral scalar or pointer type.
// Because it is a pointer type, we don't have to worry about any implicit
// casts here.
// FIXME: We don't allow floating point scalars as input.
Expr *FirstArg = TheCall->getArg(0);
ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
if (FirstArgResult.isInvalid())
return ExprError();
FirstArg = FirstArgResult.get();
TheCall->setArg(0, FirstArg);
const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
if (!pointerType) {
Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
<< FirstArg->getType() << FirstArg->getSourceRange();
return ExprError();
}
QualType ValType = pointerType->getPointeeType();
if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
!ValType->isBlockPointerType()) {
Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
<< FirstArg->getType() << FirstArg->getSourceRange();
return ExprError();
}
switch (ValType.getObjCLifetime()) {
case Qualifiers::OCL_None:
case Qualifiers::OCL_ExplicitNone:
// okay
break;
case Qualifiers::OCL_Weak:
case Qualifiers::OCL_Strong:
case Qualifiers::OCL_Autoreleasing:
Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
<< ValType << FirstArg->getSourceRange();
return ExprError();
}
// Strip any qualifiers off ValType.
ValType = ValType.getUnqualifiedType();
// The majority of builtins return a value, but a few have special return
// types, so allow them to override appropriately below.
QualType ResultType = ValType;
// We need to figure out which concrete builtin this maps onto. For example,
// __sync_fetch_and_add with a 2 byte object turns into
// __sync_fetch_and_add_2.
#define BUILTIN_ROW(x) \
{ Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
Builtin::BI##x##_8, Builtin::BI##x##_16 }
static const unsigned BuiltinIndices[][5] = {
BUILTIN_ROW(__sync_fetch_and_add),
BUILTIN_ROW(__sync_fetch_and_sub),
BUILTIN_ROW(__sync_fetch_and_or),
BUILTIN_ROW(__sync_fetch_and_and),
BUILTIN_ROW(__sync_fetch_and_xor),
BUILTIN_ROW(__sync_fetch_and_nand),
BUILTIN_ROW(__sync_add_and_fetch),
BUILTIN_ROW(__sync_sub_and_fetch),
BUILTIN_ROW(__sync_and_and_fetch),
BUILTIN_ROW(__sync_or_and_fetch),
BUILTIN_ROW(__sync_xor_and_fetch),
BUILTIN_ROW(__sync_nand_and_fetch),
BUILTIN_ROW(__sync_val_compare_and_swap),
BUILTIN_ROW(__sync_bool_compare_and_swap),
BUILTIN_ROW(__sync_lock_test_and_set),
BUILTIN_ROW(__sync_lock_release),
BUILTIN_ROW(__sync_swap)
};
#undef BUILTIN_ROW
// Determine the index of the size.
unsigned SizeIndex;
switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
case 1: SizeIndex = 0; break;
case 2: SizeIndex = 1; break;
case 4: SizeIndex = 2; break;
case 8: SizeIndex = 3; break;
case 16: SizeIndex = 4; break;
default:
Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
<< FirstArg->getType() << FirstArg->getSourceRange();
return ExprError();
}
// Each of these builtins has one pointer argument, followed by some number of
// values (0, 1 or 2) followed by a potentially empty varags list of stuff
// that we ignore. Find out which row of BuiltinIndices to read from as well
// as the number of fixed args.
unsigned BuiltinID = FDecl->getBuiltinID();
unsigned BuiltinIndex, NumFixed = 1;
bool WarnAboutSemanticsChange = false;
switch (BuiltinID) {
default: llvm_unreachable("Unknown overloaded atomic builtin!");
case Builtin::BI__sync_fetch_and_add:
case Builtin::BI__sync_fetch_and_add_1:
case Builtin::BI__sync_fetch_and_add_2:
case Builtin::BI__sync_fetch_and_add_4:
case Builtin::BI__sync_fetch_and_add_8:
case Builtin::BI__sync_fetch_and_add_16:
BuiltinIndex = 0;
break;
case Builtin::BI__sync_fetch_and_sub:
case Builtin::BI__sync_fetch_and_sub_1:
case Builtin::BI__sync_fetch_and_sub_2:
case Builtin::BI__sync_fetch_and_sub_4:
case Builtin::BI__sync_fetch_and_sub_8:
case Builtin::BI__sync_fetch_and_sub_16:
BuiltinIndex = 1;
break;
case Builtin::BI__sync_fetch_and_or:
case Builtin::BI__sync_fetch_and_or_1:
case Builtin::BI__sync_fetch_and_or_2:
case Builtin::BI__sync_fetch_and_or_4:
case Builtin::BI__sync_fetch_and_or_8:
case Builtin::BI__sync_fetch_and_or_16:
BuiltinIndex = 2;
break;
case Builtin::BI__sync_fetch_and_and:
case Builtin::BI__sync_fetch_and_and_1:
case Builtin::BI__sync_fetch_and_and_2:
case Builtin::BI__sync_fetch_and_and_4:
case Builtin::BI__sync_fetch_and_and_8:
case Builtin::BI__sync_fetch_and_and_16:
BuiltinIndex = 3;
break;
case Builtin::BI__sync_fetch_and_xor:
case Builtin::BI__sync_fetch_and_xor_1:
case Builtin::BI__sync_fetch_and_xor_2:
case Builtin::BI__sync_fetch_and_xor_4:
case Builtin::BI__sync_fetch_and_xor_8:
case Builtin::BI__sync_fetch_and_xor_16:
BuiltinIndex = 4;
break;
case Builtin::BI__sync_fetch_and_nand:
case Builtin::BI__sync_fetch_and_nand_1:
case Builtin::BI__sync_fetch_and_nand_2:
case Builtin::BI__sync_fetch_and_nand_4:
case Builtin::BI__sync_fetch_and_nand_8:
case Builtin::BI__sync_fetch_and_nand_16:
BuiltinIndex = 5;
WarnAboutSemanticsChange = true;
break;
case Builtin::BI__sync_add_and_fetch:
case Builtin::BI__sync_add_and_fetch_1:
case Builtin::BI__sync_add_and_fetch_2:
case Builtin::BI__sync_add_and_fetch_4:
case Builtin::BI__sync_add_and_fetch_8:
case Builtin::BI__sync_add_and_fetch_16:
BuiltinIndex = 6;
break;
case Builtin::BI__sync_sub_and_fetch:
case Builtin::BI__sync_sub_and_fetch_1:
case Builtin::BI__sync_sub_and_fetch_2:
case Builtin::BI__sync_sub_and_fetch_4:
case Builtin::BI__sync_sub_and_fetch_8:
case Builtin::BI__sync_sub_and_fetch_16:
BuiltinIndex = 7;
break;
case Builtin::BI__sync_and_and_fetch:
case Builtin::BI__sync_and_and_fetch_1:
case Builtin::BI__sync_and_and_fetch_2:
case Builtin::BI__sync_and_and_fetch_4:
case Builtin::BI__sync_and_and_fetch_8:
case Builtin::BI__sync_and_and_fetch_16:
BuiltinIndex = 8;
break;
case Builtin::BI__sync_or_and_fetch:
case Builtin::BI__sync_or_and_fetch_1:
case Builtin::BI__sync_or_and_fetch_2:
case Builtin::BI__sync_or_and_fetch_4:
case Builtin::BI__sync_or_and_fetch_8:
case Builtin::BI__sync_or_and_fetch_16:
BuiltinIndex = 9;
break;
case Builtin::BI__sync_xor_and_fetch:
case Builtin::BI__sync_xor_and_fetch_1:
case Builtin::BI__sync_xor_and_fetch_2:
case Builtin::BI__sync_xor_and_fetch_4:
case Builtin::BI__sync_xor_and_fetch_8:
case Builtin::BI__sync_xor_and_fetch_16:
BuiltinIndex = 10;
break;
case Builtin::BI__sync_nand_and_fetch:
case Builtin::BI__sync_nand_and_fetch_1:
case Builtin::BI__sync_nand_and_fetch_2:
case Builtin::BI__sync_nand_and_fetch_4:
case Builtin::BI__sync_nand_and_fetch_8:
case Builtin::BI__sync_nand_and_fetch_16:
BuiltinIndex = 11;
WarnAboutSemanticsChange = true;
break;
case Builtin::BI__sync_val_compare_and_swap:
case Builtin::BI__sync_val_compare_and_swap_1:
case Builtin::BI__sync_val_compare_and_swap_2:
case Builtin::BI__sync_val_compare_and_swap_4:
case Builtin::BI__sync_val_compare_and_swap_8:
case Builtin::BI__sync_val_compare_and_swap_16:
BuiltinIndex = 12;
NumFixed = 2;
break;
case Builtin::BI__sync_bool_compare_and_swap:
case Builtin::BI__sync_bool_compare_and_swap_1:
case Builtin::BI__sync_bool_compare_and_swap_2:
case Builtin::BI__sync_bool_compare_and_swap_4:
case Builtin::BI__sync_bool_compare_and_swap_8:
case Builtin::BI__sync_bool_compare_and_swap_16:
BuiltinIndex = 13;
NumFixed = 2;
ResultType = Context.BoolTy;
break;
case Builtin::BI__sync_lock_test_and_set:
case Builtin::BI__sync_lock_test_and_set_1:
case Builtin::BI__sync_lock_test_and_set_2:
case Builtin::BI__sync_lock_test_and_set_4:
case Builtin::BI__sync_lock_test_and_set_8:
case Builtin::BI__sync_lock_test_and_set_16:
BuiltinIndex = 14;
break;
case Builtin::BI__sync_lock_release:
case Builtin::BI__sync_lock_release_1:
case Builtin::BI__sync_lock_release_2:
case Builtin::BI__sync_lock_release_4:
case Builtin::BI__sync_lock_release_8:
case Builtin::BI__sync_lock_release_16:
BuiltinIndex = 15;
NumFixed = 0;
ResultType = Context.VoidTy;
break;
case Builtin::BI__sync_swap:
case Builtin::BI__sync_swap_1:
case Builtin::BI__sync_swap_2:
case Builtin::BI__sync_swap_4:
case Builtin::BI__sync_swap_8:
case Builtin::BI__sync_swap_16:
BuiltinIndex = 16;
break;
}
// Now that we know how many fixed arguments we expect, first check that we
// have at least that many.
if (TheCall->getNumArgs() < 1+NumFixed) {
Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
<< 0 << 1+NumFixed << TheCall->getNumArgs()
<< TheCall->getCallee()->getSourceRange();
return ExprError();
}
if (WarnAboutSemanticsChange) {
Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
<< TheCall->getCallee()->getSourceRange();
}
// Get the decl for the concrete builtin from this, we can tell what the
// concrete integer type we should convert to is.
unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
FunctionDecl *NewBuiltinDecl;
if (NewBuiltinID == BuiltinID)
NewBuiltinDecl = FDecl;
else {
// Perform builtin lookup to avoid redeclaring it.
DeclarationName DN(&Context.Idents.get(NewBuiltinName));
LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
assert(Res.getFoundDecl());
NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
if (!NewBuiltinDecl)
return ExprError();
}
// The first argument --- the pointer --- has a fixed type; we
// deduce the types of the rest of the arguments accordingly. Walk
// the remaining arguments, converting them to the deduced value type.
for (unsigned i = 0; i != NumFixed; ++i) {
ExprResult Arg = TheCall->getArg(i+1);
// GCC does an implicit conversion to the pointer or integer ValType. This
// can fail in some cases (1i -> int**), check for this error case now.
// Initialize the argument.
InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
ValType, /*consume*/ false);
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (Arg.isInvalid())
return ExprError();
// Okay, we have something that *can* be converted to the right type. Check
// to see if there is a potentially weird extension going on here. This can
// happen when you do an atomic operation on something like an char* and
// pass in 42. The 42 gets converted to char. This is even more strange
// for things like 45.123 -> char, etc.
// FIXME: Do this check.
TheCall->setArg(i+1, Arg.get());
}
ASTContext& Context = this->getASTContext();
// Create a new DeclRefExpr to refer to the new decl.
DeclRefExpr* NewDRE = DeclRefExpr::Create(
Context,
DRE->getQualifierLoc(),
SourceLocation(),
NewBuiltinDecl,
/*enclosing*/ false,
DRE->getLocation(),
Context.BuiltinFnTy,
DRE->getValueKind());
// Set the callee in the CallExpr.
// FIXME: This loses syntactic information.
QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
CK_BuiltinFnToFnPtr);
TheCall->setCallee(PromotedCall.get());
// Change the result type of the call to match the original value type. This
// is arbitrary, but the codegen for these builtins ins design to handle it
// gracefully.
TheCall->setType(ResultType);
return TheCallResult;
}
/// SemaBuiltinNontemporalOverloaded - We have a call to
/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
/// overloaded function based on the pointer type of its last argument.
///
/// This function goes through and does final semantic checking for these
/// builtins.
ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
CallExpr *TheCall = (CallExpr *)TheCallResult.get();
DeclRefExpr *DRE =
cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
unsigned BuiltinID = FDecl->getBuiltinID();
assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
"Unexpected nontemporal load/store builtin!");
bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
unsigned numArgs = isStore ? 2 : 1;
// Ensure that we have the proper number of arguments.
if (checkArgCount(*this, TheCall, numArgs))
return ExprError();
// Inspect the last argument of the nontemporal builtin. This should always
// be a pointer type, from which we imply the type of the memory access.
// Because it is a pointer type, we don't have to worry about any implicit
// casts here.
Expr *PointerArg = TheCall->getArg(numArgs - 1);
ExprResult PointerArgResult =
DefaultFunctionArrayLvalueConversion(PointerArg);
if (PointerArgResult.isInvalid())
return ExprError();
PointerArg = PointerArgResult.get();
TheCall->setArg(numArgs - 1, PointerArg);
const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
if (!pointerType) {
Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
<< PointerArg->getType() << PointerArg->getSourceRange();
return ExprError();
}
QualType ValType = pointerType->getPointeeType();
// Strip any qualifiers off ValType.
ValType = ValType.getUnqualifiedType();
if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
!ValType->isBlockPointerType() && !ValType->isFloatingType() &&
!ValType->isVectorType()) {
Diag(DRE->getLocStart(),
diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
<< PointerArg->getType() << PointerArg->getSourceRange();
return ExprError();
}
if (!isStore) {
TheCall->setType(ValType);
return TheCallResult;
}
ExprResult ValArg = TheCall->getArg(0);
InitializedEntity Entity = InitializedEntity::InitializeParameter(
Context, ValType, /*consume*/ false);
ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
if (ValArg.isInvalid())
return ExprError();
TheCall->setArg(0, ValArg.get());
TheCall->setType(Context.VoidTy);
return TheCallResult;
}
/// CheckObjCString - Checks that the argument to the builtin
/// CFString constructor is correct
/// Note: It might also make sense to do the UTF-16 conversion here (would
/// simplify the backend).
bool Sema::CheckObjCString(Expr *Arg) {
Arg = Arg->IgnoreParenCasts();
StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
if (!Literal || !Literal->isAscii()) {
Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
<< Arg->getSourceRange();
return true;
}
if (Literal->containsNonAsciiOrNull()) {
StringRef String = Literal->getString();
unsigned NumBytes = String.size();
SmallVector<UTF16, 128> ToBuf(NumBytes);
const UTF8 *FromPtr = (const UTF8 *)String.data();
UTF16 *ToPtr = &ToBuf[0];
ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
&ToPtr, ToPtr + NumBytes,
strictConversion);
// Check for conversion failure.
if (Result != conversionOK)
Diag(Arg->getLocStart(),
diag::warn_cfstring_truncated) << Arg->getSourceRange();
}
return false;
}
/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
/// for validity. Emit an error and return true on failure; return false
/// on success.
bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Expr *Fn = TheCall->getCallee();
if (TheCall->getNumArgs() > 2) {
Diag(TheCall->getArg(2)->getLocStart(),
diag::err_typecheck_call_too_many_args)
<< 0 /*function call*/ << 2 << TheCall->getNumArgs()
<< Fn->getSourceRange()
<< SourceRange(TheCall->getArg(2)->getLocStart(),
(*(TheCall->arg_end()-1))->getLocEnd());
return true;
}
if (TheCall->getNumArgs() < 2) {
return Diag(TheCall->getLocEnd(),
diag::err_typecheck_call_too_few_args_at_least)
<< 0 /*function call*/ << 2 << TheCall->getNumArgs();
}
// Type-check the first argument normally.
if (checkBuiltinArgument(*this, TheCall, 0))
return true;
// Determine whether the current function is variadic or not.
BlockScopeInfo *CurBlock = getCurBlock();
bool isVariadic;
if (CurBlock)
isVariadic = CurBlock->TheDecl->isVariadic();
else if (FunctionDecl *FD = getCurFunctionDecl())
isVariadic = FD->isVariadic();
else
isVariadic = getCurMethodDecl()->isVariadic();
if (!isVariadic) {
Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
return true;
}
// Verify that the second argument to the builtin is the last argument of the
// current function or method.
bool SecondArgIsLastNamedArgument = false;
const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
// These are valid if SecondArgIsLastNamedArgument is false after the next
// block.
QualType Type;
SourceLocation ParamLoc;
bool IsCRegister = false;
if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
// FIXME: This isn't correct for methods (results in bogus warning).
// Get the last formal in the current function.
const ParmVarDecl *LastArg;
if (CurBlock)
LastArg = *(CurBlock->TheDecl->param_end()-1);
else if (FunctionDecl *FD = getCurFunctionDecl())
LastArg = *(FD->param_end()-1);
else
LastArg = *(getCurMethodDecl()->param_end()-1);
SecondArgIsLastNamedArgument = PV == LastArg;
Type = PV->getType();
ParamLoc = PV->getLocation();
IsCRegister =
PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
}
}
if (!SecondArgIsLastNamedArgument)
Diag(TheCall->getArg(1)->getLocStart(),
diag::warn_second_arg_of_va_start_not_last_named_param);
else if (IsCRegister || Type->isReferenceType() ||
Type->isPromotableIntegerType() ||
Type->isSpecificBuiltinType(BuiltinType::Float)) {
unsigned Reason = 0;
if (Type->isReferenceType()) Reason = 1;
else if (IsCRegister) Reason = 2;
Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Diag(ParamLoc, diag::note_parameter_type) << Type;
}
TheCall->setType(Context.VoidTy);
return false;
}
/// Check the arguments to '__builtin_va_start' for validity, and that
/// it was called from a function of the native ABI.
/// Emit an error and return true on failure; return false on success.
bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
// On x86-64 Unix, don't allow this in Win64 ABI functions.
// On x64 Windows, don't allow this in System V ABI functions.
// (Yes, that means there's no corresponding way to support variadic
// System V ABI functions on Windows.)
if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
unsigned OS = Context.getTargetInfo().getTriple().getOS();
clang::CallingConv CC = CC_C;
if (const FunctionDecl *FD = getCurFunctionDecl())
CC = FD->getType()->getAs<FunctionType>()->getCallConv();
if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
(OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
return Diag(TheCall->getCallee()->getLocStart(),
diag::err_va_start_used_in_wrong_abi_function)
<< (OS != llvm::Triple::Win32);
}
return SemaBuiltinVAStartImpl(TheCall);
}
/// Check the arguments to '__builtin_ms_va_start' for validity, and that
/// it was called from a Win64 ABI function.
/// Emit an error and return true on failure; return false on success.
bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
// This only makes sense for x86-64.
const llvm::Triple &TT = Context.getTargetInfo().getTriple();
Expr *Callee = TheCall->getCallee();
if (TT.getArch() != llvm::Triple::x86_64)
return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
// Don't allow this in System V ABI functions.
clang::CallingConv CC = CC_C;
if (const FunctionDecl *FD = getCurFunctionDecl())
CC = FD->getType()->getAs<FunctionType>()->getCallConv();
if (CC == CC_X86_64SysV ||
(TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
return Diag(Callee->getLocStart(),
diag::err_ms_va_start_used_in_sysv_function);
return SemaBuiltinVAStartImpl(TheCall);
}
bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
// void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
// const char *named_addr);
Expr *Func = Call->getCallee();
if (Call->getNumArgs() < 3)
return Diag(Call->getLocEnd(),
diag::err_typecheck_call_too_few_args_at_least)
<< 0 /*function call*/ << 3 << Call->getNumArgs();
// Determine whether the current function is variadic or not.
bool IsVariadic;
if (BlockScopeInfo *CurBlock = getCurBlock())
IsVariadic = CurBlock->TheDecl->isVariadic();
else if (FunctionDecl *FD = getCurFunctionDecl())
IsVariadic = FD->isVariadic();
else if (ObjCMethodDecl *MD = getCurMethodDecl())
IsVariadic = MD->isVariadic();
else
llvm_unreachable("unexpected statement type");
if (!IsVariadic) {
Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
return true;
}
// Type-check the first argument normally.
if (checkBuiltinArgument(*this, Call, 0))
return true;
const struct {
unsigned ArgNo;
QualType Type;
} ArgumentTypes[] = {
{ 1, Context.getPointerType(Context.CharTy.withConst()) },
{ 2, Context.getSizeType() },
};
for (const auto &AT : ArgumentTypes) {
const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
continue;
Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
<< Arg->getType() << AT.Type << 1 /* different class */
<< 0 /* qualifier difference */ << 3 /* parameter mismatch */
<< AT.ArgNo + 1 << Arg->getType() << AT.Type;
}
return false;
}
/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
/// friends. This is declared to take (...), so we have to check everything.
bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
if (TheCall->getNumArgs() < 2)
return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
<< 0 << 2 << TheCall->getNumArgs()/*function call*/;
if (TheCall->getNumArgs() > 2)
return Diag(TheCall->getArg(2)->getLocStart(),
diag::err_typecheck_call_too_many_args)
<< 0 /*function call*/ << 2 << TheCall->getNumArgs()
<< SourceRange(TheCall->getArg(2)->getLocStart(),
(*(TheCall->arg_end()-1))->getLocEnd());
ExprResult OrigArg0 = TheCall->getArg(0);
ExprResult OrigArg1 = TheCall->getArg(1);
// Do standard promotions between the two arguments, returning their common
// type.
QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
return true;
// Make sure any conversions are pushed back into the call; this is
// type safe since unordered compare builtins are declared as "_Bool
// foo(...)".
TheCall->setArg(0, OrigArg0.get());
TheCall->setArg(1, OrigArg1.get());
if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
return false;
// If the common type isn't a real floating type, then the arguments were
// invalid for this operation.
if (Res.isNull() || !Res->isRealFloatingType())
return Diag(OrigArg0.get()->getLocStart(),
diag::err_typecheck_call_invalid_ordered_compare)
<< OrigArg0.get()->getType() << OrigArg1.get()->getType()
<< SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
return false;
}
/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
/// __builtin_isnan and friends. This is declared to take (...), so we have
/// to check everything. We expect the last argument to be a floating point
/// value.
bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
if (TheCall->getNumArgs() < NumArgs)
return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
<< 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
if (TheCall->getNumArgs() > NumArgs)
return Diag(TheCall->getArg(NumArgs)->getLocStart(),
diag::err_typecheck_call_too_many_args)
<< 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
<< SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
(*(TheCall->arg_end()-1))->getLocEnd());
Expr *OrigArg = TheCall->getArg(NumArgs-1);
if (OrigArg->isTypeDependent())
return false;
// This operation requires a non-_Complex floating-point number.
if (!OrigArg->getType()->isRealFloatingType())
return Diag(OrigArg->getLocStart(),
diag::err_typecheck_call_invalid_unary_fp)
<< OrigArg->getType() << OrigArg->getSourceRange();
// If this is an implicit conversion from float -> double, remove it.
if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Expr *CastArg = Cast->getSubExpr();
if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
"promotion from float to double is the only expected cast here");
Cast->setSubExpr(nullptr);
TheCall->setArg(NumArgs-1, CastArg);
}
}
return false;
}
/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
// This is declared to take (...), so we have to check everything.
ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
if (TheCall->getNumArgs() < 2)
return ExprError(Diag(TheCall->getLocEnd(),
diag::err_typecheck_call_too_few_args_at_least)
<< 0 /*function call*/ << 2 << TheCall->getNumArgs()
<< TheCall->getSourceRange());
// Determine which of the following types of shufflevector we're checking:
// 1) unary, vector mask: (lhs, mask)
// 2) binary, vector mask: (lhs, rhs, mask)
// 3) binary, scalar mask: (lhs, rhs, index, ..., index)
QualType resType = TheCall->getArg(0)->getType();
unsigned numElements = 0;
if (!TheCall->getArg(0)->isTypeDependent() &&
!TheCall->getArg(1)->isTypeDependent()) {
QualType LHSType = TheCall->getArg(0)->getType();
QualType RHSType = TheCall->getArg(1)->getType();
if (!LHSType->isVectorType() || !RHSType->isVectorType())
return ExprError(Diag(TheCall->getLocStart(),
diag::err_shufflevector_non_vector)
<< SourceRange(TheCall->getArg(0)->getLocStart(),
TheCall->getArg(1)->getLocEnd()));
numElements = LHSType->getAs<VectorType>()->getNumElements();
unsigned numResElements = TheCall->getNumArgs() - 2;
// Check to see if we have a call with 2 vector arguments, the unary shuffle
// with mask. If so, verify that RHS is an integer vector type with the
// same number of elts as lhs.
if (TheCall->getNumArgs() == 2) {
if (!RHSType->hasIntegerRepresentation() ||
RHSType->getAs<VectorType>()->getNumElements() != numElements)
return ExprError(Diag(TheCall->getLocStart(),
diag::err_shufflevector_incompatible_vector)
<< SourceRange(TheCall->getArg(1)->getLocStart(),
TheCall->getArg(1)->getLocEnd()));
} else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
return ExprError(Diag(TheCall->getLocStart(),
diag::err_shufflevector_incompatible_vector)
<< SourceRange(TheCall->getArg(0)->getLocStart(),
TheCall->getArg(1)->getLocEnd()));
} else if (numElements != numResElements) {
QualType eltType = LHSType->getAs<VectorType>()->getElementType();
resType = Context.getVectorType(eltType, numResElements,
VectorType::GenericVector);
}
}
for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
if (TheCall->getArg(i)->isTypeDependent() ||
TheCall->getArg(i)->isValueDependent())
continue;
llvm::APSInt Result(32);
if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
return ExprError(Diag(TheCall->getLocStart(),
diag::err_shufflevector_nonconstant_argument)
<< TheCall->getArg(i)->getSourceRange());
// Allow -1 which will be translated to undef in the IR.
if (Result.isSigned() && Result.isAllOnesValue())
continue;
if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
return ExprError(Diag(TheCall->getLocStart(),
diag::err_shufflevector_argument_too_large)
<< TheCall->getArg(i)->getSourceRange());
}
SmallVector<Expr*, 32> exprs;
for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
exprs.push_back(TheCall->getArg(i));
TheCall->setArg(i, nullptr);
}
return new (Context) ShuffleVectorExpr(Context, exprs, resType,
TheCall->getCallee()->getLocStart(),
TheCall->getRParenLoc());
}
/// SemaConvertVectorExpr - Handle __builtin_convertvector
ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc) {
ExprValueKind VK = VK_RValue;
ExprObjectKind OK = OK_Ordinary;
QualType DstTy = TInfo->getType();
QualType SrcTy = E->getType();
if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
return ExprError(Diag(BuiltinLoc,
diag::err_convertvector_non_vector)
<< E->getSourceRange());
if (!DstTy->isVectorType() && !DstTy->isDependentType())
return ExprError(Diag(BuiltinLoc,
diag::err_convertvector_non_vector_type));
if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
if (SrcElts != DstElts)
return ExprError(Diag(BuiltinLoc,
diag::err_convertvector_incompatible_vector)
<< E->getSourceRange());
}
return new (Context)
ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
}
/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
// This is declared to take (const void*, ...) and can take two
// optional constant int args.
bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
unsigned NumArgs = TheCall->getNumArgs();
if (NumArgs > 3)
return Diag(TheCall->getLocEnd(),
diag::err_typecheck_call_too_many_args_at_most)
<< 0 /*function call*/ << 3 << NumArgs
<< TheCall->getSourceRange();
// Argument 0 is checked for us and the remaining arguments must be
// constant integers.
for (unsigned i = 1; i != NumArgs; ++i)
if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
return true;
return false;
}
/// SemaBuiltinAssume - Handle __assume (MS Extension).
// __assume does not evaluate its arguments, and should warn if its argument
// has side effects.
bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
Expr *Arg = TheCall->getArg(0);
if (Arg->isInstantiationDependent()) return false;
if (Arg->HasSideEffects(Context))
Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
<< Arg->getSourceRange()
<< cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
return false;
}
/// Handle __builtin_assume_aligned. This is declared
/// as (const void*, size_t, ...) and can take one optional constant int arg.
bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
unsigned NumArgs = TheCall->getNumArgs();
if (NumArgs > 3)
return Diag(TheCall->getLocEnd(),
diag::err_typecheck_call_too_many_args_at_most)
<< 0 /*function call*/ << 3 << NumArgs
<< TheCall->getSourceRange();
// The alignment must be a constant integer.
Expr *Arg = TheCall->getArg(1);
// We can't check the value of a dependent argument.
if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
llvm::APSInt Result;
if (SemaBuiltinConstantArg(TheCall, 1, Result))
return true;
if (!Result.isPowerOf2())
return Diag(TheCall->getLocStart(),
diag::err_alignment_not_power_of_two)
<< Arg->getSourceRange();
}
if (NumArgs > 2) {
ExprResult Arg(TheCall->getArg(2));
InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
Context.getSizeType(), false);
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (Arg.isInvalid()) return true;
TheCall->setArg(2, Arg.get());
}
return false;
}
/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
/// TheCall is a constant expression.
bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result) {
Expr *Arg = TheCall->getArg(ArgNum);
DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
if (!Arg->isIntegerConstantExpr(Result, Context))
return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
<< FDecl->getDeclName() << Arg->getSourceRange();
return false;
}
/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
/// TheCall is a constant expression in the range [Low, High].
bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
int Low, int High) {
llvm::APSInt Result;
// We can't check the value of a dependent argument.
Expr *Arg = TheCall->getArg(ArgNum);
if (Arg->isTypeDependent() || Arg->isValueDependent())
return false;
// Check constant-ness first.
if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
return true;
if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
<< Low << High << Arg->getSourceRange();
return false;
}
/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
/// TheCall is an ARM/AArch64 special register string literal.
bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName) {
bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
BuiltinID == ARM::BI__builtin_arm_wsr64 ||
BuiltinID == ARM::BI__builtin_arm_rsr ||
BuiltinID == ARM::BI__builtin_arm_rsrp ||
BuiltinID == ARM::BI__builtin_arm_wsr ||
BuiltinID == ARM::BI__builtin_arm_wsrp;
bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
BuiltinID == AArch64::BI__builtin_arm_rsr ||
BuiltinID == AArch64::BI__builtin_arm_rsrp ||
BuiltinID == AArch64::BI__builtin_arm_wsr ||
BuiltinID == AArch64::BI__builtin_arm_wsrp;
assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
// We can't check the value of a dependent argument.
Expr *Arg = TheCall->getArg(ArgNum);
if (Arg->isTypeDependent() || Arg->isValueDependent())
return false;
// Check if the argument is a string literal.
if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
<< Arg->getSourceRange();
// Check the type of special register given.
StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
SmallVector<StringRef, 6> Fields;
Reg.split(Fields, ":");
if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
<< Arg->getSourceRange();
// If the string is the name of a register then we cannot check that it is
// valid here but if the string is of one the forms described in ACLE then we
// can check that the supplied fields are integers and within the valid
// ranges.
if (Fields.size() > 1) {
bool FiveFields = Fields.size() == 5;
bool ValidString = true;
if (IsARMBuiltin) {
ValidString &= Fields[0].startswith_lower("cp") ||
Fields[0].startswith_lower("p");
if (ValidString)
Fields[0] =
Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
ValidString &= Fields[2].startswith_lower("c");
if (ValidString)
Fields[2] = Fields[2].drop_front(1);
if (FiveFields) {
ValidString &= Fields[3].startswith_lower("c");
if (ValidString)
Fields[3] = Fields[3].drop_front(1);
}
}
SmallVector<int, 5> Ranges;
if (FiveFields)
Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
else
Ranges.append({15, 7, 15});
for (unsigned i=0; i<Fields.size(); ++i) {
int IntField;
ValidString &= !Fields[i].getAsInteger(10, IntField);
ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
}
if (!ValidString)
return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
<< Arg->getSourceRange();
} else if (IsAArch64Builtin && Fields.size() == 1) {
// If the register name is one of those that appear in the condition below
// and the special register builtin being used is one of the write builtins,
// then we require that the argument provided for writing to the register
// is an integer constant expression. This is because it will be lowered to
// an MSR (immediate) instruction, so we need to know the immediate at
// compile time.
if (TheCall->getNumArgs() != 2)
return false;
std::string RegLower = Reg.lower();
if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
RegLower != "pan" && RegLower != "uao")
return false;
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
}
return false;
}
/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
/// This checks that the target supports __builtin_longjmp and
/// that val is a constant 1.
bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
if (!Context.getTargetInfo().hasSjLjLowering())
return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
<< SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
Expr *Arg = TheCall->getArg(1);
llvm::APSInt Result;
// TODO: This is less than ideal. Overload this to take a value.
if (SemaBuiltinConstantArg(TheCall, 1, Result))
return true;
if (Result != 1)
return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
<< SourceRange(Arg->getLocStart(), Arg->getLocEnd());
return false;
}
/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
/// This checks that the target supports __builtin_setjmp.
bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
if (!Context.getTargetInfo().hasSjLjLowering())
return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
<< SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
return false;
}
namespace {
class UncoveredArgHandler {
enum { Unknown = -1, AllCovered = -2 };
signed FirstUncoveredArg;
SmallVector<const Expr *, 4> DiagnosticExprs;
public:
UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
bool hasUncoveredArg() const {
return (FirstUncoveredArg >= 0);
}
unsigned getUncoveredArg() const {
assert(hasUncoveredArg() && "no uncovered argument");
return FirstUncoveredArg;
}
void setAllCovered() {
// A string has been found with all arguments covered, so clear out
// the diagnostics.
DiagnosticExprs.clear();
FirstUncoveredArg = AllCovered;
}
void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
assert(NewFirstUncoveredArg >= 0 && "Outside range");
// Don't update if a previous string covers all arguments.
if (FirstUncoveredArg == AllCovered)
return;
// UncoveredArgHandler tracks the highest uncovered argument index
// and with it all the strings that match this index.
if (NewFirstUncoveredArg == FirstUncoveredArg)
DiagnosticExprs.push_back(StrExpr);
else if (NewFirstUncoveredArg > FirstUncoveredArg) {
DiagnosticExprs.clear();
DiagnosticExprs.push_back(StrExpr);
FirstUncoveredArg = NewFirstUncoveredArg;
}
}
void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
};
enum StringLiteralCheckType {
SLCT_NotALiteral,
SLCT_UncheckedLiteral,
SLCT_CheckedLiteral
};
} // end anonymous namespace
static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
const Expr *OrigFormatExpr,
ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg,
Sema::FormatStringType Type,
bool inFunctionCall,
Sema::VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg);
// Determine if an expression is a string literal or constant string.
// If this function returns false on the arguments to a function expecting a
// format string, we will usually need to emit a warning.
// True string literals are then checked by CheckFormatString.
static StringLiteralCheckType
checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, Sema::FormatStringType Type,
Sema::VariadicCallType CallType, bool InFunctionCall,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg) {
tryAgain:
if (E->isTypeDependent() || E->isValueDependent())
return SLCT_NotALiteral;
E = E->IgnoreParenCasts();
if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
// Technically -Wformat-nonliteral does not warn about this case.
// The behavior of printf and friends in this case is implementation
// dependent. Ideally if the format string cannot be null then
// it should have a 'nonnull' attribute in the function prototype.
return SLCT_UncheckedLiteral;
switch (E->getStmtClass()) {
case Stmt::BinaryConditionalOperatorClass:
case Stmt::ConditionalOperatorClass: {
// The expression is a literal if both sub-expressions were, and it was
// completely checked only if both sub-expressions were checked.
const AbstractConditionalOperator *C =
cast<AbstractConditionalOperator>(E);
// Determine whether it is necessary to check both sub-expressions, for
// example, because the condition expression is a constant that can be
// evaluated at compile time.
bool CheckLeft = true, CheckRight = true;
bool Cond;
if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
if (Cond)
CheckRight = false;
else
CheckLeft = false;
}
StringLiteralCheckType Left;
if (!CheckLeft)
Left = SLCT_UncheckedLiteral;
else {
Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
HasVAListArg, format_idx, firstDataArg,
Type, CallType, InFunctionCall,
CheckedVarArgs, UncoveredArg);
if (Left == SLCT_NotALiteral || !CheckRight)
return Left;
}
StringLiteralCheckType Right =
checkFormatStringExpr(S, C->getFalseExpr(), Args,
HasVAListArg, format_idx, firstDataArg,
Type, CallType, InFunctionCall, CheckedVarArgs,
UncoveredArg);
return (CheckLeft && Left < Right) ? Left : Right;
}
case Stmt::ImplicitCastExprClass: {
E = cast<ImplicitCastExpr>(E)->getSubExpr();
goto tryAgain;
}
case Stmt::OpaqueValueExprClass:
if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
E = src;
goto tryAgain;
}
return SLCT_NotALiteral;
case Stmt::PredefinedExprClass:
// While __func__, etc., are technically not string literals, they
// cannot contain format specifiers and thus are not a security
// liability.
return SLCT_UncheckedLiteral;
case Stmt::DeclRefExprClass: {
const DeclRefExpr *DR = cast<DeclRefExpr>(E);
// As an exception, do not flag errors for variables binding to
// const string literals.
if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
bool isConstant = false;
QualType T = DR->getType();
if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
isConstant = AT->getElementType().isConstant(S.Context);
} else if (const PointerType *PT = T->getAs<PointerType>()) {
isConstant = T.isConstant(S.Context) &&
PT->getPointeeType().isConstant(S.Context);
} else if (T->isObjCObjectPointerType()) {
// In ObjC, there is usually no "const ObjectPointer" type,
// so don't check if the pointee type is constant.
isConstant = T.isConstant(S.Context);
}
if (isConstant) {
if (const Expr *Init = VD->getAnyInitializer()) {
// Look through initializers like const char c[] = { "foo" }
if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
if (InitList->isStringLiteralInit())
Init = InitList->getInit(0)->IgnoreParenImpCasts();
}
return checkFormatStringExpr(S, Init, Args,
HasVAListArg, format_idx,
firstDataArg, Type, CallType,
/*InFunctionCall*/false, CheckedVarArgs,
UncoveredArg);
}
}
// For vprintf* functions (i.e., HasVAListArg==true), we add a
// special check to see if the format string is a function parameter
// of the function calling the printf function. If the function
// has an attribute indicating it is a printf-like function, then we
// should suppress warnings concerning non-literals being used in a call
// to a vprintf function. For example:
//
// void
// logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
// va_list ap;
// va_start(ap, fmt);
// vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
// ...
// }
if (HasVAListArg) {
if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
int PVIndex = PV->getFunctionScopeIndex() + 1;
for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
// adjust for implicit parameter
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
if (MD->isInstance())
++PVIndex;
// We also check if the formats are compatible.
// We can't pass a 'scanf' string to a 'printf' function.
if (PVIndex == PVFormat->getFormatIdx() &&
Type == S.GetFormatStringType(PVFormat))
return SLCT_UncheckedLiteral;
}
}
}
}
}
return SLCT_NotALiteral;
}
case Stmt::CallExprClass:
case Stmt::CXXMemberCallExprClass: {
const CallExpr *CE = cast<CallExpr>(E);
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
unsigned ArgIndex = FA->getFormatIdx();
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
if (MD->isInstance())
--ArgIndex;
const Expr *Arg = CE->getArg(ArgIndex - 1);
return checkFormatStringExpr(S, Arg, Args,
HasVAListArg, format_idx, firstDataArg,
Type, CallType, InFunctionCall,
CheckedVarArgs, UncoveredArg);
} else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
unsigned BuiltinID = FD->getBuiltinID();
if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
const Expr *Arg = CE->getArg(0);
return checkFormatStringExpr(S, Arg, Args,
HasVAListArg, format_idx,
firstDataArg, Type, CallType,
InFunctionCall, CheckedVarArgs,
UncoveredArg);
}
}
}
return SLCT_NotALiteral;
}
case Stmt::ObjCStringLiteralClass:
case Stmt::StringLiteralClass: {
const StringLiteral *StrE = nullptr;
if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
StrE = ObjCFExpr->getString();
else
StrE = cast<StringLiteral>(E);
if (StrE) {
CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
firstDataArg, Type, InFunctionCall, CallType,
CheckedVarArgs, UncoveredArg);
return SLCT_CheckedLiteral;
}
return SLCT_NotALiteral;
}
default:
return SLCT_NotALiteral;
}
}
Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
.Case("scanf", FST_Scanf)
.Cases("printf", "printf0", FST_Printf)
.Cases("NSString", "CFString", FST_NSString)
.Case("strftime", FST_Strftime)
.Case("strfmon", FST_Strfmon)
.Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
.Case("freebsd_kprintf", FST_FreeBSDKPrintf)
.Case("os_trace", FST_OSTrace)
.Default(FST_Unknown);
}
/// CheckFormatArguments - Check calls to printf and scanf (and similar
/// functions) for correct use of format strings.
/// Returns true if a format string has been fully checked.
bool Sema::CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs) {
FormatStringInfo FSI;
if (getFormatStringInfo(Format, IsCXXMember, &FSI))
return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
FSI.FirstDataArg, GetFormatStringType(Format),
CallType, Loc, Range, CheckedVarArgs);
return false;
}
bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs) {
// CHECK: printf/scanf-like function is called with no format string.
if (format_idx >= Args.size()) {
Diag(Loc, diag::warn_missing_format_string) << Range;
return false;
}
const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
// CHECK: format string is not a string literal.
//
// Dynamically generated format strings are difficult to
// automatically vet at compile time. Requiring that format strings
// are string literals: (1) permits the checking of format strings by
// the compiler and thereby (2) can practically remove the source of
// many format string exploits.
// Format string can be either ObjC string (e.g. @"%d") or
// C string (e.g. "%d")
// ObjC string uses the same format specifiers as C string, so we can use
// the same format string checking logic for both ObjC and C strings.
UncoveredArgHandler UncoveredArg;
StringLiteralCheckType CT =
checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
format_idx, firstDataArg, Type, CallType,
/*IsFunctionCall*/true, CheckedVarArgs,
UncoveredArg);
// Generate a diagnostic where an uncovered argument is detected.
if (UncoveredArg.hasUncoveredArg()) {
unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
}
if (CT != SLCT_NotALiteral)
// Literal format string found, check done!
return CT == SLCT_CheckedLiteral;
// Strftime is particular as it always uses a single 'time' argument,
// so it is safe to pass a non-literal string.
if (Type == FST_Strftime)
return false;
// Do not emit diag when the string param is a macro expansion and the
// format is either NSString or CFString. This is a hack to prevent
// diag when using the NSLocalizedString and CFCopyLocalizedString macros
// which are usually used in place of NS and CF string literals.
SourceLocation FormatLoc = Args[format_idx]->getLocStart();
if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
return false;
// If there are no arguments specified, warn with -Wformat-security, otherwise
// warn only with -Wformat-nonliteral.
if (Args.size() == firstDataArg) {
Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
<< OrigFormatExpr->getSourceRange();
switch (Type) {
default:
break;
case FST_Kprintf:
case FST_FreeBSDKPrintf:
case FST_Printf:
Diag(FormatLoc, diag::note_format_security_fixit)
<< FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
break;
case FST_NSString:
Diag(FormatLoc, diag::note_format_security_fixit)
<< FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
break;
}
} else {
Diag(FormatLoc, diag::warn_format_nonliteral)
<< OrigFormatExpr->getSourceRange();
}
return false;
}
namespace {
class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
protected:
Sema &S;
const StringLiteral *FExpr;
const Expr *OrigFormatExpr;
const unsigned FirstDataArg;
const unsigned NumDataArgs;
const char *Beg; // Start of format string.
const bool HasVAListArg;
ArrayRef<const Expr *> Args;
unsigned FormatIdx;
llvm::SmallBitVector CoveredArgs;
bool usesPositionalArgs;
bool atFirstArg;
bool inFunctionCall;
Sema::VariadicCallType CallType;
llvm::SmallBitVector &CheckedVarArgs;
UncoveredArgHandler &UncoveredArg;
public:
CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
const Expr *origFormatExpr, unsigned firstDataArg,
unsigned numDataArgs, const char *beg, bool hasVAListArg,
ArrayRef<const Expr *> Args,
unsigned formatIdx, bool inFunctionCall,
Sema::VariadicCallType callType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg)
: S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
Beg(beg), HasVAListArg(hasVAListArg),
Args(Args), FormatIdx(formatIdx),
usesPositionalArgs(false), atFirstArg(true),
inFunctionCall(inFunctionCall), CallType(callType),
CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
CoveredArgs.resize(numDataArgs);
CoveredArgs.reset();
}
void DoneProcessing();
void HandleIncompleteSpecifier(const char *startSpecifier,
unsigned specifierLen) override;
void HandleInvalidLengthModifier(
const analyze_format_string::FormatSpecifier &FS,
const analyze_format_string::ConversionSpecifier &CS,
const char *startSpecifier, unsigned specifierLen,
unsigned DiagID);
void HandleNonStandardLengthModifier(
const analyze_format_string::FormatSpecifier &FS,
const char *startSpecifier, unsigned specifierLen);
void HandleNonStandardConversionSpecifier(
const analyze_format_string::ConversionSpecifier &CS,
const char *startSpecifier, unsigned specifierLen);
void HandlePosition(const char *startPos, unsigned posLen) override;
void HandleInvalidPosition(const char *startSpecifier,
unsigned specifierLen,
analyze_format_string::PositionContext p) override;
void HandleZeroPosition(const char *startPos, unsigned posLen) override;
void HandleNullChar(const char *nullCharacter) override;
template <typename Range>
static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
const Expr *ArgumentExpr,
PartialDiagnostic PDiag,
SourceLocation StringLoc,
bool IsStringLocation, Range StringRange,
ArrayRef<FixItHint> Fixit = None);
protected:
bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
const char *startSpec,
unsigned specifierLen,
const char *csStart, unsigned csLen);
void HandlePositionalNonpositionalArgs(SourceLocation Loc,
const char *startSpec,
unsigned specifierLen);
SourceRange getFormatStringRange();
CharSourceRange getSpecifierRange(const char *startSpecifier,
unsigned specifierLen);
SourceLocation getLocationOfByte(const char *x);
const Expr *getDataArg(unsigned i) const;
bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
const analyze_format_string::ConversionSpecifier &CS,
const char *startSpecifier, unsigned specifierLen,
unsigned argIndex);
template <typename Range>
void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
bool IsStringLocation, Range StringRange,
ArrayRef<FixItHint> Fixit = None);
};
} // end anonymous namespace
SourceRange CheckFormatHandler::getFormatStringRange() {
return OrigFormatExpr->getSourceRange();
}
CharSourceRange CheckFormatHandler::
getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
SourceLocation Start = getLocationOfByte(startSpecifier);
SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
// Advance the end SourceLocation by one due to half-open ranges.
End = End.getLocWithOffset(1);
return CharSourceRange::getCharRange(Start, End);
}
SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
}
void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
unsigned specifierLen){
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
getLocationOfByte(startSpecifier),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
}
void CheckFormatHandler::HandleInvalidLengthModifier(
const analyze_format_string::FormatSpecifier &FS,
const analyze_format_string::ConversionSpecifier &CS,
const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
using namespace analyze_format_string;
const LengthModifier &LM = FS.getLengthModifier();
CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
// See if we know how to fix this length modifier.
Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
if (FixedLM) {
EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
getLocationOfByte(LM.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
<< FixedLM->toString()
<< FixItHint::CreateReplacement(LMRange, FixedLM->toString());
} else {
FixItHint Hint;
if (DiagID == diag::warn_format_nonsensical_length)
Hint = FixItHint::CreateRemoval(LMRange);
EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
getLocationOfByte(LM.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen),
Hint);
}
}
void CheckFormatHandler::HandleNonStandardLengthModifier(
const analyze_format_string::FormatSpecifier &FS,
const char *startSpecifier, unsigned specifierLen) {
using namespace analyze_format_string;
const LengthModifier &LM = FS.getLengthModifier();
CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
// See if we know how to fix this length modifier.
Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
if (FixedLM) {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
<< LM.toString() << 0,
getLocationOfByte(LM.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
<< FixedLM->toString()
<< FixItHint::CreateReplacement(LMRange, FixedLM->toString());
} else {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
<< LM.toString() << 0,
getLocationOfByte(LM.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
}
}
void CheckFormatHandler::HandleNonStandardConversionSpecifier(
const analyze_format_string::ConversionSpecifier &CS,
const char *startSpecifier, unsigned specifierLen) {
using namespace analyze_format_string;
// See if we know how to fix this conversion specifier.
Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
if (FixedCS) {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
<< CS.toString() << /*conversion specifier*/1,
getLocationOfByte(CS.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
<< FixedCS->toString()
<< FixItHint::CreateReplacement(CSRange, FixedCS->toString());
} else {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
<< CS.toString() << /*conversion specifier*/1,
getLocationOfByte(CS.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
}
}
void CheckFormatHandler::HandlePosition(const char *startPos,
unsigned posLen) {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
getLocationOfByte(startPos),
/*IsStringLocation*/true,
getSpecifierRange(startPos, posLen));
}
void
CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
analyze_format_string::PositionContext p) {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
<< (unsigned) p,
getLocationOfByte(startPos), /*IsStringLocation*/true,
getSpecifierRange(startPos, posLen));
}
void CheckFormatHandler::HandleZeroPosition(const char *startPos,
unsigned posLen) {
EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
getLocationOfByte(startPos),
/*IsStringLocation*/true,
getSpecifierRange(startPos, posLen));
}
void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
// The presence of a null character is likely an error.
EmitFormatDiagnostic(
S.PDiag(diag::warn_printf_format_string_contains_null_char),
getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
getFormatStringRange());
}
}
// Note that this may return NULL if there was an error parsing or building
// one of the argument expressions.
const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
return Args[FirstDataArg + i];
}
void CheckFormatHandler::DoneProcessing() {
// Does the number of data arguments exceed the number of
// format conversions in the format string?
if (!HasVAListArg) {
// Find any arguments that weren't covered.
CoveredArgs.flip();
signed notCoveredArg = CoveredArgs.find_first();
if (notCoveredArg >= 0) {
assert((unsigned)notCoveredArg < NumDataArgs);
UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
} else {
UncoveredArg.setAllCovered();
}
}
}
void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
const Expr *ArgExpr) {
assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
"Invalid state");
if (!ArgExpr)
return;
SourceLocation Loc = ArgExpr->getLocStart();
if (S.getSourceManager().isInSystemMacro(Loc))
return;
PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
for (auto E : DiagnosticExprs)
PDiag << E->getSourceRange();
CheckFormatHandler::EmitFormatDiagnostic(
S, IsFunctionCall, DiagnosticExprs[0],
PDiag, Loc, /*IsStringLocation*/false,
DiagnosticExprs[0]->getSourceRange());
}
bool
CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
SourceLocation Loc,
const char *startSpec,
unsigned specifierLen,
const char *csStart,
unsigned csLen) {
bool keepGoing = true;
if (argIndex < NumDataArgs) {
// Consider the argument coverered, even though the specifier doesn't
// make sense.
CoveredArgs.set(argIndex);
}
else {
// If argIndex exceeds the number of data arguments we
// don't issue a warning because that is just a cascade of warnings (and
// they may have intended '%%' anyway). We don't want to continue processing
// the format string after this point, however, as we will like just get
// gibberish when trying to match arguments.
keepGoing = false;
}
StringRef Specifier(csStart, csLen);
// If the specifier in non-printable, it could be the first byte of a UTF-8
// sequence. In that case, print the UTF-8 code point. If not, print the byte
// hex value.
std::string CodePointStr;
if (!llvm::sys::locale::isPrint(*csStart)) {
UTF32 CodePoint;
const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
const UTF8 *E =
reinterpret_cast<const UTF8 *>(csStart + csLen);
ConversionResult Result =
llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
if (Result != conversionOK) {
unsigned char FirstChar = *csStart;
CodePoint = (UTF32)FirstChar;
}
llvm::raw_string_ostream OS(CodePointStr);
if (CodePoint < 256)
OS << "\\x" << llvm::format("%02x", CodePoint);
else if (CodePoint <= 0xFFFF)
OS << "\\u" << llvm::format("%04x", CodePoint);
else
OS << "\\U" << llvm::format("%08x", CodePoint);
OS.flush();
Specifier = CodePointStr;
}
EmitFormatDiagnostic(
S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
/*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
return keepGoing;
}
void
CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
const char *startSpec,
unsigned specifierLen) {
EmitFormatDiagnostic(
S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
}
bool
CheckFormatHandler::CheckNumArgs(
const analyze_format_string::FormatSpecifier &FS,
const analyze_format_string::ConversionSpecifier &CS,
const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
if (argIndex >= NumDataArgs) {
PartialDiagnostic PDiag = FS.usesPositionalArg()
? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
<< (argIndex+1) << NumDataArgs)
: S.PDiag(diag::warn_printf_insufficient_data_args);
EmitFormatDiagnostic(
PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
// Since more arguments than conversion tokens are given, by extension
// all arguments are covered, so mark this as so.
UncoveredArg.setAllCovered();
return false;
}
return true;
}
template<typename Range>
void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
SourceLocation Loc,
bool IsStringLocation,
Range StringRange,
ArrayRef<FixItHint> FixIt) {
EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Loc, IsStringLocation, StringRange, FixIt);
}
/// \brief If the format string is not within the funcion call, emit a note
/// so that the function call and string are in diagnostic messages.
///
/// \param InFunctionCall if true, the format string is within the function
/// call and only one diagnostic message will be produced. Otherwise, an
/// extra note will be emitted pointing to location of the format string.
///
/// \param ArgumentExpr the expression that is passed as the format string
/// argument in the function call. Used for getting locations when two
/// diagnostics are emitted.
///
/// \param PDiag the callee should already have provided any strings for the
/// diagnostic message. This function only adds locations and fixits
/// to diagnostics.
///
/// \param Loc primary location for diagnostic. If two diagnostics are
/// required, one will be at Loc and a new SourceLocation will be created for
/// the other one.
///
/// \param IsStringLocation if true, Loc points to the format string should be
/// used for the note. Otherwise, Loc points to the argument list and will
/// be used with PDiag.
///
/// \param StringRange some or all of the string to highlight. This is
/// templated so it can accept either a CharSourceRange or a SourceRange.
///
/// \param FixIt optional fix it hint for the format string.
template<typename Range>
void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
const Expr *ArgumentExpr,
PartialDiagnostic PDiag,
SourceLocation Loc,
bool IsStringLocation,
Range StringRange,
ArrayRef<FixItHint> FixIt) {
if (InFunctionCall) {
const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
D << StringRange;
D << FixIt;
} else {
S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
<< ArgumentExpr->getSourceRange();
const Sema::SemaDiagnosticBuilder &Note =
S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
diag::note_format_string_defined);
Note << StringRange;
Note << FixIt;
}
}
//===--- CHECK: Printf format string checking ------------------------------===//
namespace {
class CheckPrintfHandler : public CheckFormatHandler {
bool ObjCContext;
public:
CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
const Expr *origFormatExpr, unsigned firstDataArg,
unsigned numDataArgs, bool isObjC,
const char *beg, bool hasVAListArg,
ArrayRef<const Expr *> Args,
unsigned formatIdx, bool inFunctionCall,
Sema::VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg)
: CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
numDataArgs, beg, hasVAListArg, Args,
formatIdx, inFunctionCall, CallType, CheckedVarArgs,
UncoveredArg),
ObjCContext(isObjC)
{}
bool HandleInvalidPrintfConversionSpecifier(
const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) override;
bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) override;
bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
const char *StartSpecifier,
unsigned SpecifierLen,
const Expr *E);
bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
const char *startSpecifier, unsigned specifierLen);
void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
const analyze_printf::OptionalAmount &Amt,
unsigned type,
const char *startSpecifier, unsigned specifierLen);
void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
const analyze_printf::OptionalFlag &flag,
const char *startSpecifier, unsigned specifierLen);
void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
const analyze_printf::OptionalFlag &ignoredFlag,
const analyze_printf::OptionalFlag &flag,
const char *startSpecifier, unsigned specifierLen);
bool checkForCStrMembers(const analyze_printf::ArgType &AT,
const Expr *E);
void HandleEmptyObjCModifierFlag(const char *startFlag,
unsigned flagLen) override;
void HandleInvalidObjCModifierFlag(const char *startFlag,
unsigned flagLen) override;
void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition)
override;
};
} // end anonymous namespace
bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
const analyze_printf::PrintfConversionSpecifier &CS =
FS.getConversionSpecifier();
return HandleInvalidConversionSpecifier(FS.getArgIndex(),
getLocationOfByte(CS.getStart()),
startSpecifier, specifierLen,
CS.getStart(), CS.getLength());
}
bool CheckPrintfHandler::HandleAmount(
const analyze_format_string::OptionalAmount &Amt,
unsigned k, const char *startSpecifier,
unsigned specifierLen) {
if (Amt.hasDataArgument()) {
if (!HasVAListArg) {
unsigned argIndex = Amt.getArgIndex();
if (argIndex >= NumDataArgs) {
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
<< k,
getLocationOfByte(Amt.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
// Don't do any more checking. We will just emit
// spurious errors.
return false;
}
// Type check the data argument. It should be an 'int'.
// Although not in conformance with C99, we also allow the argument to be
// an 'unsigned int' as that is a reasonably safe case. GCC also
// doesn't emit a warning for that case.
CoveredArgs.set(argIndex);
const Expr *Arg = getDataArg(argIndex);
if (!Arg)
return false;
QualType T = Arg->getType();
const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
assert(AT.isValid());
if (!AT.matchesType(S.Context, T)) {
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
<< k << AT.getRepresentativeTypeName(S.Context)
<< T << Arg->getSourceRange(),
getLocationOfByte(Amt.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen));
// Don't do any more checking. We will just emit
// spurious errors.
return false;
}
}
}
return true;
}
void CheckPrintfHandler::HandleInvalidAmount(
const analyze_printf::PrintfSpecifier &FS,
const analyze_printf::OptionalAmount &Amt,
unsigned type,
const char *startSpecifier,
unsigned specifierLen) {
const analyze_printf::PrintfConversionSpecifier &CS =
FS.getConversionSpecifier();
FixItHint fixit =
Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Amt.getConstantLength()))
: FixItHint();
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
<< type << CS.toString(),
getLocationOfByte(Amt.getStart()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen),
fixit);
}
void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
const analyze_printf::OptionalFlag &flag,
const char *startSpecifier,
unsigned specifierLen) {
// Warn about pointless flag with a fixit removal.
const analyze_printf::PrintfConversionSpecifier &CS =
FS.getConversionSpecifier();
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
<< flag.toString() << CS.toString(),
getLocationOfByte(flag.getPosition()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen),
FixItHint::CreateRemoval(
getSpecifierRange(flag.getPosition(), 1)));
}
void CheckPrintfHandler::HandleIgnoredFlag(
const analyze_printf::PrintfSpecifier &FS,
const analyze_printf::OptionalFlag &ignoredFlag,
const analyze_printf::OptionalFlag &flag,
const char *startSpecifier,
unsigned specifierLen) {
// Warn about ignored flag with a fixit removal.
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
<< ignoredFlag.toString() << flag.toString(),
getLocationOfByte(ignoredFlag.getPosition()),
/*IsStringLocation*/true,
getSpecifierRange(startSpecifier, specifierLen),
FixItHint::CreateRemoval(
getSpecifierRange(ignoredFlag.getPosition(), 1)));
}
// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
// bool IsStringLocation, Range StringRange,
// ArrayRef<FixItHint> Fixit = None);
void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
unsigned flagLen) {
// Warn about an empty flag.
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
getLocationOfByte(startFlag),
/*IsStringLocation*/true,
getSpecifierRange(startFlag, flagLen));
}
void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
unsigned flagLen) {
// Warn about an invalid flag.
auto Range = getSpecifierRange(startFlag, flagLen);
StringRef flag(startFlag, flagLen);
EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
getLocationOfByte(startFlag),
/*IsStringLocation*/true,
Range, FixItHint::CreateRemoval(Range));
}
void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
// Warn about using '[...]' without a '@' conversion.
auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
getLocationOfByte(conversionPosition),
/*IsStringLocation*/true,
Range, FixItHint::CreateRemoval(Range));
}
// Determines if the specified is a C++ class or struct containing
// a member with the specified name and kind (e.g. a CXXMethodDecl named
// "c_str()").
template<typename MemberKind>
static llvm::SmallPtrSet<MemberKind*, 1>
CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
const RecordType *RT = Ty->getAs<RecordType>();
llvm::SmallPtrSet<MemberKind*, 1> Results;
if (!RT)
return Results;
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
if (!RD || !RD->getDefinition())
return Results;
LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Sema::LookupMemberName);
R.suppressDiagnostics();
// We just need to include all members of the right kind turned up by the
// filter, at this point.
if (S.LookupQualifiedName(R, RT->getDecl()))
for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
NamedDecl *decl = (*I)->getUnderlyingDecl();
if (MemberKind *FK = dyn_cast<MemberKind>(decl))
Results.insert(FK);
}
return Results;
}
/// Check if we could call '.c_str()' on an object.
///
/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
/// allow the call, or if it would be ambiguous).
bool Sema::hasCStrMethod(const Expr *E) {
typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
MethodSet Results =
CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
MI != ME; ++MI)
if ((*MI)->getMinRequiredArguments() == 0)
return true;
return false;
}
// Check if a (w)string was passed when a (w)char* was needed, and offer a
// better diagnostic if so. AT is assumed to be valid.
// Returns true when a c_str() conversion method is found.
bool CheckPrintfHandler::checkForCStrMembers(
const analyze_printf::ArgType &AT, const Expr *E) {
typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
MethodSet Results =
CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
MI != ME; ++MI) {
const CXXMethodDecl *Method = *MI;
if (Method->getMinRequiredArguments() == 0 &&
AT.matchesType(S.Context, Method->getReturnType())) {
// FIXME: Suggest parens if the expression needs them.
SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
S.Diag(E->getLocStart(), diag::note_printf_c_str)
<< "c_str()"
<< FixItHint::CreateInsertion(EndLoc, ".c_str()");
return true;
}
}
return false;
}
bool
CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
&FS,
const char *startSpecifier,
unsigned specifierLen) {
using namespace analyze_format_string;
using namespace analyze_printf;
const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
if (FS.consumesDataArgument()) {
if (atFirstArg) {
atFirstArg = false;
usesPositionalArgs = FS.usesPositionalArg();
}
else if (usesPositionalArgs != FS.usesPositionalArg()) {
HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
startSpecifier, specifierLen);
return false;
}
}
// First check if the field width, precision, and conversion specifier
// have matching data arguments.
if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
startSpecifier, specifierLen)) {
return false;
}
if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
startSpecifier, specifierLen)) {
return false;
}
if (!CS.consumesDataArgument()) {
// FIXME: Technically specifying a precision or field width here
// makes no sense. Worth issuing a warning at some point.
return true;
}
// Consume the argument.
unsigned argIndex = FS.getArgIndex();
if (argIndex < NumDataArgs) {
// The check to see if the argIndex is valid will come later.
// We set the bit here because we may exit early from this
// function if we encounter some other error.
CoveredArgs.set(argIndex);
}
// FreeBSD kernel extensions.
if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
// We need at least two arguments.
if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
return false;
// Claim the second argument.
CoveredArgs.set(argIndex + 1);
// Type check the first argument (int for %b, pointer for %D)
const Expr *Ex = getDataArg(argIndex);
const analyze_printf::ArgType &AT =
(CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
ArgType(S.Context.IntTy) : ArgType::CPointerTy;
if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
EmitFormatDiagnostic(
S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
<< AT.getRepresentativeTypeName(S.Context) << Ex->getType()
<< false << Ex->getSourceRange(),
Ex->getLocStart(), /*IsStringLocation*/false,
getSpecifierRange(startSpecifier, specifierLen));
// Type check the second argument (char * for both %b and %D)
Ex = getDataArg(argIndex + 1);
const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
EmitFormatDiagnostic(
S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
<< AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
<< false << Ex->getSourceRange(),
Ex->getLocStart(), /*IsStringLocation*/false,
getSpecifierRange(startSpecifier, specifierLen));
return true;
}
// Check for using an Objective-C specific conversion specifier
// in a non-ObjC literal.
if (!ObjCContext && CS.isObjCArg()) {
return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
specifierLen);
}
// Check for invalid use of field width
if (!FS.hasValidFieldWidth()) {
HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
startSpecifier, specifierLen);
}
// Check for invalid use of precision
if (!FS.hasValidPrecision()) {
HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
startSpecifier, specifierLen);
}
// Check each flag does not conflict with any other component.
if (!FS.hasValidThousandsGroupingPrefix())
HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
if (!FS.hasValidLeadingZeros())
HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
if (!FS.hasValidPlusPrefix())
HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
if (!FS.hasValidSpacePrefix())
HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
if (!FS.hasValidAlternativeForm())
HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
if (!FS.hasValidLeftJustified())
HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
// Check that flags are not ignored by another flag
if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
startSpecifier, specifierLen);
if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
startSpecifier, specifierLen);
// Check the length modifier is valid with the given conversion specifier.
if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
diag::warn_format_nonsensical_length);
else if (!FS.hasStandardLengthModifier())
HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
else if (!FS.hasStandardLengthConversionCombination())
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
diag::warn_format_non_standard_conversion_spec);
if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
// The remaining checks depend on the data arguments.
if (HasVAListArg)
return true;
if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
return false;
const Expr *Arg = getDataArg(argIndex);
if (!Arg)
return true;
return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
}
static bool requiresParensToAddCast(const Expr *E) {
// FIXME: We should have a general way to reason about operator
// precedence and whether parens are actually needed here.
// Take care of a few common cases where they aren't.
const Expr *Inside = E->IgnoreImpCasts();
if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
Inside = POE->getSyntacticForm()->IgnoreImpCasts();
switch (Inside->getStmtClass()) {
case Stmt::ArraySubscriptExprClass:
case Stmt::CallExprClass:
case Stmt::CharacterLiteralClass:
case Stmt::CXXBoolLiteralExprClass:
case Stmt::DeclRefExprClass:
case Stmt::FloatingLiteralClass:
case Stmt::IntegerLiteralClass:
case Stmt::MemberExprClass:
case Stmt::ObjCArrayLiteralClass:
case Stmt::ObjCBoolLiteralExprClass:
case Stmt::ObjCBoxedExprClass:
case Stmt::ObjCDictionaryLiteralClass:
case Stmt::ObjCEncodeExprClass:
case Stmt::ObjCIvarRefExprClass:
case Stmt::ObjCMessageExprClass:
case Stmt::ObjCPropertyRefExprClass:
case Stmt::ObjCStringLiteralClass:
case Stmt::ObjCSubscriptRefExprClass:
case Stmt::ParenExprClass:
case Stmt::StringLiteralClass:
case Stmt::UnaryOperatorClass:
return false;
default:
return true;
}
}
static std::pair<QualType, StringRef>
shouldNotPrintDirectly(const ASTContext &Context,
QualType IntendedTy,
const Expr *E) {
// Use a 'while' to peel off layers of typedefs.
QualType TyTy = IntendedTy;
while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
StringRef Name = UserTy->getDecl()->getName();
QualType CastTy = llvm::StringSwitch<QualType>(Name)
.Case("NSInteger", Context.LongTy)
.Case("NSUInteger", Context.UnsignedLongTy)
.Case("SInt32", Context.IntTy)
.Case("UInt32", Context.UnsignedIntTy)
.Default(QualType());
if (!CastTy.isNull())
return std::make_pair(CastTy, Name);
TyTy = UserTy->desugar();
}
// Strip parens if necessary.
if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
return shouldNotPrintDirectly(Context,
PE->getSubExpr()->getType(),
PE->getSubExpr());
// If this is a conditional expression, then its result type is constructed
// via usual arithmetic conversions and thus there might be no necessary
// typedef sugar there. Recurse to operands to check for NSInteger &
// Co. usage condition.
if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
QualType TrueTy, FalseTy;
StringRef TrueName, FalseName;
std::tie(TrueTy, TrueName) =
shouldNotPrintDirectly(Context,
CO->getTrueExpr()->getType(),
CO->getTrueExpr());
std::tie(FalseTy, FalseName) =
shouldNotPrintDirectly(Context,
CO->getFalseExpr()->getType(),
CO->getFalseExpr());
if (TrueTy == FalseTy)
return std::make_pair(TrueTy, TrueName);
else if (TrueTy.isNull())
return std::make_pair(FalseTy, FalseName);
else if (FalseTy.isNull())
return std::make_pair(TrueTy, TrueName);
}
return std::make_pair(QualType(), StringRef());
}
bool
CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
const char *StartSpecifier,
unsigned SpecifierLen,
const Expr *E) {
using namespace analyze_format_string;
using namespace analyze_printf;
// Now type check the data expression that matches the
// format specifier.
const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
ObjCContext);
if (!AT.isValid())
return true;
QualType ExprTy = E->getType();
while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
ExprTy = TET->getUnderlyingExpr()->getType();
}
analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
if (match == analyze_printf::ArgType::Match) {
return true;
}
// Look through argument promotions for our error message's reported type.
// This includes the integral and floating promotions, but excludes array
// and function pointer decay; seeing that an argument intended to be a
// string has type 'char [6]' is probably more confusing than 'char *'.
if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
if (ICE->getCastKind() == CK_IntegralCast ||
ICE->getCastKind() == CK_FloatingCast) {
E = ICE->getSubExpr();
ExprTy = E->getType();
// Check if we didn't match because of an implicit cast from a 'char'
// or 'short' to an 'int'. This is done because printf is a varargs
// function.
if (ICE->getType() == S.Context.IntTy ||
ICE->getType() == S.Context.UnsignedIntTy) {
// All further checking is done on the subexpression.
if (AT.matchesType(S.Context, ExprTy))
return true;
}
}
} else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
// Special case for 'a', which has type 'int' in C.
// Note, however, that we do /not/ want to treat multibyte constants like
// 'MooV' as characters! This form is deprecated but still exists.
if (ExprTy == S.Context.IntTy)
if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
ExprTy = S.Context.CharTy;
}
// Look through enums to their underlying type.
bool IsEnum = false;
if (auto EnumTy = ExprTy->getAs<EnumType>()) {
ExprTy = EnumTy->getDecl()->getIntegerType();
IsEnum = true;
}
// %C in an Objective-C context prints a unichar, not a wchar_t.
// If the argument is an integer of some kind, believe the %C and suggest
// a cast instead of changing the conversion specifier.
QualType IntendedTy = ExprTy;
if (ObjCContext &&
FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
!ExprTy->isCharType()) {
// 'unichar' is defined as a typedef of unsigned short, but we should
// prefer using the typedef if it is visible.
IntendedTy = S.Context.UnsignedShortTy;
// While we are here, check if the value is an IntegerLiteral that happens
// to be within the valid range.
if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
const llvm::APInt &V = IL->getValue();
if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
return true;
}
LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
Sema::LookupOrdinaryName);
if (S.LookupName(Result, S.getCurScope())) {
NamedDecl *ND = Result.getFoundDecl();
if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
if (TD->getUnderlyingType() == IntendedTy)
IntendedTy = S.Context.getTypedefType(TD);
}
}
}
// Special-case some of Darwin's platform-independence types by suggesting
// casts to primitive types that are known to be large enough.
bool ShouldNotPrintDirectly = false; StringRef CastTyName;
if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
QualType CastTy;
std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
if (!CastTy.isNull()) {
IntendedTy = CastTy;
ShouldNotPrintDirectly = true;
}
}
// We may be able to offer a FixItHint if it is a supported type.
PrintfSpecifier fixedFS = FS;
bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
S.Context, ObjCContext);
if (success) {
// Get the fix string from the fixed format specifier
SmallString<16> buf;
llvm::raw_svector_ostream os(buf);
fixedFS.toString(os);
CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
if (match == analyze_format_string::ArgType::NoMatchPedantic) {
diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
}
// In this case, the specifier is wrong and should be changed to match
// the argument.
EmitFormatDiagnostic(S.PDiag(diag)
<< AT.getRepresentativeTypeName(S.Context)
<< IntendedTy << IsEnum << E->getSourceRange(),
E->getLocStart(),
/*IsStringLocation*/ false, SpecRange,
FixItHint::CreateReplacement(SpecRange, os.str()));
} else {
// The canonical type for formatting this value is different from the
// actual type of the expression. (This occurs, for example, with Darwin's
// NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
// should be printed as 'long' for 64-bit compatibility.)
// Rather than emitting a normal format/argument mismatch, we want to
// add a cast to the recommended type (and correct the format string
// if necessary).
SmallString<16> CastBuf;
llvm::raw_svector_ostream CastFix(CastBuf);
CastFix << "(";
IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
CastFix << ")";
SmallVector<FixItHint,4> Hints;
if (!AT.matchesType(S.Context, IntendedTy))
Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
// If there's already a cast present, just replace it.
SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
} else if (!requiresParensToAddCast(E)) {
// If the expression has high enough precedence,
// just write the C-style cast.
Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
CastFix.str()));
} else {
// Otherwise, add parens around the expression as well as the cast.
CastFix << "(";
Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
CastFix.str()));
SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Hints.push_back(FixItHint::CreateInsertion(After, ")"));
}
if (ShouldNotPrintDirectly) {
// The expression has a type that should not be printed directly.
// We extract the name from the typedef because we don't want to show
// the underlying type in the diagnostic.
StringRef Name;
if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
Name = TypedefTy->getDecl()->getName();
else
Name = CastTyName;
EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
<< Name << IntendedTy << IsEnum
<< E->getSourceRange(),
E->getLocStart(), /*IsStringLocation=*/false,
SpecRange, Hints);
} else {
// In this case, the expression could be printed using a different
// specifier, but we've decided that the specifier is probably correct
// and we should cast instead. Just use the normal warning message.
EmitFormatDiagnostic(
S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
<< AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
<< E->getSourceRange(),
E->getLocStart(), /*IsStringLocation*/false,
SpecRange, Hints);
}
}
} else {
const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
SpecifierLen);
// Since the warning for passing non-POD types to variadic functions
// was deferred until now, we emit a warning for non-POD
// arguments here.
switch (S.isValidVarArgType(ExprTy)) {
case Sema::VAK_Valid:
case Sema::VAK_ValidInCXX11: {
unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
if (match == analyze_printf::ArgType::NoMatchPedantic) {
diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
}
EmitFormatDiagnostic(
S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
<< IsEnum << CSR << E->getSourceRange(),
E->getLocStart(), /*IsStringLocation*/ false, CSR);
break;
}
case Sema::VAK_Undefined:
case Sema::VAK_MSVCUndefined:
EmitFormatDiagnostic(
S.PDiag(diag::warn_non_pod_vararg_with_format_string)
<< S.getLangOpts().CPlusPlus11
<< ExprTy
<< CallType
<< AT.getRepresentativeTypeName(S.Context)
<< CSR
<< E->getSourceRange(),
E->getLocStart(), /*IsStringLocation*/false, CSR);
checkForCStrMembers(AT, E);
break;
case Sema::VAK_Invalid:
if (ExprTy->isObjCObjectType())
EmitFormatDiagnostic(
S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
<< S.getLangOpts().CPlusPlus11
<< ExprTy
<< CallType
<< AT.getRepresentativeTypeName(S.Context)
<< CSR
<< E->getSourceRange(),
E->getLocStart(), /*IsStringLocation*/false, CSR);
else
// FIXME: If this is an initializer list, suggest removing the braces
// or inserting a cast to the target type.
S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
<< isa<InitListExpr>(E) << ExprTy << CallType
<< AT.getRepresentativeTypeName(S.Context)
<< E->getSourceRange();
break;
}
assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
"format string specifier index out of range");
CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
}
return true;
}
//===--- CHECK: Scanf format string checking ------------------------------===//
namespace {
class CheckScanfHandler : public CheckFormatHandler {
public:
CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
const Expr *origFormatExpr, unsigned firstDataArg,
unsigned numDataArgs, const char *beg, bool hasVAListArg,
ArrayRef<const Expr *> Args,
unsigned formatIdx, bool inFunctionCall,
Sema::VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg)
: CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
numDataArgs, beg, hasVAListArg,
Args, formatIdx, inFunctionCall, CallType,
CheckedVarArgs, UncoveredArg)
{}
bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) override;
bool HandleInvalidScanfConversionSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) override;
void HandleIncompleteScanList(const char *start, const char *end) override;
};
} // end anonymous namespace
void CheckScanfHandler::HandleIncompleteScanList(const char *start,
const char *end) {
EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
getLocationOfByte(end), /*IsStringLocation*/true,
getSpecifierRange(start, end - start));
}
bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
const analyze_scanf::ScanfConversionSpecifier &CS =
FS.getConversionSpecifier();
return HandleInvalidConversionSpecifier(FS.getArgIndex(),
getLocationOfByte(CS.getStart()),
startSpecifier, specifierLen,
CS.getStart(), CS.getLength());
}
bool CheckScanfHandler::HandleScanfSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
using namespace analyze_scanf;
using namespace analyze_format_string;
const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
// Handle case where '%' and '*' don't consume an argument. These shouldn't
// be used to decide if we are using positional arguments consistently.
if (FS.consumesDataArgument()) {
if (atFirstArg) {
atFirstArg = false;
usesPositionalArgs = FS.usesPositionalArg();
}
else if (usesPositionalArgs != FS.usesPositionalArg()) {
HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
startSpecifier, specifierLen);
return false;
}
}
// Check if the field with is non-zero.
const OptionalAmount &Amt = FS.getFieldWidth();
if (Amt.getHowSpecified() == OptionalAmount::Constant) {
if (Amt.getConstantAmount() == 0) {
const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
Amt.getConstantLength());
EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
getLocationOfByte(Amt.getStart()),
/*IsStringLocation*/true, R,
FixItHint::CreateRemoval(R));
}
}
if (!FS.consumesDataArgument()) {
// FIXME: Technically specifying a precision or field width here
// makes no sense. Worth issuing a warning at some point.
return true;
}
// Consume the argument.
unsigned argIndex = FS.getArgIndex();
if (argIndex < NumDataArgs) {
// The check to see if the argIndex is valid will come later.
// We set the bit here because we may exit early from this
// function if we encounter some other error.
CoveredArgs.set(argIndex);
}
// Check the length modifier is valid with the given conversion specifier.
if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
diag::warn_format_nonsensical_length);
else if (!FS.hasStandardLengthModifier())
HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
else if (!FS.hasStandardLengthConversionCombination())
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
diag::warn_format_non_standard_conversion_spec);
if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
// The remaining checks depend on the data arguments.
if (HasVAListArg)
return true;
if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
return false;
// Check that the argument type matches the format specifier.
const Expr *Ex = getDataArg(argIndex);
if (!Ex)
return true;
const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
if (!AT.isValid()) {
return true;
}
analyze_format_string::ArgType::MatchKind match =
AT.matchesType(S.Context, Ex->getType());
if (match == analyze_format_string::ArgType::Match) {
return true;
}
ScanfSpecifier fixedFS = FS;
bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
S.getLangOpts(), S.Context);
unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
if (match == analyze_format_string::ArgType::NoMatchPedantic) {
diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
}
if (success) {
// Get the fix string from the fixed format specifier.
SmallString<128> buf;
llvm::raw_svector_ostream os(buf);
fixedFS.toString(os);
EmitFormatDiagnostic(
S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
<< Ex->getType() << false << Ex->getSourceRange(),
Ex->getLocStart(),
/*IsStringLocation*/ false,
getSpecifierRange(startSpecifier, specifierLen),
FixItHint::CreateReplacement(
getSpecifierRange(startSpecifier, specifierLen), os.str()));
} else {
EmitFormatDiagnostic(S.PDiag(diag)
<< AT.getRepresentativeTypeName(S.Context)
<< Ex->getType() << false << Ex->getSourceRange(),
Ex->getLocStart(),
/*IsStringLocation*/ false,
getSpecifierRange(startSpecifier, specifierLen));
}
return true;
}
static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
const Expr *OrigFormatExpr,
ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg,
Sema::FormatStringType Type,
bool inFunctionCall,
Sema::VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg) {
// CHECK: is the format string a wide literal?
if (!FExpr->isAscii() && !FExpr->isUTF8()) {
CheckFormatHandler::EmitFormatDiagnostic(
S, inFunctionCall, Args[format_idx],
S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
/*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
return;
}
// Str - The format string. NOTE: this is NOT null-terminated!
StringRef StrRef = FExpr->getString();
const char *Str = StrRef.data();
// Account for cases where the string literal is truncated in a declaration.
const ConstantArrayType *T =
S.Context.getAsConstantArrayType(FExpr->getType());
assert(T && "String literal not of constant array type!");
size_t TypeSize = T->getSize().getZExtValue();
size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
const unsigned numDataArgs = Args.size() - firstDataArg;
// Emit a warning if the string literal is truncated and does not contain an
// embedded null character.
if (TypeSize <= StrRef.size() &&
StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
CheckFormatHandler::EmitFormatDiagnostic(
S, inFunctionCall, Args[format_idx],
S.PDiag(diag::warn_printf_format_string_not_null_terminated),
FExpr->getLocStart(),
/*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
return;
}
// CHECK: empty format string?
if (StrLen == 0 && numDataArgs > 0) {
CheckFormatHandler::EmitFormatDiagnostic(
S, inFunctionCall, Args[format_idx],
S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
/*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
return;
}
if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
numDataArgs, (Type == Sema::FST_NSString ||
Type == Sema::FST_OSTrace),
Str, HasVAListArg, Args, format_idx,
inFunctionCall, CallType, CheckedVarArgs,
UncoveredArg);
if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
S.getLangOpts(),
S.Context.getTargetInfo(),
Type == Sema::FST_FreeBSDKPrintf))
H.DoneProcessing();
} else if (Type == Sema::FST_Scanf) {
CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Str, HasVAListArg, Args, format_idx,
inFunctionCall, CallType, CheckedVarArgs,
UncoveredArg);
if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
S.getLangOpts(),
S.Context.getTargetInfo()))
H.DoneProcessing();
} // TODO: handle other formats
}
bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
// Str - The format string. NOTE: this is NOT null-terminated!
StringRef StrRef = FExpr->getString();
const char *Str = StrRef.data();
// Account for cases where the string literal is truncated in a declaration.
const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
assert(T && "String literal not of constant array type!");
size_t TypeSize = T->getSize().getZExtValue();
size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
getLangOpts(),
Context.getTargetInfo());
}
//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
// Returns the related absolute value function that is larger, of 0 if one
// does not exist.
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
switch (AbsFunction) {
default:
return 0;
case Builtin::BI__builtin_abs:
return Builtin::BI__builtin_labs;
case Builtin::BI__builtin_labs:
return Builtin::BI__builtin_llabs;
case Builtin::BI__builtin_llabs:
return 0;
case Builtin::BI__builtin_fabsf:
return Builtin::BI__builtin_fabs;
case Builtin::BI__builtin_fabs:
return Builtin::BI__builtin_fabsl;
case Builtin::BI__builtin_fabsl:
return 0;
case Builtin::BI__builtin_cabsf:
return Builtin::BI__builtin_cabs;
case Builtin::BI__builtin_cabs:
return Builtin::BI__builtin_cabsl;
case Builtin::BI__builtin_cabsl:
return 0;
case Builtin::BIabs:
return Builtin::BIlabs;
case Builtin::BIlabs:
return Builtin::BIllabs;
case Builtin::BIllabs:
return 0;
case Builtin::BIfabsf:
return Builtin::BIfabs;
case Builtin::BIfabs:
return Builtin::BIfabsl;
case Builtin::BIfabsl:
return 0;
case Builtin::BIcabsf:
return Builtin::BIcabs;
case Builtin::BIcabs:
return Builtin::BIcabsl;
case Builtin::BIcabsl:
return 0;
}
}
// Returns the argument type of the absolute value function.
static QualType getAbsoluteValueArgumentType(ASTContext &Context,
unsigned AbsType) {
if (AbsType == 0)
return QualType();
ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
if (Error != ASTContext::GE_None)
return QualType();
const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
if (!FT)
return QualType();
if (FT->getNumParams() != 1)
return QualType();
return FT->getParamType(0);
}
// Returns the best absolute value function, or zero, based on type and
// current absolute value function.
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
unsigned AbsFunctionKind) {
unsigned BestKind = 0;
uint64_t ArgSize = Context.getTypeSize(ArgType);
for (unsigned Kind = AbsFunctionKind; Kind != 0;
Kind = getLargerAbsoluteValueFunction(Kind)) {
QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
if (Context.getTypeSize(ParamType) >= ArgSize) {
if (BestKind == 0)
BestKind = Kind;
else if (Context.hasSameType(ParamType, ArgType)) {
BestKind = Kind;
break;
}
}
}
return BestKind;
}
enum AbsoluteValueKind {
AVK_Integer,
AVK_Floating,
AVK_Complex
};
static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
if (T->isIntegralOrEnumerationType())
return AVK_Integer;
if (T->isRealFloatingType())
return AVK_Floating;
if (T->isAnyComplexType())
return AVK_Complex;
llvm_unreachable("Type not integer, floating, or complex");
}
// Changes the absolute value function to a different type. Preserves whether
// the function is a builtin.
static unsigned changeAbsFunction(unsigned AbsKind,
AbsoluteValueKind ValueKind) {
switch (ValueKind) {
case AVK_Integer:
switch (AbsKind) {
default:
return 0;
case Builtin::BI__builtin_fabsf:
case Builtin::BI__builtin_fabs:
case Builtin::BI__builtin_fabsl:
case Builtin::BI__builtin_cabsf:
case Builtin::BI__builtin_cabs:
case Builtin::BI__builtin_cabsl:
return Builtin::BI__builtin_abs;
case Builtin::BIfabsf:
case Builtin::BIfabs:
case Builtin::BIfabsl:
case Builtin::BIcabsf:
case Builtin::BIcabs:
case Builtin::BIcabsl:
return Builtin::BIabs;
}
case AVK_Floating:
switch (AbsKind) {
default:
return 0;
case Builtin::BI__builtin_abs:
case Builtin::BI__builtin_labs:
case Builtin::BI__builtin_llabs:
case Builtin::BI__builtin_cabsf:
case Builtin::BI__builtin_cabs:
case Builtin::BI__builtin_cabsl:
return Builtin::BI__builtin_fabsf;
case Builtin::BIabs:
case Builtin::BIlabs:
case Builtin::BIllabs:
case Builtin::BIcabsf:
case Builtin::BIcabs:
case Builtin::BIcabsl:
return Builtin::BIfabsf;
}
case AVK_Complex:
switch (AbsKind) {
default:
return 0;
case Builtin::BI__builtin_abs:
case Builtin::BI__builtin_labs:
case Builtin::BI__builtin_llabs:
case Builtin::BI__builtin_fabsf:
case Builtin::BI__builtin_fabs:
case Builtin::BI__builtin_fabsl:
return Builtin::BI__builtin_cabsf;
case Builtin::BIabs:
case Builtin::BIlabs:
case Builtin::BIllabs:
case Builtin::BIfabsf:
case Builtin::BIfabs:
case Builtin::BIfabsl:
return Builtin::BIcabsf;
}
}
llvm_unreachable("Unable to convert function");
}
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
const IdentifierInfo *FnInfo = FDecl->getIdentifier();
if (!FnInfo)
return 0;
switch (FDecl->getBuiltinID()) {
default:
return 0;
case Builtin::BI__builtin_abs:
case Builtin::BI__builtin_fabs:
case Builtin::BI__builtin_fabsf:
case Builtin::BI__builtin_fabsl:
case Builtin::BI__builtin_labs:
case Builtin::BI__builtin_llabs:
case Builtin::BI__builtin_cabs:
case Builtin::BI__builtin_cabsf:
case Builtin::BI__builtin_cabsl:
case Builtin::BIabs:
case Builtin::BIlabs:
case Builtin::BIllabs:
case Builtin::BIfabs:
case Builtin::BIfabsf:
case Builtin::BIfabsl:
case Builtin::BIcabs:
case Builtin::BIcabsf:
case Builtin::BIcabsl:
return FDecl->getBuiltinID();
}
llvm_unreachable("Unknown Builtin type");
}
// If the replacement is valid, emit a note with replacement function.
// Additionally, suggest including the proper header if not already included.
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
unsigned AbsKind, QualType ArgType) {
bool EmitHeaderHint = true;
const char *HeaderName = nullptr;
const char *FunctionName = nullptr;
if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
FunctionName = "std::abs";
if (ArgType->isIntegralOrEnumerationType()) {
HeaderName = "cstdlib";
} else if (ArgType->isRealFloatingType()) {
HeaderName = "cmath";
} else {
llvm_unreachable("Invalid Type");
}
// Lookup all std::abs
if (NamespaceDecl *Std = S.getStdNamespace()) {
LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
R.suppressDiagnostics();
S.LookupQualifiedName(R, Std);
for (const auto *I : R) {
const FunctionDecl *FDecl = nullptr;
if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
} else {
FDecl = dyn_cast<FunctionDecl>(I);
}
if (!FDecl)
continue;
// Found std::abs(), check that they are the right ones.
if (FDecl->getNumParams() != 1)
continue;
// Check that the parameter type can handle the argument.
QualType ParamType = FDecl->getParamDecl(0)->getType();
if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
S.Context.getTypeSize(ArgType) <=
S.Context.getTypeSize(ParamType)) {
// Found a function, don't need the header hint.
EmitHeaderHint = false;
break;
}
}
}
} else {
FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
if (HeaderName) {
DeclarationName DN(&S.Context.Idents.get(FunctionName));
LookupResult R(S, DN, Loc, Sema::LookupAnyName);
R.suppressDiagnostics();
S.LookupName(R, S.getCurScope());
if (R.isSingleResult()) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
if (FD && FD->getBuiltinID() == AbsKind) {
EmitHeaderHint = false;
} else {
return;
}
} else if (!R.empty()) {
return;
}
}
}
S.Diag(Loc, diag::note_replace_abs_function)
<< FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
if (!HeaderName)
return;
if (!EmitHeaderHint)
return;
S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
<< FunctionName;
}
static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
if (!FDecl)
return false;
if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
return false;
const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
while (ND && ND->isInlineNamespace()) {
ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
}
if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
return false;
if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
return false;
return true;
}
// Warn when using the wrong abs() function.
void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl,
IdentifierInfo *FnInfo) {
if (Call->getNumArgs() != 1)
return;
unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
bool IsStdAbs = IsFunctionStdAbs(FDecl);
if (AbsKind == 0 && !IsStdAbs)
return;
QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
QualType ParamType = Call->getArg(0)->getType();
// Unsigned types cannot be negative. Suggest removing the absolute value
// function call.
if (ArgType->isUnsignedIntegerType()) {
const char *FunctionName =
IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
Diag(Call->getExprLoc(), diag::note_remove_abs)
<< FunctionName
<< FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
return;
}
// Taking the absolute value of a pointer is very suspicious, they probably
// wanted to index into an array, dereference a pointer, call a function, etc.
if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
unsigned DiagType = 0;
if (ArgType->isFunctionType())
DiagType = 1;
else if (ArgType->isArrayType())
DiagType = 2;
Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
return;
}
// std::abs has overloads which prevent most of the absolute value problems
// from occurring.
if (IsStdAbs)
return;
AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
// The argument and parameter are the same kind. Check if they are the right
// size.
if (ArgValueKind == ParamValueKind) {
if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
return;
unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
Diag(Call->getExprLoc(), diag::warn_abs_too_small)
<< FDecl << ArgType << ParamType;
if (NewAbsKind == 0)
return;
emitReplacement(*this, Call->getExprLoc(),
Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
return;
}
// ArgValueKind != ParamValueKind
// The wrong type of absolute value function was used. Attempt to find the
// proper one.
unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
if (NewAbsKind == 0)
return;
Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
<< FDecl << ParamValueKind << ArgValueKind;
emitReplacement(*this, Call->getExprLoc(),
Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
}
//===--- CHECK: Standard memory functions ---------------------------------===//
/// \brief Takes the expression passed to the size_t parameter of functions
/// such as memcmp, strncat, etc and warns if it's a comparison.
///
/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
IdentifierInfo *FnName,
SourceLocation FnLoc,
SourceLocation RParenLoc) {
const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
if (!Size)
return false;
// if E is binop and op is >, <, >=, <=, ==, &&, ||:
if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
return false;
SourceRange SizeRange = Size->getSourceRange();
S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
<< SizeRange << FnName;
S.Diag(FnLoc, diag::note_memsize_comparison_paren)
<< FnName << FixItHint::CreateInsertion(
S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
<< FixItHint::CreateRemoval(RParenLoc);
S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
<< FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
<< FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
")");
return true;
}
/// \brief Determine whether the given type is or contains a dynamic class type
/// (e.g., whether it has a vtable).
static const CXXRecordDecl *getContainedDynamicClass(QualType T,
bool &IsContained) {
// Look through array types while ignoring qualifiers.
const Type *Ty = T->getBaseElementTypeUnsafe();
IsContained = false;
const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
RD = RD ? RD->getDefinition() : nullptr;
if (!RD || RD->isInvalidDecl())
return nullptr;
if (RD->isDynamicClass())
return RD;
// Check all the fields. If any bases were dynamic, the class is dynamic.
// It's impossible for a class to transitively contain itself by value, so
// infinite recursion is impossible.
for (auto *FD : RD->fields()) {
bool SubContained;
if (const CXXRecordDecl *ContainedRD =
getContainedDynamicClass(FD->getType(), SubContained)) {
IsContained = true;
return ContainedRD;
}
}
return nullptr;
}
/// \brief If E is a sizeof expression, returns its argument expression,
/// otherwise returns NULL.
static const Expr *getSizeOfExprArg(const Expr *E) {
if (const UnaryExprOrTypeTraitExpr *SizeOf =
dyn_cast<UnaryExprOrTypeTraitExpr>(E))
if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
return nullptr;
}
/// \brief If E is a sizeof expression, returns its argument type.
static QualType getSizeOfArgType(const Expr *E) {
if (const UnaryExprOrTypeTraitExpr *SizeOf =
dyn_cast<UnaryExprOrTypeTraitExpr>(E))
if (SizeOf->getKind() == clang::UETT_SizeOf)
return SizeOf->getTypeOfArgument();
return QualType();
}
/// \brief Check for dangerous or invalid arguments to memset().
///
/// This issues warnings on known problematic, dangerous or unspecified
/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
/// function calls.
///
/// \param Call The call expression to diagnose.
void Sema::CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName) {
assert(BId != 0);
// It is possible to have a non-standard definition of memset. Validate
// we have enough arguments, and if not, abort further checking.
unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
if (Call->getNumArgs() < ExpectedNumArgs)
return;
unsigned LastArg = (BId == Builtin::BImemset ||
BId == Builtin::BIstrndup ? 1 : 2);
unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Call->getLocStart(), Call->getRParenLoc()))
return;
// We have special checking when the length is a sizeof expression.
QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
llvm::FoldingSetNodeID SizeOfArgID;
for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
QualType DestTy = Dest->getType();
QualType PointeeTy;
if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
PointeeTy = DestPtrTy->getPointeeType();
// Never warn about void type pointers. This can be used to suppress
// false positives.
if (PointeeTy->isVoidType())
continue;
// Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
// actually comparing the expressions for equality. Because computing the
// expression IDs can be expensive, we only do this if the diagnostic is
// enabled.
if (SizeOfArg &&
!Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
SizeOfArg->getExprLoc())) {
// We only compute IDs for expressions if the warning is enabled, and
// cache the sizeof arg's ID.
if (SizeOfArgID == llvm::FoldingSetNodeID())
SizeOfArg->Profile(SizeOfArgID, Context, true);
llvm::FoldingSetNodeID DestID;
Dest->Profile(DestID, Context, true);
if (DestID == SizeOfArgID) {
// TODO: For strncpy() and friends, this could suggest sizeof(dst)
// over sizeof(src) as well.
unsigned ActionIdx = 0; // Default is to suggest dereferencing.
StringRef ReadableName = FnName->getName();
if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
if (UnaryOp->getOpcode() == UO_AddrOf)
ActionIdx = 1; // If its an address-of operator, just remove it.
if (!PointeeTy->isIncompleteType() &&
(Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
ActionIdx = 2; // If the pointee's size is sizeof(char),
// suggest an explicit length.
// If the function is defined as a builtin macro, do not show macro
// expansion.
SourceLocation SL = SizeOfArg->getExprLoc();
SourceRange DSR = Dest->getSourceRange();
SourceRange SSR = SizeOfArg->getSourceRange();
SourceManager &SM = getSourceManager();
if (SM.isMacroArgExpansion(SL)) {
ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
SL = SM.getSpellingLoc(SL);
DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
SM.getSpellingLoc(DSR.getEnd()));
SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
SM.getSpellingLoc(SSR.getEnd()));
}
DiagRuntimeBehavior(SL, SizeOfArg,
PDiag(diag::warn_sizeof_pointer_expr_memaccess)
<< ReadableName
<< PointeeTy
<< DestTy
<< DSR
<< SSR);
DiagRuntimeBehavior(SL, SizeOfArg,
PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
<< ActionIdx
<< SSR);
break;
}
}
// Also check for cases where the sizeof argument is the exact same
// type as the memory argument, and where it points to a user-defined
// record type.
if (SizeOfArgTy != QualType()) {
if (PointeeTy->isRecordType() &&
Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
PDiag(diag::warn_sizeof_pointer_type_memaccess)
<< FnName << SizeOfArgTy << ArgIdx
<< PointeeTy << Dest->getSourceRange()
<< LenExpr->getSourceRange());
break;
}
}
} else if (DestTy->isArrayType()) {
PointeeTy = DestTy;
}
if (PointeeTy == QualType())
continue;
// Always complain about dynamic classes.
bool IsContained;
if (const CXXRecordDecl *ContainedRD =
getContainedDynamicClass(PointeeTy, IsContained)) {
unsigned OperationType = 0;
// "overwritten" if we're warning about the destination for any call
// but memcmp; otherwise a verb appropriate to the call.
if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
if (BId == Builtin::BImemcpy)
OperationType = 1;
else if(BId == Builtin::BImemmove)
OperationType = 2;
else if (BId == Builtin::BImemcmp)
OperationType = 3;
}
DiagRuntimeBehavior(
Dest->getExprLoc(), Dest,
PDiag(diag::warn_dyn_class_memaccess)
<< (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
<< FnName << IsContained << ContainedRD << OperationType
<< Call->getCallee()->getSourceRange());
} else if (PointeeTy.hasNonTrivialObjCLifetime() &&
BId != Builtin::BImemset)
DiagRuntimeBehavior(
Dest->getExprLoc(), Dest,
PDiag(diag::warn_arc_object_memaccess)
<< ArgIdx << FnName << PointeeTy
<< Call->getCallee()->getSourceRange());
else
continue;
DiagRuntimeBehavior(
Dest->getExprLoc(), Dest,
PDiag(diag::note_bad_memaccess_silence)
<< FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
break;
}
}
// A little helper routine: ignore addition and subtraction of integer literals.
// This intentionally does not ignore all integer constant expressions because
// we don't want to remove sizeof().
static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
Ex = Ex->IgnoreParenCasts();
for (;;) {
const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
if (!BO || !BO->isAdditiveOp())
break;
const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
if (isa<IntegerLiteral>(RHS))
Ex = LHS;
else if (isa<IntegerLiteral>(LHS))
Ex = RHS;
else
break;
}
return Ex;
}
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
ASTContext &Context) {
// Only handle constant-sized or VLAs, but not flexible members.
if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
// Only issue the FIXIT for arrays of size > 1.
if (CAT->getSize().getSExtValue() <= 1)
return false;
} else if (!Ty->isVariableArrayType()) {
return false;
}
return true;
}
// Warn if the user has made the 'size' argument to strlcpy or strlcat
// be the size of the source, instead of the destination.
void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName) {
// Don't crash if the user has the wrong number of arguments
unsigned NumArgs = Call->getNumArgs();
if ((NumArgs != 3) && (NumArgs != 4))
return;
const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
const Expr *CompareWithSrc = nullptr;
if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Call->getLocStart(), Call->getRParenLoc()))
return;
// Look for 'strlcpy(dst, x, sizeof(x))'
if (const Expr *Ex = getSizeOfExprArg(SizeArg))
CompareWithSrc = Ex;
else {
// Look for 'strlcpy(dst, x, strlen(x))'
if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
SizeCall->getNumArgs() == 1)
CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
}
}
if (!CompareWithSrc)
return;
// Determine if the argument to sizeof/strlen is equal to the source
// argument. In principle there's all kinds of things you could do
// here, for instance creating an == expression and evaluating it with
// EvaluateAsBooleanCondition, but this uses a more direct technique:
const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
if (!SrcArgDRE)
return;
const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
if (!CompareWithSrcDRE ||
SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
return;
const Expr *OriginalSizeArg = Call->getArg(2);
Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
<< OriginalSizeArg->getSourceRange() << FnName;
// Output a FIXIT hint if the destination is an array (rather than a
// pointer to an array). This could be enhanced to handle some
// pointers if we know the actual size, like if DstArg is 'array+2'
// we could say 'sizeof(array)-2'.
const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
return;
SmallString<128> sizeString;
llvm::raw_svector_ostream OS(sizeString);
OS << "sizeof(";
DstArg->printPretty(OS, nullptr, getPrintingPolicy());
OS << ")";
Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
<< FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
OS.str());
}
/// Check if two expressions refer to the same declaration.
static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
return D1->getDecl() == D2->getDecl();
return false;
}
static const Expr *getStrlenExprArg(const Expr *E) {
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
const FunctionDecl *FD = CE->getDirectCallee();
if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
return nullptr;
return CE->getArg(0)->IgnoreParenCasts();
}
return nullptr;
}
// Warn on anti-patterns as the 'size' argument to strncat.
// The correct size argument should look like following:
// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
void Sema::CheckStrncatArguments(const CallExpr *CE,
IdentifierInfo *FnName) {
// Don't crash if the user has the wrong number of arguments.
if (CE->getNumArgs() < 3)
return;
const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
CE->getRParenLoc()))
return;
// Identify common expressions, which are wrongly used as the size argument
// to strncat and may lead to buffer overflows.
unsigned PatternType = 0;
if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
// - sizeof(dst)
if (referToTheSameDecl(SizeOfArg, DstArg))
PatternType = 1;
// - sizeof(src)
else if (referToTheSameDecl(SizeOfArg, SrcArg))
PatternType = 2;
} else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
if (BE->getOpcode() == BO_Sub) {
const Expr *L = BE->getLHS()->IgnoreParenCasts();
const Expr *R = BE->getRHS()->IgnoreParenCasts();
// - sizeof(dst) - strlen(dst)
if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
referToTheSameDecl(DstArg, getStrlenExprArg(R)))
PatternType = 1;
// - sizeof(src) - (anything)
else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
PatternType = 2;
}
}
if (PatternType == 0)
return;
// Generate the diagnostic.
SourceLocation SL = LenArg->getLocStart();
SourceRange SR = LenArg->getSourceRange();
SourceManager &SM = getSourceManager();
// If the function is defined as a builtin macro, do not show macro expansion.
if (SM.isMacroArgExpansion(SL)) {
SL = SM.getSpellingLoc(SL);
SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
SM.getSpellingLoc(SR.getEnd()));
}
// Check if the destination is an array (rather than a pointer to an array).
QualType DstTy = DstArg->getType();
bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
Context);
if (!isKnownSizeArray) {
if (PatternType == 1)
Diag(SL, diag::warn_strncat_wrong_size) << SR;
else
Diag(SL, diag::warn_strncat_src_size) << SR;
return;
}
if (PatternType == 1)
Diag(SL, diag::warn_strncat_large_size) << SR;
else
Diag(SL, diag::warn_strncat_src_size) << SR;
SmallString<128> sizeString;
llvm::raw_svector_ostream OS(sizeString);
OS << "sizeof(";
DstArg->printPretty(OS, nullptr, getPrintingPolicy());
OS << ") - ";
OS << "strlen(";
DstArg->printPretty(OS, nullptr, getPrintingPolicy());
OS << ") - 1";
Diag(SL, diag::note_strncat_wrong_size)
<< FixItHint::CreateReplacement(SR, OS.str());
}
//===--- CHECK: Return Address of Stack Variable --------------------------===//
static const Expr *EvalVal(const Expr *E,
SmallVectorImpl<const DeclRefExpr *> &refVars,
const Decl *ParentDecl);
static const Expr *EvalAddr(const Expr *E,
SmallVectorImpl<const DeclRefExpr *> &refVars,
const Decl *ParentDecl);
/// CheckReturnStackAddr - Check if a return statement returns the address
/// of a stack variable.
static void
CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc) {
const Expr *stackE = nullptr;
SmallVector<const DeclRefExpr *, 8> refVars;
// Perform checking for returned stack addresses, local blocks,
// label addresses or references to temporaries.
if (lhsType->isPointerType() ||
(!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
} else if (lhsType->isReferenceType()) {
stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
}
if (!stackE)
return; // Nothing suspicious was found.
SourceLocation diagLoc;
SourceRange diagRange;
if (refVars.empty()) {
diagLoc = stackE->getLocStart();
diagRange = stackE->getSourceRange();
} else {
// We followed through a reference variable. 'stackE' contains the
// problematic expression but we will warn at the return statement pointing
// at the reference variable. We will later display the "trail" of
// reference variables using notes.
diagLoc = refVars[0]->getLocStart();
diagRange = refVars[0]->getSourceRange();
}
if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
// address of local var
S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
<< DR->getDecl()->getDeclName() << diagRange;
} else if (isa<BlockExpr>(stackE)) { // local block.
S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
} else if (isa<AddrLabelExpr>(stackE)) { // address of label.
S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
} else { // local temporary.
S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
<< lhsType->isReferenceType() << diagRange;
}
// Display the "trail" of reference variables that we followed until we
// found the problematic expression using notes.
for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
// If this var binds to another reference var, show the range of the next
// var, otherwise the var binds to the problematic expression, in which case
// show the range of the expression.
SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
: stackE->getSourceRange();
S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
<< VD->getDeclName() << range;
}
}
/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
/// check if the expression in a return statement evaluates to an address
/// to a location on the stack, a local block, an address of a label, or a
/// reference to local temporary. The recursion is used to traverse the
/// AST of the return expression, with recursion backtracking when we
/// encounter a subexpression that (1) clearly does not lead to one of the
/// above problematic expressions (2) is something we cannot determine leads to
/// a problematic expression based on such local checking.
///
/// Both EvalAddr and EvalVal follow through reference variables to evaluate
/// the expression that they point to. Such variables are added to the
/// 'refVars' vector so that we know what the reference variable "trail" was.
///
/// EvalAddr processes expressions that are pointers that are used as
/// references (and not L-values). EvalVal handles all other values.
/// At the base case of the recursion is a check for the above problematic
/// expressions.
///
/// This implementation handles:
///
/// * pointer-to-pointer casts
/// * implicit conversions from array references to pointers
/// * taking the address of fields
/// * arbitrary interplay between "&" and "*" operators
/// * pointer arithmetic from an address of a stack variable
/// * taking the address of an array element where the array is on the stack
static const Expr *EvalAddr(const Expr *E,
SmallVectorImpl<const DeclRefExpr *> &refVars,
const Decl *ParentDecl) {
if (E->isTypeDependent())
return nullptr;
// We should only be called for evaluating pointer expressions.
assert((E->getType()->isAnyPointerType() ||
E->getType()->isBlockPointerType() ||
E->getType()->isObjCQualifiedIdType()) &&
"EvalAddr only works on pointers");
E = E->IgnoreParens();
// Our "symbolic interpreter" is just a dispatch off the currently
// viewed AST node. We then recursively traverse the AST by calling
// EvalAddr and EvalVal appropriately.
switch (E->getStmtClass()) {
case Stmt::DeclRefExprClass: {
const DeclRefExpr *DR = cast<DeclRefExpr>(E);
// If we leave the immediate function, the lifetime isn't about to end.
if (DR->refersToEnclosingVariableOrCapture())
return nullptr;
if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
// If this is a reference variable, follow through to the expression that
// it points to.
if (V->hasLocalStorage() &&
V->getType()->isReferenceType() && V->hasInit()) {
// Add the reference variable to the "trail".
refVars.push_back(DR);
return EvalAddr(V->getInit(), refVars, ParentDecl);
}
return nullptr;
}
case Stmt::UnaryOperatorClass: {
// The only unary operator that make sense to handle here
// is AddrOf. All others don't make sense as pointers.
const UnaryOperator *U = cast<UnaryOperator>(E);
if (U->getOpcode() == UO_AddrOf)
return EvalVal(U->getSubExpr(), refVars, ParentDecl);
return nullptr;
}
case Stmt::BinaryOperatorClass: {
// Handle pointer arithmetic. All other binary operators are not valid
// in this context.
const BinaryOperator *B = cast<BinaryOperator>(E);
BinaryOperatorKind op = B->getOpcode();
if (op != BO_Add && op != BO_Sub)
return nullptr;
const Expr *Base = B->getLHS();
// Determine which argument is the real pointer base. It could be
// the RHS argument instead of the LHS.
if (!Base->getType()->isPointerType())
Base = B->getRHS();
assert(Base->getType()->isPointerType());
return EvalAddr(Base, refVars, ParentDecl);
}
// For conditional operators we need to see if either the LHS or RHS are
// valid DeclRefExpr*s. If one of them is valid, we return it.
case Stmt::ConditionalOperatorClass: {
const ConditionalOperator *C = cast<ConditionalOperator>(E);
// Handle the GNU extension for missing LHS.
// FIXME: That isn't a ConditionalOperator, so doesn't get here.
if (const Expr *LHSExpr = C->getLHS()) {
// In C++, we can have a throw-expression, which has 'void' type.
if (!LHSExpr->getType()->isVoidType())
if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
return LHS;
}
// In C++, we can have a throw-expression, which has 'void' type.
if (C->getRHS()->getType()->isVoidType())
return nullptr;
return EvalAddr(C->getRHS(), refVars, ParentDecl);
}
case Stmt::BlockExprClass:
if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
return E; // local block.
return nullptr;
case Stmt::AddrLabelExprClass:
return E; // address of label.
case Stmt::ExprWithCleanupsClass:
return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
ParentDecl);
// For casts, we need to handle conversions from arrays to
// pointer values, and pointer-to-pointer conversions.
case Stmt::ImplicitCastExprClass:
case Stmt::CStyleCastExprClass:
case Stmt::CXXFunctionalCastExprClass:
case Stmt::ObjCBridgedCastExprClass:
case Stmt::CXXStaticCastExprClass:
case Stmt::CXXDynamicCastExprClass:
case Stmt::CXXConstCastExprClass:
case Stmt::CXXReinterpretCastExprClass: {
const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
switch (cast<CastExpr>(E)->getCastKind()) {
case CK_LValueToRValue:
case CK_NoOp:
case CK_BaseToDerived:
case CK_DerivedToBase:
case CK_UncheckedDerivedToBase:
case CK_Dynamic:
case CK_CPointerToObjCPointerCast:
case CK_BlockPointerToObjCPointerCast:
case CK_AnyPointerToBlockPointerCast:
return EvalAddr(SubExpr, refVars, ParentDecl);
case CK_ArrayToPointerDecay:
return EvalVal(SubExpr, refVars, ParentDecl);
case CK_BitCast:
if (SubExpr->getType()->isAnyPointerType() ||
SubExpr->getType()->isBlockPointerType() ||
SubExpr->getType()->isObjCQualifiedIdType())
return EvalAddr(SubExpr, refVars, ParentDecl);
else
return nullptr;
default:
return nullptr;
}
}
case Stmt::MaterializeTemporaryExprClass:
if (const Expr *Result =
EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
refVars, ParentDecl))
return Result;
return E;
// Everything else: we simply don't reason about them.
default:
return nullptr;
}
}
/// EvalVal - This function is complements EvalAddr in the mutual recursion.
/// See the comments for EvalAddr for more details.
static const Expr *EvalVal(const Expr *E,
SmallVectorImpl<const DeclRefExpr *> &refVars,
const Decl *ParentDecl) {
do {
// We should only be called for evaluating non-pointer expressions, or
// expressions with a pointer type that are not used as references but
// instead
// are l-values (e.g., DeclRefExpr with a pointer type).
// Our "symbolic interpreter" is just a dispatch off the currently
// viewed AST node. We then recursively traverse the AST by calling
// EvalAddr and EvalVal appropriately.
E = E->IgnoreParens();
switch (E->getStmtClass()) {
case Stmt::ImplicitCastExprClass: {
const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
if (IE->getValueKind() == VK_LValue) {
E = IE->getSubExpr();
continue;
}
return nullptr;
}
case Stmt::ExprWithCleanupsClass:
return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
ParentDecl);
case Stmt::DeclRefExprClass: {
// When we hit a DeclRefExpr we are looking at code that refers to a
// variable's name. If it's not a reference variable we check if it has
// local storage within the function, and if so, return the expression.
const DeclRefExpr *DR = cast<DeclRefExpr>(E);
// If we leave the immediate function, the lifetime isn't about to end.
if (DR->refersToEnclosingVariableOrCapture())
return nullptr;
if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
// Check if it refers to itself, e.g. "int& i = i;".
if (V == ParentDecl)
return DR;
if (V->hasLocalStorage()) {
if (!V->getType()->isReferenceType())
return DR;
// Reference variable, follow through to the expression that
// it points to.
if (V->hasInit()) {
// Add the reference variable to the "trail".
refVars.push_back(DR);
return EvalVal(V->getInit(), refVars, V);
}
}
}
return nullptr;
}
case Stmt::UnaryOperatorClass: {
// The only unary operator that make sense to handle here
// is Deref. All others don't resolve to a "name." This includes
// handling all sorts of rvalues passed to a unary operator.
const UnaryOperator *U = cast<UnaryOperator>(E);
if (U->getOpcode() == UO_Deref)
return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
return nullptr;
}
case Stmt::ArraySubscriptExprClass: {
// Array subscripts are potential references to data on the stack. We
// retrieve the DeclRefExpr* for the array variable if it indeed
// has local storage.
const auto *ASE = cast<ArraySubscriptExpr>(E);
if (ASE->isTypeDependent())
return nullptr;
return EvalAddr(ASE->getBase(), refVars, ParentDecl);
}
case Stmt::OMPArraySectionExprClass: {
return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
ParentDecl);
}
case Stmt::ConditionalOperatorClass: {
// For conditional operators we need to see if either the LHS or RHS are
// non-NULL Expr's. If one is non-NULL, we return it.
const ConditionalOperator *C = cast<ConditionalOperator>(E);
// Handle the GNU extension for missing LHS.
if (const Expr *LHSExpr = C->getLHS()) {
// In C++, we can have a throw-expression, which has 'void' type.
if (!LHSExpr->getType()->isVoidType())
if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
return LHS;
}
// In C++, we can have a throw-expression, which has 'void' type.
if (C->getRHS()->getType()->isVoidType())
return nullptr;
return EvalVal(C->getRHS(), refVars, ParentDecl);
}
// Accesses to members are potential references to data on the stack.
case Stmt::MemberExprClass: {
const MemberExpr *M = cast<MemberExpr>(E);
// Check for indirect access. We only want direct field accesses.
if (M->isArrow())
return nullptr;
// Check whether the member type is itself a reference, in which case
// we're not going to refer to the member, but to what the member refers
// to.
if (M->getMemberDecl()->getType()->isReferenceType())
return nullptr;
return EvalVal(M->getBase(), refVars, ParentDecl);
}
case Stmt::MaterializeTemporaryExprClass:
if (const Expr *Result =
EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
refVars, ParentDecl))
return Result;
return E;
default:
// Check that we don't return or take the address of a reference to a
// temporary. This is only useful in C++.
if (!E->isTypeDependent() && E->isRValue())
return E;
// Everything else: we simply don't reason about them.
return nullptr;
}
} while (true);
}
void
Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod,
const AttrVec *Attrs,
const FunctionDecl *FD) {
CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
// Check if the return value is null but should not be.
if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
(!isObjCMethod && isNonNullType(Context, lhsType))) &&
CheckNonNullExpr(*this, RetValExp))
Diag(ReturnLoc, diag::warn_null_ret)
<< (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
// C++11 [basic.stc.dynamic.allocation]p4:
// If an allocation function declared with a non-throwing
// exception-specification fails to allocate storage, it shall return
// a null pointer. Any other allocation function that fails to allocate
// storage shall indicate failure only by throwing an exception [...]
if (FD) {
OverloadedOperatorKind Op = FD->getOverloadedOperator();
if (Op == OO_New || Op == OO_Array_New) {
const FunctionProtoType *Proto
= FD->getType()->castAs<FunctionProtoType>();
if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
CheckNonNullExpr(*this, RetValExp))
Diag(ReturnLoc, diag::warn_operator_new_returns_null)
<< FD << getLangOpts().CPlusPlus11;
}
}
}
//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
/// Check for comparisons of floating point operands using != and ==.
/// Issue a warning if these are no self-comparisons, as they are not likely
/// to do what the programmer intended.
void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
// Special case: check for x == x (which is OK).
// Do not emit warnings for such cases.
if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
if (DRL->getDecl() == DRR->getDecl())
return;
// Special case: check for comparisons against literals that can be exactly
// represented by APFloat. In such cases, do not emit a warning. This
// is a heuristic: often comparison against such literals are used to
// detect if a value in a variable has not changed. This clearly can
// lead to false negatives.
if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
if (FLL->isExact())
return;
} else
if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
if (FLR->isExact())
return;
// Check for comparisons with builtin types.
if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
if (CL->getBuiltinCallee())
return;
if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
if (CR->getBuiltinCallee())
return;
// Emit the diagnostic.
Diag(Loc, diag::warn_floatingpoint_eq)
<< LHS->getSourceRange() << RHS->getSourceRange();
}
//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
namespace {
/// Structure recording the 'active' range of an integer-valued
/// expression.
struct IntRange {
/// The number of bits active in the int.
unsigned Width;
/// True if the int is known not to have negative values.
bool NonNegative;
IntRange(unsigned Width, bool NonNegative)
: Width(Width), NonNegative(NonNegative)
{}
/// Returns the range of the bool type.
static IntRange forBoolType() {
return IntRange(1, true);
}
/// Returns the range of an opaque value of the given integral type.
static IntRange forValueOfType(ASTContext &C, QualType T) {
return forValueOfCanonicalType(C,
T->getCanonicalTypeInternal().getTypePtr());
}
/// Returns the range of an opaque value of a canonical integral type.
static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
assert(T->isCanonicalUnqualified());
if (const VectorType *VT = dyn_cast<VectorType>(T))
T = VT->getElementType().getTypePtr();
if (const ComplexType *CT = dyn_cast<ComplexType>(T))
T = CT->getElementType().getTypePtr();
if (const AtomicType *AT = dyn_cast<AtomicType>(T))
T = AT->getValueType().getTypePtr();
// For enum types, use the known bit width of the enumerators.
if (const EnumType *ET = dyn_cast<EnumType>(T)) {
EnumDecl *Enum = ET->getDecl();
if (!Enum->isCompleteDefinition())
return IntRange(C.getIntWidth(QualType(T, 0)), false);
unsigned NumPositive = Enum->getNumPositiveBits();
unsigned NumNegative = Enum->getNumNegativeBits();
if (NumNegative == 0)
return IntRange(NumPositive, true/*NonNegative*/);
else
return IntRange(std::max(NumPositive + 1, NumNegative),
false/*NonNegative*/);
}
const BuiltinType *BT = cast<BuiltinType>(T);
assert(BT->isInteger());
return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
}
/// Returns the "target" range of a canonical integral type, i.e.
/// the range of values expressible in the type.
///
/// This matches forValueOfCanonicalType except that enums have the
/// full range of their type, not the range of their enumerators.
static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
assert(T->isCanonicalUnqualified());
if (const VectorType *VT = dyn_cast<VectorType>(T))
T = VT->getElementType().getTypePtr();
if (const ComplexType *CT = dyn_cast<ComplexType>(T))
T = CT->getElementType().getTypePtr();
if (const AtomicType *AT = dyn_cast<AtomicType>(T))
T = AT->getValueType().getTypePtr();
if (const EnumType *ET = dyn_cast<EnumType>(T))
T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
const BuiltinType *BT = cast<BuiltinType>(T);
assert(BT->isInteger());
return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
}
/// Returns the supremum of two ranges: i.e. their conservative merge.
static IntRange join(IntRange L, IntRange R) {
return IntRange(std::max(L.Width, R.Width),
L.NonNegative && R.NonNegative);
}
/// Returns the infinum of two ranges: i.e. their aggressive merge.
static IntRange meet(IntRange L, IntRange R) {
return IntRange(std::min(L.Width, R.Width),
L.NonNegative || R.NonNegative);
}
};
IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
if (value.isSigned() && value.isNegative())
return IntRange(value.getMinSignedBits(), false);
if (value.getBitWidth() > MaxWidth)
value = value.trunc(MaxWidth);
// isNonNegative() just checks the sign bit without considering
// signedness.
return IntRange(value.getActiveBits(), true);
}
IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
unsigned MaxWidth) {
if (result.isInt())
return GetValueRange(C, result.getInt(), MaxWidth);
if (result.isVector()) {
IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
R = IntRange::join(R, El);
}
return R;
}
if (result.isComplexInt()) {
IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
return IntRange::join(R, I);
}
// This can happen with lossless casts to intptr_t of "based" lvalues.
// Assume it might use arbitrary bits.
// FIXME: The only reason we need to pass the type in here is to get
// the sign right on this one case. It would be nice if APValue
// preserved this.
assert(result.isLValue() || result.isAddrLabelDiff());
return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
}
QualType GetExprType(const Expr *E) {
QualType Ty = E->getType();
if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
Ty = AtomicRHS->getValueType();
return Ty;
}
/// Pseudo-evaluate the given integer expression, estimating the
/// range of values it might take.
///
/// \param MaxWidth - the width to which the value will be truncated
IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
E = E->IgnoreParens();
// Try a full evaluation first.
Expr::EvalResult result;
if (E->EvaluateAsRValue(result, C))
return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
// I think we only want to look through implicit casts here; if the
// user has an explicit widening cast, we should treat the value as
// being of the new, wider type.
if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
return GetExprRange(C, CE->getSubExpr(), MaxWidth);
IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
CE->getCastKind() == CK_BooleanToSignedIntegral;
// Assume that non-integer casts can span the full range of the type.
if (!isIntegerCast)
return OutputTypeRange;
IntRange SubRange
= GetExprRange(C, CE->getSubExpr(),
std::min(MaxWidth, OutputTypeRange.Width));
// Bail out if the subexpr's range is as wide as the cast type.
if (SubRange.Width >= OutputTypeRange.Width)
return OutputTypeRange;
// Otherwise, we take the smaller width, and we're non-negative if
// either the output type or the subexpr is.
return IntRange(SubRange.Width,
SubRange.NonNegative || OutputTypeRange.NonNegative);
}
if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
// If we can fold the condition, just take that operand.
bool CondResult;
if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
return GetExprRange(C, CondResult ? CO->getTrueExpr()
: CO->getFalseExpr(),
MaxWidth);
// Otherwise, conservatively merge.
IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
return IntRange::join(L, R);
}
if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
switch (BO->getOpcode()) {
// Boolean-valued operations are single-bit and positive.
case BO_LAnd:
case BO_LOr:
case BO_LT:
case BO_GT:
case BO_LE:
case BO_GE:
case BO_EQ:
case BO_NE:
return IntRange::forBoolType();
// The type of the assignments is the type of the LHS, so the RHS
// is not necessarily the same type.
case BO_MulAssign:
case BO_DivAssign:
case BO_RemAssign:
case BO_AddAssign:
case BO_SubAssign:
case BO_XorAssign:
case BO_OrAssign:
// TODO: bitfields?
return IntRange::forValueOfType(C, GetExprType(E));
// Simple assignments just pass through the RHS, which will have
// been coerced to the LHS type.
case BO_Assign:
// TODO: bitfields?
return GetExprRange(C, BO->getRHS(), MaxWidth);
// Operations with opaque sources are black-listed.
case BO_PtrMemD:
case BO_PtrMemI:
return IntRange::forValueOfType(C, GetExprType(E));
// Bitwise-and uses the *infinum* of the two source ranges.
case BO_And:
case BO_AndAssign:
return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
GetExprRange(C, BO->getRHS(), MaxWidth));
// Left shift gets black-listed based on a judgement call.
case BO_Shl:
// ...except that we want to treat '1 << (blah)' as logically
// positive. It's an important idiom.
if (IntegerLiteral *I
= dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
if (I->getValue() == 1) {
IntRange R = IntRange::forValueOfType(C, GetExprType(E));
return IntRange(R.Width, /*NonNegative*/ true);
}
}
// fallthrough
case BO_ShlAssign:
return IntRange::forValueOfType(C, GetExprType(E));
// Right shift by a constant can narrow its left argument.
case BO_Shr:
case BO_ShrAssign: {
IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
// If the shift amount is a positive constant, drop the width by
// that much.
llvm::APSInt shift;
if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
shift.isNonNegative()) {
unsigned zext = shift.getZExtValue();
if (zext >= L.Width)
L.Width = (L.NonNegative ? 0 : 1);
else
L.Width -= zext;
}
return L;
}
// Comma acts as its right operand.
case BO_Comma:
return GetExprRange(C, BO->getRHS(), MaxWidth);
// Black-list pointer subtractions.
case BO_Sub:
if (BO->getLHS()->getType()->isPointerType())
return IntRange::forValueOfType(C, GetExprType(E));
break;
// The width of a division result is mostly determined by the size
// of the LHS.
case BO_Div: {
// Don't 'pre-truncate' the operands.
unsigned opWidth = C.getIntWidth(GetExprType(E));
IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
// If the divisor is constant, use that.
llvm::APSInt divisor;
if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
if (log2 >= L.Width)
L.Width = (L.NonNegative ? 0 : 1);
else
L.Width = std::min(L.Width - log2, MaxWidth);
return L;
}
// Otherwise, just use the LHS's width.
IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
return IntRange(L.Width, L.NonNegative && R.NonNegative);
}
// The result of a remainder can't be larger than the result of
// either side.
case BO_Rem: {
// Don't 'pre-truncate' the operands.
unsigned opWidth = C.getIntWidth(GetExprType(E));
IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
IntRange meet = IntRange::meet(L, R);
meet.Width = std::min(meet.Width, MaxWidth);
return meet;
}
// The default behavior is okay for these.
case BO_Mul:
case BO_Add:
case BO_Xor:
case BO_Or:
break;
}
// The default case is to treat the operation as if it were closed
// on the narrowest type that encompasses both operands.
IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
return IntRange::join(L, R);
}
if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
switch (UO->getOpcode()) {
// Boolean-valued operations are white-listed.
case UO_LNot:
return IntRange::forBoolType();
// Operations with opaque sources are black-listed.
case UO_Deref:
case UO_AddrOf: // should be impossible
return IntRange::forValueOfType(C, GetExprType(E));
default:
return GetExprRange(C, UO->getSubExpr(), MaxWidth);
}
}
if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
if (const auto *BitField = E->getSourceBitField())
return IntRange(BitField->getBitWidthValue(C),
BitField->getType()->isUnsignedIntegerOrEnumerationType());
return IntRange::forValueOfType(C, GetExprType(E));
}
IntRange GetExprRange(ASTContext &C, const Expr *E) {
return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
}
/// Checks whether the given value, which currently has the given
/// source semantics, has the same value when coerced through the
/// target semantics.
bool IsSameFloatAfterCast(const llvm::APFloat &value,
const llvm::fltSemantics &Src,
const llvm::fltSemantics &Tgt) {
llvm::APFloat truncated = value;
bool ignored;
truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
return truncated.bitwiseIsEqual(value);
}
/// Checks whether the given value, which currently has the given
/// source semantics, has the same value when coerced through the
/// target semantics.
///
/// The value might be a vector of floats (or a complex number).
bool IsSameFloatAfterCast(const APValue &value,
const llvm::fltSemantics &Src,
const llvm::fltSemantics &Tgt) {
if (value.isFloat())
return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
if (value.isVector()) {
for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
return false;
return true;
}
assert(value.isComplexFloat());
return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
}
void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
bool IsZero(Sema &S, Expr *E) {
// Suppress cases where we are comparing against an enum constant.
if (const DeclRefExpr *DR =
dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
if (isa<EnumConstantDecl>(DR->getDecl()))
return false;
// Suppress cases where the '0' value is expanded from a macro.
if (E->getLocStart().isMacroID())
return false;
llvm::APSInt Value;
return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
}
bool HasEnumType(Expr *E) {
// Strip off implicit integral promotions.
while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
if (ICE->getCastKind() != CK_IntegralCast &&
ICE->getCastKind() != CK_NoOp)
break;
E = ICE->getSubExpr();
}
return E->getType()->isEnumeralType();
}
void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
// Disable warning in template instantiations.
if (!S.ActiveTemplateInstantiations.empty())
return;
BinaryOperatorKind op = E->getOpcode();
if (E->isValueDependent())
return;
if (op == BO_LT && IsZero(S, E->getRHS())) {
S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
<< "< 0" << "false" << HasEnumType(E->getLHS())
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
} else if (op == BO_GE && IsZero(S, E->getRHS())) {
S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
<< ">= 0" << "true" << HasEnumType(E->getLHS())
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
} else if (op == BO_GT && IsZero(S, E->getLHS())) {
S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
<< "0 >" << "false" << HasEnumType(E->getRHS())
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
} else if (op == BO_LE && IsZero(S, E->getLHS())) {
S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
<< "0 <=" << "true" << HasEnumType(E->getRHS())
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
}
}
void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Expr *Constant, Expr *Other,
llvm::APSInt Value,
bool RhsConstant) {
// Disable warning in template instantiations.
if (!S.ActiveTemplateInstantiations.empty())
return;
// TODO: Investigate using GetExprRange() to get tighter bounds
// on the bit ranges.
QualType OtherT = Other->getType();
if (const auto *AT = OtherT->getAs<AtomicType>())
OtherT = AT->getValueType();
IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
unsigned OtherWidth = OtherRange.Width;
bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
// 0 values are handled later by CheckTrivialUnsignedComparison().
if ((Value == 0) && (!OtherIsBooleanType))
return;
BinaryOperatorKind op = E->getOpcode();
bool IsTrue = true;
// Used for diagnostic printout.
enum {
LiteralConstant = 0,
CXXBoolLiteralTrue,
CXXBoolLiteralFalse
} LiteralOrBoolConstant = LiteralConstant;
if (!OtherIsBooleanType) {
QualType ConstantT = Constant->getType();
QualType CommonT = E->getLHS()->getType();
if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
return;
assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
"comparison with non-integer type");
bool ConstantSigned = ConstantT->isSignedIntegerType();
bool CommonSigned = CommonT->isSignedIntegerType();
bool EqualityOnly = false;
if (CommonSigned) {
// The common type is signed, therefore no signed to unsigned conversion.
if (!OtherRange.NonNegative) {
// Check that the constant is representable in type OtherT.
if (ConstantSigned) {
if (OtherWidth >= Value.getMinSignedBits())
return;
} else { // !ConstantSigned
if (OtherWidth >= Value.getActiveBits() + 1)
return;
}
} else { // !OtherSigned
// Check that the constant is representable in type OtherT.
// Negative values are out of range.
if (ConstantSigned) {
if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
return;
} else { // !ConstantSigned
if (OtherWidth >= Value.getActiveBits())
return;
}
}
} else { // !CommonSigned
if (OtherRange.NonNegative) {
if (OtherWidth >= Value.getActiveBits())
return;
} else { // OtherSigned
assert(!ConstantSigned &&
"Two signed types converted to unsigned types.");
// Check to see if the constant is representable in OtherT.
if (OtherWidth > Value.getActiveBits())
return;
// Check to see if the constant is equivalent to a negative value
// cast to CommonT.
if (S.Context.getIntWidth(ConstantT) ==
S.Context.getIntWidth(CommonT) &&
Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
return;
// The constant value rests between values that OtherT can represent
// after conversion. Relational comparison still works, but equality
// comparisons will be tautological.
EqualityOnly = true;
}
}
bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
if (op == BO_EQ || op == BO_NE) {
IsTrue = op == BO_NE;
} else if (EqualityOnly) {
return;
} else if (RhsConstant) {
if (op == BO_GT || op == BO_GE)
IsTrue = !PositiveConstant;
else // op == BO_LT || op == BO_LE
IsTrue = PositiveConstant;
} else {
if (op == BO_LT || op == BO_LE)
IsTrue = !PositiveConstant;
else // op == BO_GT || op == BO_GE
IsTrue = PositiveConstant;
}
} else {
// Other isKnownToHaveBooleanValue
enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
static const struct LinkedConditions {
CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
} TruthTable = {
// Constant on LHS. | Constant on RHS. |
// LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
{ { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
{ { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
{ { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
{ { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
{ { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
{ { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
};
bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
enum ConstantValue ConstVal = Zero;
if (Value.isUnsigned() || Value.isNonNegative()) {
if (Value == 0) {
LiteralOrBoolConstant =
ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
ConstVal = Zero;
} else if (Value == 1) {
LiteralOrBoolConstant =
ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
ConstVal = One;
} else {
LiteralOrBoolConstant = LiteralConstant;
ConstVal = GT_One;
}
} else {
ConstVal = LT_Zero;
}
CompareBoolWithConstantResult CmpRes;
switch (op) {
case BO_LT:
CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
break;
case BO_GT:
CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
break;
case BO_LE:
CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
break;
case BO_GE:
CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
break;
case BO_EQ:
CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
break;
case BO_NE:
CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
break;
default:
CmpRes = Unkwn;
break;
}
if (CmpRes == AFals) {
IsTrue = false;
} else if (CmpRes == ATrue) {
IsTrue = true;
} else {
return;
}
}
// If this is a comparison to an enum constant, include that
// constant in the diagnostic.
const EnumConstantDecl *ED = nullptr;
if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
SmallString<64> PrettySourceValue;
llvm::raw_svector_ostream OS(PrettySourceValue);
if (ED)
OS << '\'' << *ED << "' (" << Value << ")";
else
OS << Value;
S.DiagRuntimeBehavior(
E->getOperatorLoc(), E,
S.PDiag(diag::warn_out_of_range_compare)
<< OS.str() << LiteralOrBoolConstant
<< OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
}
/// Analyze the operands of the given comparison. Implements the
/// fallback case from AnalyzeComparison.
void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
}
/// \brief Implements -Wsign-compare.
///
/// \param E the binary operator to check for warnings
void AnalyzeComparison(Sema &S, BinaryOperator *E) {
// The type the comparison is being performed in.
QualType T = E->getLHS()->getType();
// Only analyze comparison operators where both sides have been converted to
// the same type.
if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
return AnalyzeImpConvsInComparison(S, E);
// Don't analyze value-dependent comparisons directly.
if (E->isValueDependent())
return AnalyzeImpConvsInComparison(S, E);
Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
bool IsComparisonConstant = false;
// Check whether an integer constant comparison results in a value
// of 'true' or 'false'.
if (T->isIntegralType(S.Context)) {
llvm::APSInt RHSValue;
bool IsRHSIntegralLiteral =
RHS->isIntegerConstantExpr(RHSValue, S.Context);
llvm::APSInt LHSValue;
bool IsLHSIntegralLiteral =
LHS->isIntegerConstantExpr(LHSValue, S.Context);
if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
else
IsComparisonConstant =
(IsRHSIntegralLiteral && IsLHSIntegralLiteral);
} else if (!T->hasUnsignedIntegerRepresentation())
IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
// We don't do anything special if this isn't an unsigned integral
// comparison: we're only interested in integral comparisons, and
// signed comparisons only happen in cases we don't care to warn about.
//
// We also don't care about value-dependent expressions or expressions
// whose result is a constant.
if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
return AnalyzeImpConvsInComparison(S, E);
// Check to see if one of the (unmodified) operands is of different
// signedness.
Expr *signedOperand, *unsignedOperand;
if (LHS->getType()->hasSignedIntegerRepresentation()) {
assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
"unsigned comparison between two signed integer expressions?");
signedOperand = LHS;
unsignedOperand = RHS;
} else if (RHS->getType()->hasSignedIntegerRepresentation()) {
signedOperand = RHS;
unsignedOperand = LHS;
} else {
CheckTrivialUnsignedComparison(S, E);
return AnalyzeImpConvsInComparison(S, E);
}
// Otherwise, calculate the effective range of the signed operand.
IntRange signedRange = GetExprRange(S.Context, signedOperand);
// Go ahead and analyze implicit conversions in the operands. Note
// that we skip the implicit conversions on both sides.
AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
// If the signed range is non-negative, -Wsign-compare won't fire,
// but we should still check for comparisons which are always true
// or false.
if (signedRange.NonNegative)
return CheckTrivialUnsignedComparison(S, E);
// For (in)equality comparisons, if the unsigned operand is a
// constant which cannot collide with a overflowed signed operand,
// then reinterpreting the signed operand as unsigned will not
// change the result of the comparison.
if (E->isEqualityOp()) {
unsigned comparisonWidth = S.Context.getIntWidth(T);
IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
// We should never be unable to prove that the unsigned operand is
// non-negative.
assert(unsignedRange.NonNegative && "unsigned range includes negative?");
if (unsignedRange.Width < comparisonWidth)
return;
}
S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
S.PDiag(diag::warn_mixed_sign_comparison)
<< LHS->getType() << RHS->getType()
<< LHS->getSourceRange() << RHS->getSourceRange());
}
/// Analyzes an attempt to assign the given value to a bitfield.
///
/// Returns true if there was something fishy about the attempt.
bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
SourceLocation InitLoc) {
assert(Bitfield->isBitField());
if (Bitfield->isInvalidDecl())
return false;
// White-list bool bitfields.
if (Bitfield->getType()->isBooleanType())
return false;
// Ignore value- or type-dependent expressions.
if (Bitfield->getBitWidth()->isValueDependent() ||
Bitfield->getBitWidth()->isTypeDependent() ||
Init->isValueDependent() ||
Init->isTypeDependent())
return false;
Expr *OriginalInit = Init->IgnoreParenImpCasts();
llvm::APSInt Value;
if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
return false;
unsigned OriginalWidth = Value.getBitWidth();
unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
if (OriginalWidth <= FieldWidth)
return false;
// Compute the value which the bitfield will contain.
llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
// Check whether the stored value is equal to the original value.
TruncatedValue = TruncatedValue.extend(OriginalWidth);
if (llvm::APSInt::isSameValue(Value, TruncatedValue))
return false;
// Special-case bitfields of width 1: booleans are naturally 0/1, and
// therefore don't strictly fit into a signed bitfield of width 1.
if (FieldWidth == 1 && Value == 1)
return false;
std::string PrettyValue = Value.toString(10);
std::string PrettyTrunc = TruncatedValue.toString(10);
S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
<< PrettyValue << PrettyTrunc << OriginalInit->getType()
<< Init->getSourceRange();
return true;
}
/// Analyze the given simple or compound assignment for warning-worthy
/// operations.
void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
// Just recurse on the LHS.
AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
// We want to recurse on the RHS as normal unless we're assigning to
// a bitfield.
if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
E->getOperatorLoc())) {
// Recurse, ignoring any implicit conversions on the RHS.
return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
E->getOperatorLoc());
}
}
AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
}
/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
SourceLocation CContext, unsigned diag,
bool pruneControlFlow = false) {
if (pruneControlFlow) {
S.DiagRuntimeBehavior(E->getExprLoc(), E,
S.PDiag(diag)
<< SourceType << T << E->getSourceRange()
<< SourceRange(CContext));
return;
}
S.Diag(E->getExprLoc(), diag)
<< SourceType << T << E->getSourceRange() << SourceRange(CContext);
}
/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
unsigned diag, bool pruneControlFlow = false) {
DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
}
/// Diagnose an implicit cast from a floating point value to an integer value.
void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
SourceLocation CContext) {
const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
Expr *InnerE = E->IgnoreParenImpCasts();
// We also want to warn on, e.g., "int i = -1.234"
if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
const bool IsLiteral =
isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
llvm::APFloat Value(0.0);
bool IsConstant =
E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
if (!IsConstant) {
return DiagnoseImpCast(S, E, T, CContext,
diag::warn_impcast_float_integer, PruneWarnings);
}
bool isExact = false;
llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
T->hasUnsignedIntegerRepresentation());
if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
&isExact) == llvm::APFloat::opOK &&
isExact) {
if (IsLiteral) return;
return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
PruneWarnings);
}
unsigned DiagID = 0;
if (IsLiteral) {
// Warn on floating point literal to integer.
DiagID = diag::warn_impcast_literal_float_to_integer;
} else if (IntegerValue == 0) {
if (Value.isZero()) { // Skip -0.0 to 0 conversion.
return DiagnoseImpCast(S, E, T, CContext,
diag::warn_impcast_float_integer, PruneWarnings);
}
// Warn on non-zero to zero conversion.
DiagID = diag::warn_impcast_float_to_integer_zero;
} else {
if (IntegerValue.isUnsigned()) {
if (!IntegerValue.isMaxValue()) {
return DiagnoseImpCast(S, E, T, CContext,
diag::warn_impcast_float_integer, PruneWarnings);
}
} else { // IntegerValue.isSigned()
if (!IntegerValue.isMaxSignedValue() &&
!IntegerValue.isMinSignedValue()) {
return DiagnoseImpCast(S, E, T, CContext,
diag::warn_impcast_float_integer, PruneWarnings);
}
}
// Warn on evaluatable floating point expression to integer conversion.
DiagID = diag::warn_impcast_float_to_integer;
}
// FIXME: Force the precision of the source value down so we don't print
// digits which are usually useless (we don't really care here if we
// truncate a digit by accident in edge cases). Ideally, APFloat::toString
// would automatically print the shortest representation, but it's a bit
// tricky to implement.
SmallString<16> PrettySourceValue;
unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
precision = (precision * 59 + 195) / 196;
Value.toString(PrettySourceValue, precision);
SmallString<16> PrettyTargetValue;
if (IsBool)
PrettyTargetValue = Value.isZero() ? "false" : "true";
else
IntegerValue.toString(PrettyTargetValue);
if (PruneWarnings) {
S.DiagRuntimeBehavior(E->getExprLoc(), E,
S.PDiag(DiagID)
<< E->getType() << T.getUnqualifiedType()
<< PrettySourceValue << PrettyTargetValue
<< E->getSourceRange() << SourceRange(CContext));
} else {
S.Diag(E->getExprLoc(), DiagID)
<< E->getType() << T.getUnqualifiedType() << PrettySourceValue
<< PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
}
}
std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
if (!Range.Width) return "0";
llvm::APSInt ValueInRange = Value;
ValueInRange.setIsSigned(!Range.NonNegative);
ValueInRange = ValueInRange.trunc(Range.Width);
return ValueInRange.toString(10);
}
bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
if (!isa<ImplicitCastExpr>(Ex))
return false;
Expr *InnerE = Ex->IgnoreParenImpCasts();
const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
const Type *Source =
S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
if (Target->isDependentType())
return false;
const BuiltinType *FloatCandidateBT =
dyn_cast<BuiltinType>(ToBool ? Source : Target);
const Type *BoolCandidateType = ToBool ? Target : Source;
return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
}
void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
SourceLocation CC) {
unsigned NumArgs = TheCall->getNumArgs();
for (unsigned i = 0; i < NumArgs; ++i) {
Expr *CurrA = TheCall->getArg(i);
if (!IsImplicitBoolFloatConversion(S, CurrA, true))
continue;
bool IsSwapped = ((i > 0) &&
IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
IsSwapped |= ((i < (NumArgs - 1)) &&
IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
if (IsSwapped) {
// Warn on this floating-point to bool conversion.
DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
CurrA->getType(), CC,
diag::warn_impcast_floating_point_to_bool);
}
}
}
void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
E->getExprLoc()))
return;
// Don't warn on functions which have return type nullptr_t.
if (isa<CallExpr>(E))
return;
// Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
const Expr::NullPointerConstantKind NullKind =
E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
return;
// Return if target type is a safe conversion.
if (T->isAnyPointerType() || T->isBlockPointerType() ||
T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
return;
SourceLocation Loc = E->getSourceRange().getBegin();
// Venture through the macro stacks to get to the source of macro arguments.
// The new location is a better location than the complete location that was
// passed in.
while (S.SourceMgr.isMacroArgExpansion(Loc))
Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
while (S.SourceMgr.isMacroArgExpansion(CC))
CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
// __null is usually wrapped in a macro. Go up a macro if that is the case.
if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
Loc, S.SourceMgr, S.getLangOpts());
if (MacroName == "NULL")
Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
}
// Only warn if the null and context location are in the same macro expansion.
if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
return;
S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
<< (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
<< FixItHint::CreateReplacement(Loc,
S.getFixItZeroLiteralForType(T, Loc));
}
void checkObjCArrayLiteral(Sema &S, QualType TargetType,
ObjCArrayLiteral *ArrayLiteral);
void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
ObjCDictionaryLiteral *DictionaryLiteral);
/// Check a single element within a collection literal against the
/// target element type.
void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
Expr *Element, unsigned ElementKind) {
// Skip a bitcast to 'id' or qualified 'id'.
if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
if (ICE->getCastKind() == CK_BitCast &&
ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
Element = ICE->getSubExpr();
}
QualType ElementType = Element->getType();
ExprResult ElementResult(Element);
if (ElementType->getAs<ObjCObjectPointerType>() &&
S.CheckSingleAssignmentConstraints(TargetElementType,
ElementResult,
false, false)
!= Sema::Compatible) {
S.Diag(Element->getLocStart(),
diag::warn_objc_collection_literal_element)
<< ElementType << ElementKind << TargetElementType
<< Element->getSourceRange();
}
if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
}
/// Check an Objective-C array literal being converted to the given
/// target type.
void checkObjCArrayLiteral(Sema &S, QualType TargetType,
ObjCArrayLiteral *ArrayLiteral) {
if (!S.NSArrayDecl)
return;
const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
if (!TargetObjCPtr)
return;
if (TargetObjCPtr->isUnspecialized() ||
TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
!= S.NSArrayDecl->getCanonicalDecl())
return;
auto TypeArgs = TargetObjCPtr->getTypeArgs();
if (TypeArgs.size() != 1)
return;
QualType TargetElementType = TypeArgs[0];
for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
checkObjCCollectionLiteralElement(S, TargetElementType,
ArrayLiteral->getElement(I),
0);
}
}
/// Check an Objective-C dictionary literal being converted to the given
/// target type.
void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
ObjCDictionaryLiteral *DictionaryLiteral) {
if (!S.NSDictionaryDecl)
return;
const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
if (!TargetObjCPtr)
return;
if (TargetObjCPtr->isUnspecialized() ||
TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
!= S.NSDictionaryDecl->getCanonicalDecl())
return;
auto TypeArgs = TargetObjCPtr->getTypeArgs();
if (TypeArgs.size() != 2)
return;
QualType TargetKeyType = TypeArgs[0];
QualType TargetObjectType = TypeArgs[1];
for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
auto Element = DictionaryLiteral->getKeyValueElement(I);
checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
}
}
// Helper function to filter out cases for constant width constant conversion.
// Don't warn on char array initialization or for non-decimal values.
bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
SourceLocation CC) {
// If initializing from a constant, and the constant starts with '0',
// then it is a binary, octal, or hexadecimal. Allow these constants
// to fill all the bits, even if there is a sign change.
if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
const char FirstLiteralCharacter =
S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
if (FirstLiteralCharacter == '0')
return false;
}
// If the CC location points to a '{', and the type is char, then assume
// assume it is an array initialization.
if (CC.isValid() && T->isCharType()) {
const char FirstContextCharacter =
S.getSourceManager().getCharacterData(CC)[0];
if (FirstContextCharacter == '{')
return false;
}
return true;
}
void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
SourceLocation CC, bool *ICContext = nullptr) {
if (E->isTypeDependent() || E->isValueDependent()) return;
const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
if (Source == Target) return;
if (Target->isDependentType()) return;
// If the conversion context location is invalid don't complain. We also
// don't want to emit a warning if the issue occurs from the expansion of
// a system macro. The problem is that 'getSpellingLoc()' is slow, so we
// delay this check as long as possible. Once we detect we are in that
// scenario, we just return.
if (CC.isInvalid())
return;
// Diagnose implicit casts to bool.
if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
if (isa<StringLiteral>(E))
// Warn on string literal to bool. Checks for string literals in logical
// and expressions, for instance, assert(0 && "error here"), are
// prevented by a check in AnalyzeImplicitConversions().
return DiagnoseImpCast(S, E, T, CC,
diag::warn_impcast_string_literal_to_bool);
if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
// This covers the literal expressions that evaluate to Objective-C
// objects.
return DiagnoseImpCast(S, E, T, CC,
diag::warn_impcast_objective_c_literal_to_bool);
}
if (Source->isPointerType() || Source->canDecayToPointerType()) {
// Warn on pointer to bool conversion that is always true.
S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
SourceRange(CC));
}
}
// Check implicit casts from Objective-C collection literals to specialized
// collection types, e.g., NSArray<NSString *> *.
if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
// Strip vector types.
if (isa<VectorType>(Source)) {
if (!isa<VectorType>(Target)) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
}
// If the vector cast is cast between two vectors of the same size, it is
// a bitcast, not a conversion.
if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
return;
Source = cast<VectorType>(Source)->getElementType().getTypePtr();
Target = cast<VectorType>(Target)->getElementType().getTypePtr();
}
if (auto VecTy = dyn_cast<VectorType>(Target))
Target = VecTy->getElementType().getTypePtr();
// Strip complex types.
if (isa<ComplexType>(Source)) {
if (!isa<ComplexType>(Target)) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
}
Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
}
const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
// If the source is floating point...
if (SourceBT && SourceBT->isFloatingPoint()) {
// ...and the target is floating point...
if (TargetBT && TargetBT->isFloatingPoint()) {
// ...then warn if we're dropping FP rank.
// Builtin FP kinds are ordered by increasing FP rank.
if (SourceBT->getKind() > TargetBT->getKind()) {
// Don't warn about float constants that are precisely
// representable in the target type.
Expr::EvalResult result;
if (E->EvaluateAsRValue(result, S.Context)) {
// Value might be a float, a float vector, or a float complex.
if (IsSameFloatAfterCast(result.Val,
S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
return;
}
if (S.SourceMgr.isInSystemMacro(CC))
return;
DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
}
// ... or possibly if we're increasing rank, too
else if (TargetBT->getKind() > SourceBT->getKind()) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
}
return;
}
// If the target is integral, always warn.
if (TargetBT && TargetBT->isInteger()) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
DiagnoseFloatingImpCast(S, E, T, CC);
}
// Detect the case where a call result is converted from floating-point to
// to bool, and the final argument to the call is converted from bool, to
// discover this typo:
//
// bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
//
// FIXME: This is an incredibly special case; is there some more general
// way to detect this class of misplaced-parentheses bug?
if (Target->isBooleanType() && isa<CallExpr>(E)) {
// Check last argument of function call to see if it is an
// implicit cast from a type matching the type the result
// is being cast to.
CallExpr *CEx = cast<CallExpr>(E);
if (unsigned NumArgs = CEx->getNumArgs()) {
Expr *LastA = CEx->getArg(NumArgs - 1);
Expr *InnerE = LastA->IgnoreParenImpCasts();
if (isa<ImplicitCastExpr>(LastA) &&
InnerE->getType()->isBooleanType()) {
// Warn on this floating-point to bool conversion
DiagnoseImpCast(S, E, T, CC,
diag::warn_impcast_floating_point_to_bool);
}
}
}
return;
}
DiagnoseNullConversion(S, E, T, CC);
if (!Source->isIntegerType() || !Target->isIntegerType())
return;
// TODO: remove this early return once the false positives for constant->bool
// in templates, macros, etc, are reduced or removed.
if (Target->isSpecificBuiltinType(BuiltinType::Bool))
return;
IntRange SourceRange = GetExprRange(S.Context, E);
IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
if (SourceRange.Width > TargetRange.Width) {
// If the source is a constant, use a default-on diagnostic.
// TODO: this should happen for bitfield stores, too.
llvm::APSInt Value(32);
if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
std::string PrettySourceValue = Value.toString(10);
std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
S.DiagRuntimeBehavior(E->getExprLoc(), E,
S.PDiag(diag::warn_impcast_integer_precision_constant)
<< PrettySourceValue << PrettyTargetValue
<< E->getType() << T << E->getSourceRange()
<< clang::SourceRange(CC));
return;
}
// People want to build with -Wshorten-64-to-32 and not -Wconversion.
if (S.SourceMgr.isInSystemMacro(CC))
return;
if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
/* pruneControlFlow */ true);
return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
}
if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
SourceRange.NonNegative && Source->isSignedIntegerType()) {
// Warn when doing a signed to signed conversion, warn if the positive
// source value is exactly the width of the target type, which will
// cause a negative value to be stored.
llvm::APSInt Value;
if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
!S.SourceMgr.isInSystemMacro(CC)) {
if (isSameWidthConstantConversion(S, E, T, CC)) {
std::string PrettySourceValue = Value.toString(10);
std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
S.DiagRuntimeBehavior(
E->getExprLoc(), E,
S.PDiag(diag::warn_impcast_integer_precision_constant)
<< PrettySourceValue << PrettyTargetValue << E->getType() << T
<< E->getSourceRange() << clang::SourceRange(CC));
return;
}
}
// Fall through for non-constants to give a sign conversion warning.
}
if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
(!TargetRange.NonNegative && SourceRange.NonNegative &&
SourceRange.Width == TargetRange.Width)) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
unsigned DiagID = diag::warn_impcast_integer_sign;
// Traditionally, gcc has warned about this under -Wsign-compare.
// We also want to warn about it in -Wconversion.
// So if -Wconversion is off, use a completely identical diagnostic
// in the sign-compare group.
// The conditional-checking code will
if (ICContext) {
DiagID = diag::warn_impcast_integer_sign_conditional;
*ICContext = true;
}
return DiagnoseImpCast(S, E, T, CC, DiagID);
}
// Diagnose conversions between different enumeration types.
// In C, we pretend that the type of an EnumConstantDecl is its enumeration
// type, to give us better diagnostics.
QualType SourceType = E->getType();
if (!S.getLangOpts().CPlusPlus) {
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
SourceType = S.Context.getTypeDeclType(Enum);
Source = S.Context.getCanonicalType(SourceType).getTypePtr();
}
}
if (const EnumType *SourceEnum = Source->getAs<EnumType>())
if (const EnumType *TargetEnum = Target->getAs<EnumType>())
if (SourceEnum->getDecl()->hasNameForLinkage() &&
TargetEnum->getDecl()->hasNameForLinkage() &&
SourceEnum != TargetEnum) {
if (S.SourceMgr.isInSystemMacro(CC))
return;
return DiagnoseImpCast(S, E, SourceType, T, CC,
diag::warn_impcast_different_enum_types);
}
}
void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
SourceLocation CC, QualType T);
void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
SourceLocation CC, bool &ICContext) {
E = E->IgnoreParenImpCasts();
if (isa<ConditionalOperator>(E))
return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
AnalyzeImplicitConversions(S, E, CC);
if (E->getType() != T)
return CheckImplicitConversion(S, E, T, CC, &ICContext);
}
void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
SourceLocation CC, QualType T) {
AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
bool Suspicious = false;
CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
// If -Wconversion would have warned about either of the candidates
// for a signedness conversion to the context type...
if (!Suspicious) return;
// ...but it's currently ignored...
if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
return;
// ...then check whether it would have warned about either of the
// candidates for a signedness conversion to the condition type.
if (E->getType() == T) return;
Suspicious = false;
CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
E->getType(), CC, &Suspicious);
if (!Suspicious)
CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
E->getType(), CC, &Suspicious);
}
/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
/// Input argument E is a logical expression.
void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
if (S.getLangOpts().Bool)
return;
CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
}
/// AnalyzeImplicitConversions - Find and report any interesting
/// implicit conversions in the given expression. There are a couple
/// of competing diagnostics here, -Wconversion and -Wsign-compare.
void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
QualType T = OrigE->getType();
Expr *E = OrigE->IgnoreParenImpCasts();
if (E->isTypeDependent() || E->isValueDependent())
return;
// For conditional operators, we analyze the arguments as if they
// were being fed directly into the output.
if (isa<ConditionalOperator>(E)) {
ConditionalOperator *CO = cast<ConditionalOperator>(E);
CheckConditionalOperator(S, CO, CC, T);
return;
}
// Check implicit argument conversions for function calls.
if (CallExpr *Call = dyn_cast<CallExpr>(E))
CheckImplicitArgumentConversions(S, Call, CC);
// Go ahead and check any implicit conversions we might have skipped.
// The non-canonical typecheck is just an optimization;
// CheckImplicitConversion will filter out dead implicit conversions.
if (E->getType() != T)
CheckImplicitConversion(S, E, T, CC);
// Now continue drilling into this expression.
if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
// The bound subexpressions in a PseudoObjectExpr are not reachable
// as transitive children.
// FIXME: Use a more uniform representation for this.
for (auto *SE : POE->semantics())
if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
}
// Skip past explicit casts.
if (isa<ExplicitCastExpr>(E)) {
E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
return AnalyzeImplicitConversions(S, E, CC);
}
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
// Do a somewhat different check with comparison operators.
if (BO->isComparisonOp())
return AnalyzeComparison(S, BO);
// And with simple assignments.
if (BO->getOpcode() == BO_Assign)
return AnalyzeAssignment(S, BO);
}
// These break the otherwise-useful invariant below. Fortunately,
// we don't really need to recurse into them, because any internal
// expressions should have been analyzed already when they were
// built into statements.
if (isa<StmtExpr>(E)) return;
// Don't descend into unevaluated contexts.
if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
// Now just recurse over the expression's children.
CC = E->getExprLoc();
BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
for (Stmt *SubStmt : E->children()) {
Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
if (!ChildExpr)
continue;
if (IsLogicalAndOperator &&
isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
// Ignore checking string literals that are in logical and operators.
// This is a common pattern for asserts.
continue;
AnalyzeImplicitConversions(S, ChildExpr, CC);
}
if (BO && BO->isLogicalOp()) {
Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
SubExpr = BO->getRHS()->IgnoreParenImpCasts();
if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
}
if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
if (U->getOpcode() == UO_LNot)
::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
}
} // end anonymous namespace
// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
// Returns true when emitting a warning about taking the address of a reference.
static bool CheckForReference(Sema &SemaRef, const Expr *E,
PartialDiagnostic PD) {
E = E->IgnoreParenImpCasts();
const FunctionDecl *FD = nullptr;
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
if (!DRE->getDecl()->getType()->isReferenceType())
return false;
} else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
if (!M->getMemberDecl()->getType()->isReferenceType())
return false;
} else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
return false;
FD = Call->getDirectCallee();
} else {
return false;
}
SemaRef.Diag(E->getExprLoc(), PD);
// If possible, point to location of function.
if (FD) {
SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
}
return true;
}
// Returns true if the SourceLocation is expanded from any macro body.
// Returns false if the SourceLocation is invalid, is from not in a macro
// expansion, or is from expanded from a top-level macro argument.
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
if (Loc.isInvalid())
return false;
while (Loc.isMacroID()) {
if (SM.isMacroBodyExpansion(Loc))
return true;
Loc = SM.getImmediateMacroCallerLoc(Loc);
}
return false;
}
/// \brief Diagnose pointers that are always non-null.
/// \param E the expression containing the pointer
/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
/// compared to a null pointer
/// \param IsEqual True when the comparison is equal to a null pointer
/// \param Range Extra SourceRange to highlight in the diagnostic
void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullKind,
bool IsEqual, SourceRange Range) {
if (!E)
return;
// Don't warn inside macros.
if (E->getExprLoc().isMacroID()) {
const SourceManager &SM = getSourceManager();
if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
IsInAnyMacroBody(SM, Range.getBegin()))
return;
}
E = E->IgnoreImpCasts();
const bool IsCompare = NullKind != Expr::NPCK_NotNull;
if (isa<CXXThisExpr>(E)) {
unsigned DiagID = IsCompare ? diag::warn_this_null_compare
: diag::warn_this_bool_conversion;
Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
return;
}
bool IsAddressOf = false;
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
if (UO->getOpcode() != UO_AddrOf)
return;
IsAddressOf = true;
E = UO->getSubExpr();
}
if (IsAddressOf) {
unsigned DiagID = IsCompare
? diag::warn_address_of_reference_null_compare
: diag::warn_address_of_reference_bool_conversion;
PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
<< IsEqual;
if (CheckForReference(*this, E, PD)) {
return;
}
}
auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
std::string Str;
llvm::raw_string_ostream S(Str);
E->printPretty(S, nullptr, getPrintingPolicy());
unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
: diag::warn_cast_nonnull_to_bool;
Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
<< E->getSourceRange() << Range << IsEqual;
};
// If we have a CallExpr that is tagged with returns_nonnull, we can complain.
if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
if (auto *Callee = Call->getDirectCallee()) {
if (Callee->hasAttr<ReturnsNonNullAttr>()) {
ComplainAboutNonnullParamOrCall(false);
return;
}
}
}
// Expect to find a single Decl. Skip anything more complicated.
ValueDecl *D = nullptr;
if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
D = R->getDecl();
} else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
D = M->getMemberDecl();
}
// Weak Decls can be null.
if (!D || D->isWeak())
return;
// Check for parameter decl with nonnull attribute
if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
if (getCurFunction() &&
!getCurFunction()->ModifiedNonNullParams.count(PV)) {
if (PV->hasAttr<NonNullAttr>()) {
ComplainAboutNonnullParamOrCall(true);
return;
}
if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
assert(ParamIter != FD->param_end());
unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
if (!NonNull->args_size()) {
ComplainAboutNonnullParamOrCall(true);
return;
}
for (unsigned ArgNo : NonNull->args()) {
if (ArgNo == ParamNo) {
ComplainAboutNonnullParamOrCall(true);
return;
}
}
}
}
}
}
QualType T = D->getType();
const bool IsArray = T->isArrayType();
const bool IsFunction = T->isFunctionType();
// Address of function is used to silence the function warning.
if (IsAddressOf && IsFunction) {
return;
}
// Found nothing.
if (!IsAddressOf && !IsFunction && !IsArray)
return;
// Pretty print the expression for the diagnostic.
std::string Str;
llvm::raw_string_ostream S(Str);
E->printPretty(S, nullptr, getPrintingPolicy());
unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
: diag::warn_impcast_pointer_to_bool;
enum {
AddressOf,
FunctionPointer,
ArrayPointer
} DiagType;
if (IsAddressOf)
DiagType = AddressOf;
else if (IsFunction)
DiagType = FunctionPointer;
else if (IsArray)
DiagType = ArrayPointer;
else
llvm_unreachable("Could not determine diagnostic.");
Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
<< Range << IsEqual;
if (!IsFunction)
return;
// Suggest '&' to silence the function warning.
Diag(E->getExprLoc(), diag::note_function_warning_silence)
<< FixItHint::CreateInsertion(E->getLocStart(), "&");
// Check to see if '()' fixit should be emitted.
QualType ReturnType;
UnresolvedSet<4> NonTemplateOverloads;
tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
if (ReturnType.isNull())
return;
if (IsCompare) {
// There are two cases here. If there is null constant, the only suggest
// for a pointer return type. If the null is 0, then suggest if the return
// type is a pointer or an integer type.
if (!ReturnType->isPointerType()) {
if (NullKind == Expr::NPCK_ZeroExpression ||
NullKind == Expr::NPCK_ZeroLiteral) {
if (!ReturnType->isIntegerType())
return;
} else {
return;
}
}
} else { // !IsCompare
// For function to bool, only suggest if the function pointer has bool
// return type.
if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
return;
}
Diag(E->getExprLoc(), diag::note_function_to_function_call)
<< FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
}
/// Diagnoses "dangerous" implicit conversions within the given
/// expression (which is a full expression). Implements -Wconversion
/// and -Wsign-compare.
///
/// \param CC the "context" location of the implicit conversion, i.e.
/// the most location of the syntactic entity requiring the implicit
/// conversion
void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
// Don't diagnose in unevaluated contexts.
if (isUnevaluatedContext())
return;
// Don't diagnose for value- or type-dependent expressions.
if (E->isTypeDependent() || E->isValueDependent())
return;
// Check for array bounds violations in cases where the check isn't triggered
// elsewhere for other Expr types (like BinaryOperators), e.g. when an
// ArraySubscriptExpr is on the RHS of a variable initialization.
CheckArrayAccess(E);
// This is not the right CC for (e.g.) a variable initialization.
AnalyzeImplicitConversions(*this, E, CC);
}
/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
/// Input argument E is a logical expression.
void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
::CheckBoolLikeConversion(*this, E, CC);
}
/// Diagnose when expression is an integer constant expression and its evaluation
/// results in integer overflow
void Sema::CheckForIntOverflow (Expr *E) {
// Use a work list to deal with nested struct initializers.
SmallVector<Expr *, 2> Exprs(1, E);
do {
Expr *E = Exprs.pop_back_val();
if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
E->IgnoreParenCasts()->EvaluateForOverflow(Context);
continue;
}
if (auto InitList = dyn_cast<InitListExpr>(E))
Exprs.append(InitList->inits().begin(), InitList->inits().end());
} while (!Exprs.empty());
}
namespace {
/// \brief Visitor for expressions which looks for unsequenced operations on the
/// same object.
class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
typedef EvaluatedExprVisitor<SequenceChecker> Base;
/// \brief A tree of sequenced regions within an expression. Two regions are
/// unsequenced if one is an ancestor or a descendent of the other. When we
/// finish processing an expression with sequencing, such as a comma
/// expression, we fold its tree nodes into its parent, since they are
/// unsequenced with respect to nodes we will visit later.
class SequenceTree {
struct Value {
explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
unsigned Parent : 31;
bool Merged : 1;
};
SmallVector<Value, 8> Values;
public:
/// \brief A region within an expression which may be sequenced with respect
/// to some other region.
class Seq {
explicit Seq(unsigned N) : Index(N) {}
unsigned Index;
friend class SequenceTree;
public:
Seq() : Index(0) {}
};
SequenceTree() { Values.push_back(Value(0)); }
Seq root() const { return Seq(0); }
/// \brief Create a new sequence of operations, which is an unsequenced
/// subset of \p Parent. This sequence of operations is sequenced with
/// respect to other children of \p Parent.
Seq allocate(Seq Parent) {
Values.push_back(Value(Parent.Index));
return Seq(Values.size() - 1);
}
/// \brief Merge a sequence of operations into its parent.
void merge(Seq S) {
Values[S.Index].Merged = true;
}
/// \brief Determine whether two operations are unsequenced. This operation
/// is asymmetric: \p Cur should be the more recent sequence, and \p Old
/// should have been merged into its parent as appropriate.
bool isUnsequenced(Seq Cur, Seq Old) {
unsigned C = representative(Cur.Index);
unsigned Target = representative(Old.Index);
while (C >= Target) {
if (C == Target)
return true;
C = Values[C].Parent;
}
return false;
}
private:
/// \brief Pick a representative for a sequence.
unsigned representative(unsigned K) {
if (Values[K].Merged)
// Perform path compression as we go.
return Values[K].Parent = representative(Values[K].Parent);
return K;
}
};
/// An object for which we can track unsequenced uses.
typedef NamedDecl *Object;
/// Different flavors of object usage which we track. We only track the
/// least-sequenced usage of each kind.
enum UsageKind {
/// A read of an object. Multiple unsequenced reads are OK.
UK_Use,
/// A modification of an object which is sequenced before the value
/// computation of the expression, such as ++n in C++.
UK_ModAsValue,
/// A modification of an object which is not sequenced before the value
/// computation of the expression, such as n++.
UK_ModAsSideEffect,
UK_Count = UK_ModAsSideEffect + 1
};
struct Usage {
Usage() : Use(nullptr), Seq() {}
Expr *Use;
SequenceTree::Seq Seq;
};
struct UsageInfo {
UsageInfo() : Diagnosed(false) {}
Usage Uses[UK_Count];
/// Have we issued a diagnostic for this variable already?
bool Diagnosed;
};
typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
Sema &SemaRef;
/// Sequenced regions within the expression.
SequenceTree Tree;
/// Declaration modifications and references which we have seen.
UsageInfoMap UsageMap;
/// The region we are currently within.
SequenceTree::Seq Region;
/// Filled in with declarations which were modified as a side-effect
/// (that is, post-increment operations).
SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
/// Expressions to check later. We defer checking these to reduce
/// stack usage.
SmallVectorImpl<Expr *> &WorkList;
/// RAII object wrapping the visitation of a sequenced subexpression of an
/// expression. At the end of this process, the side-effects of the evaluation
/// become sequenced with respect to the value computation of the result, so
/// we downgrade any UK_ModAsSideEffect within the evaluation to
/// UK_ModAsValue.
struct SequencedSubexpression {
SequencedSubexpression(SequenceChecker &Self)
: Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
Self.ModAsSideEffect = &ModAsSideEffect;
}
~SequencedSubexpression() {
for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
MI != ME; ++MI) {
UsageInfo &U = Self.UsageMap[MI->first];
auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
SideEffectUsage = MI->second;
}
Self.ModAsSideEffect = OldModAsSideEffect;
}
SequenceChecker &Self;
SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
};
/// RAII object wrapping the visitation of a subexpression which we might
/// choose to evaluate as a constant. If any subexpression is evaluated and
/// found to be non-constant, this allows us to suppress the evaluation of
/// the outer expression.
class EvaluationTracker {
public:
EvaluationTracker(SequenceChecker &Self)
: Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
Self.EvalTracker = this;
}
~EvaluationTracker() {
Self.EvalTracker = Prev;
if (Prev)
Prev->EvalOK &= EvalOK;
}
bool evaluate(const Expr *E, bool &Result) {
if (!EvalOK || E->isValueDependent())
return false;
EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
return EvalOK;
}
private:
SequenceChecker &Self;
EvaluationTracker *Prev;
bool EvalOK;
} *EvalTracker;
/// \brief Find the object which is produced by the specified expression,
/// if any.
Object getObject(Expr *E, bool Mod) const {
E = E->IgnoreParenCasts();
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
return getObject(UO->getSubExpr(), Mod);
} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
if (BO->getOpcode() == BO_Comma)
return getObject(BO->getRHS(), Mod);
if (Mod && BO->isAssignmentOp())
return getObject(BO->getLHS(), Mod);
} else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
// FIXME: Check for more interesting cases, like "x.n = ++x.n".
if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
return ME->getMemberDecl();
} else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
// FIXME: If this is a reference, map through to its value.
return DRE->getDecl();
return nullptr;
}
/// \brief Note that an object was modified or used by an expression.
void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
Usage &U = UI.Uses[UK];
if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
if (UK == UK_ModAsSideEffect && ModAsSideEffect)
ModAsSideEffect->push_back(std::make_pair(O, U));
U.Use = Ref;
U.Seq = Region;
}
}
/// \brief Check whether a modification or use conflicts with a prior usage.
void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
bool IsModMod) {
if (UI.Diagnosed)
return;
const Usage &U = UI.Uses[OtherKind];
if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
return;
Expr *Mod = U.Use;
Expr *ModOrUse = Ref;
if (OtherKind == UK_Use)
std::swap(Mod, ModOrUse);
SemaRef.Diag(Mod->getExprLoc(),
IsModMod ? diag::warn_unsequenced_mod_mod
: diag::warn_unsequenced_mod_use)
<< O << SourceRange(ModOrUse->getExprLoc());
UI.Diagnosed = true;
}
void notePreUse(Object O, Expr *Use) {
UsageInfo &U = UsageMap[O];
// Uses conflict with other modifications.
checkUsage(O, U, Use, UK_ModAsValue, false);
}
void notePostUse(Object O, Expr *Use) {
UsageInfo &U = UsageMap[O];
checkUsage(O, U, Use, UK_ModAsSideEffect, false);
addUsage(U, O, Use, UK_Use);
}
void notePreMod(Object O, Expr *Mod) {
UsageInfo &U = UsageMap[O];
// Modifications conflict with other modifications and with uses.
checkUsage(O, U, Mod, UK_ModAsValue, true);
checkUsage(O, U, Mod, UK_Use, false);
}
void notePostMod(Object O, Expr *Use, UsageKind UK) {
UsageInfo &U = UsageMap[O];
checkUsage(O, U, Use, UK_ModAsSideEffect, true);
addUsage(U, O, Use, UK);
}
public:
SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
: Base(S.Context), SemaRef(S), Region(Tree.root()),
ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Visit(E);
}
void VisitStmt(Stmt *S) {
// Skip all statements which aren't expressions for now.
}
void VisitExpr(Expr *E) {
// By default, just recurse to evaluated subexpressions.
Base::VisitStmt(E);
}
void VisitCastExpr(CastExpr *E) {
Object O = Object();
if (E->getCastKind() == CK_LValueToRValue)
O = getObject(E->getSubExpr(), false);
if (O)
notePreUse(O, E);
VisitExpr(E);
if (O)
notePostUse(O, E);
}
void VisitBinComma(BinaryOperator *BO) {
// C++11 [expr.comma]p1:
// Every value computation and side effect associated with the left
// expression is sequenced before every value computation and side
// effect associated with the right expression.
SequenceTree::Seq LHS = Tree.allocate(Region);
SequenceTree::Seq RHS = Tree.allocate(Region);
SequenceTree::Seq OldRegion = Region;
{
SequencedSubexpression SeqLHS(*this);
Region = LHS;
Visit(BO->getLHS());
}
Region = RHS;
Visit(BO->getRHS());
Region = OldRegion;
// Forget that LHS and RHS are sequenced. They are both unsequenced
// with respect to other stuff.
Tree.merge(LHS);
Tree.merge(RHS);
}
void VisitBinAssign(BinaryOperator *BO) {
// The modification is sequenced after the value computation of the LHS
// and RHS, so check it before inspecting the operands and update the
// map afterwards.
Object O = getObject(BO->getLHS(), true);
if (!O)
return VisitExpr(BO);
notePreMod(O, BO);
// C++11 [expr.ass]p7:
// E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
// only once.
//
// Therefore, for a compound assignment operator, O is considered used
// everywhere except within the evaluation of E1 itself.
if (isa<CompoundAssignOperator>(BO))
notePreUse(O, BO);
Visit(BO->getLHS());
if (isa<CompoundAssignOperator>(BO))
notePostUse(O, BO);
Visit(BO->getRHS());
// C++11 [expr.ass]p1:
// the assignment is sequenced [...] before the value computation of the
// assignment expression.
// C11 6.5.16/3 has no such rule.
notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
: UK_ModAsSideEffect);
}
void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
VisitBinAssign(CAO);
}
void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
void VisitUnaryPreIncDec(UnaryOperator *UO) {
Object O = getObject(UO->getSubExpr(), true);
if (!O)
return VisitExpr(UO);
notePreMod(O, UO);
Visit(UO->getSubExpr());
// C++11 [expr.pre.incr]p1:
// the expression ++x is equivalent to x+=1
notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
: UK_ModAsSideEffect);
}
void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
void VisitUnaryPostIncDec(UnaryOperator *UO) {
Object O = getObject(UO->getSubExpr(), true);
if (!O)
return VisitExpr(UO);
notePreMod(O, UO);
Visit(UO->getSubExpr());
notePostMod(O, UO, UK_ModAsSideEffect);
}
/// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
void VisitBinLOr(BinaryOperator *BO) {
// The side-effects of the LHS of an '&&' are sequenced before the
// value computation of the RHS, and hence before the value computation
// of the '&&' itself, unless the LHS evaluates to zero. We treat them
// as if they were unconditionally sequenced.
EvaluationTracker Eval(*this);
{
SequencedSubexpression Sequenced(*this);
Visit(BO->getLHS());
}
bool Result;
if (Eval.evaluate(BO->getLHS(), Result)) {
if (!Result)
Visit(BO->getRHS());
} else {
// Check for unsequenced operations in the RHS, treating it as an
// entirely separate evaluation.
//
// FIXME: If there are operations in the RHS which are unsequenced
// with respect to operations outside the RHS, and those operations
// are unconditionally evaluated, diagnose them.
WorkList.push_back(BO->getRHS());
}
}
void VisitBinLAnd(BinaryOperator *BO) {
EvaluationTracker Eval(*this);
{
SequencedSubexpression Sequenced(*this);
Visit(BO->getLHS());
}
bool Result;
if (Eval.evaluate(BO->getLHS(), Result)) {
if (Result)
Visit(BO->getRHS());
} else {
WorkList.push_back(BO->getRHS());
}
}
// Only visit the condition, unless we can be sure which subexpression will
// be chosen.
void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
EvaluationTracker Eval(*this);
{
SequencedSubexpression Sequenced(*this);
Visit(CO->getCond());
}
bool Result;
if (Eval.evaluate(CO->getCond(), Result))
Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
else {
WorkList.push_back(CO->getTrueExpr());
WorkList.push_back(CO->getFalseExpr());
}
}
void VisitCallExpr(CallExpr *CE) {
// C++11 [intro.execution]p15:
// When calling a function [...], every value computation and side effect
// associated with any argument expression, or with the postfix expression
// designating the called function, is sequenced before execution of every
// expression or statement in the body of the function [and thus before
// the value computation of its result].
SequencedSubexpression Sequenced(*this);
Base::VisitCallExpr(CE);
// FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
}
void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
// This is a call, so all subexpressions are sequenced before the result.
SequencedSubexpression Sequenced(*this);
if (!CCE->isListInitialization())
return VisitExpr(CCE);
// In C++11, list initializations are sequenced.
SmallVector<SequenceTree::Seq, 32> Elts;
SequenceTree::Seq Parent = Region;
for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
E = CCE->arg_end();
I != E; ++I) {
Region = Tree.allocate(Parent);
Elts.push_back(Region);
Visit(*I);
}
// Forget that the initializers are sequenced.
Region = Parent;
for (unsigned I = 0; I < Elts.size(); ++I)
Tree.merge(Elts[I]);
}
void VisitInitListExpr(InitListExpr *ILE) {
if (!SemaRef.getLangOpts().CPlusPlus11)
return VisitExpr(ILE);
// In C++11, list initializations are sequenced.
SmallVector<SequenceTree::Seq, 32> Elts;
SequenceTree::Seq Parent = Region;
for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
Expr *E = ILE->getInit(I);
if (!E) continue;
Region = Tree.allocate(Parent);
Elts.push_back(Region);
Visit(E);
}
// Forget that the initializers are sequenced.
Region = Parent;
for (unsigned I = 0; I < Elts.size(); ++I)
Tree.merge(Elts[I]);
}
};
} // end anonymous namespace
void Sema::CheckUnsequencedOperations(Expr *E) {
SmallVector<Expr *, 8> WorkList;
WorkList.push_back(E);
while (!WorkList.empty()) {
Expr *Item = WorkList.pop_back_val();
SequenceChecker(*this, Item, WorkList);
}
}
void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
bool IsConstexpr) {
CheckImplicitConversions(E, CheckLoc);
CheckUnsequencedOperations(E);
if (!IsConstexpr && !E->isValueDependent())
CheckForIntOverflow(E);
}
void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
FieldDecl *BitField,
Expr *Init) {
(void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
}
static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
SourceLocation Loc) {
if (!PType->isVariablyModifiedType())
return;
if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
return;
}
if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
return;
}
if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
return;
}
const ArrayType *AT = S.Context.getAsArrayType(PType);
if (!AT)
return;
if (AT->getSizeModifier() != ArrayType::Star) {
diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
return;
}
S.Diag(Loc, diag::err_array_star_in_function_definition);
}
/// CheckParmsForFunctionDef - Check that the parameters of the given
/// function are appropriate for the definition of a function. This
/// takes care of any checks that cannot be performed on the
/// declaration itself, e.g., that the types of each of the function
/// parameters are complete.
bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
ParmVarDecl *const *PEnd,
bool CheckParameterNames) {
bool HasInvalidParm = false;
for (; P != PEnd; ++P) {
ParmVarDecl *Param = *P;
// C99 6.7.5.3p4: the parameters in a parameter type list in a
// function declarator that is part of a function definition of
// that function shall not have incomplete type.
//
// This is also C++ [dcl.fct]p6.
if (!Param->isInvalidDecl() &&
RequireCompleteType(Param->getLocation(), Param->getType(),
diag::err_typecheck_decl_incomplete_type)) {
Param->setInvalidDecl();
HasInvalidParm = true;
}
// C99 6.9.1p5: If the declarator includes a parameter type list, the
// declaration of each parameter shall include an identifier.
if (CheckParameterNames &&
Param->getIdentifier() == nullptr &&
!Param->isImplicit() &&
!getLangOpts().CPlusPlus)
Diag(Param->getLocation(), diag::err_parameter_name_omitted);
// C99 6.7.5.3p12:
// If the function declarator is not part of a definition of that
// function, parameters may have incomplete type and may use the [*]
// notation in their sequences of declarator specifiers to specify
// variable length array types.
QualType PType = Param->getOriginalType();
// FIXME: This diagnostic should point the '[*]' if source-location
// information is added for it.
diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
// MSVC destroys objects passed by value in the callee. Therefore a
// function definition which takes such a parameter must be able to call the
// object's destructor. However, we don't perform any direct access check
// on the dtor.
if (getLangOpts().CPlusPlus && Context.getTargetInfo()
.getCXXABI()
.areArgsDestroyedLeftToRightInCallee()) {
if (!Param->isInvalidDecl()) {
if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
if (!ClassDecl->isInvalidDecl() &&
!ClassDecl->hasIrrelevantDestructor() &&
!ClassDecl->isDependentContext()) {
CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
MarkFunctionReferenced(Param->getLocation(), Destructor);
DiagnoseUseOfDecl(Destructor, Param->getLocation());
}
}
}
}
// Parameters with the pass_object_size attribute only need to be marked
// constant at function definitions. Because we lack information about
// whether we're on a declaration or definition when we're instantiating the
// attribute, we need to check for constness here.
if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
if (!Param->getType().isConstQualified())
Diag(Param->getLocation(), diag::err_attribute_pointers_only)
<< Attr->getSpelling() << 1;
}
return HasInvalidParm;
}
/// CheckCastAlign - Implements -Wcast-align, which warns when a
/// pointer cast increases the alignment requirements.
void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
// This is actually a lot of work to potentially be doing on every
// cast; don't do it if we're ignoring -Wcast_align (as is the default).
if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
return;
// Ignore dependent types.
if (T->isDependentType() || Op->getType()->isDependentType())
return;
// Require that the destination be a pointer type.
const PointerType *DestPtr = T->getAs<PointerType>();
if (!DestPtr) return;
// If the destination has alignment 1, we're done.
QualType DestPointee = DestPtr->getPointeeType();
if (DestPointee->isIncompleteType()) return;
CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
if (DestAlign.isOne()) return;
// Require that the source be a pointer type.
const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
if (!SrcPtr) return;
QualType SrcPointee = SrcPtr->getPointeeType();
// Whitelist casts from cv void*. We already implicitly
// whitelisted casts to cv void*, since they have alignment 1.
// Also whitelist casts involving incomplete types, which implicitly
// includes 'void'.
if (SrcPointee->isIncompleteType()) return;
CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
if (SrcAlign >= DestAlign) return;
Diag(TRange.getBegin(), diag::warn_cast_align)
<< Op->getType() << T
<< static_cast<unsigned>(SrcAlign.getQuantity())
<< static_cast<unsigned>(DestAlign.getQuantity())
<< TRange << Op->getSourceRange();
}
static const Type* getElementType(const Expr *BaseExpr) {
const Type* EltType = BaseExpr->getType().getTypePtr();
if (EltType->isAnyPointerType())
return EltType->getPointeeType().getTypePtr();
else if (EltType->isArrayType())
return EltType->getBaseElementTypeUnsafe();
return EltType;
}
/// \brief Check whether this array fits the idiom of a size-one tail padded
/// array member of a struct.
///
/// We avoid emitting out-of-bounds access warnings for such arrays as they are
/// commonly used to emulate flexible arrays in C89 code.
static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
const NamedDecl *ND) {
if (Size != 1 || !ND) return false;
const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
if (!FD) return false;
// Don't consider sizes resulting from macro expansions or template argument
// substitution to form C89 tail-padded arrays.
TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
while (TInfo) {
TypeLoc TL = TInfo->getTypeLoc();
// Look through typedefs.
if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
TInfo = TDL->getTypeSourceInfo();
continue;
}
if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
return false;
}
break;
}
const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
if (!RD) return false;
if (RD->isUnion()) return false;
if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
if (!CRD->isStandardLayout()) return false;
}
// See if this is the last field decl in the record.
const Decl *D = FD;
while ((D = D->getNextDeclInContext()))
if (isa<FieldDecl>(D))
return false;
return true;
}
void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE,
bool AllowOnePastEnd, bool IndexNegated) {
IndexExpr = IndexExpr->IgnoreParenImpCasts();
if (IndexExpr->isValueDependent())
return;
const Type *EffectiveType = getElementType(BaseExpr);
BaseExpr = BaseExpr->IgnoreParenCasts();
const ConstantArrayType *ArrayTy =
Context.getAsConstantArrayType(BaseExpr->getType());
if (!ArrayTy)
return;
llvm::APSInt index;
if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
return;
if (IndexNegated)
index = -index;
const NamedDecl *ND = nullptr;
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
ND = dyn_cast<NamedDecl>(DRE->getDecl());
if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
if (index.isUnsigned() || !index.isNegative()) {
llvm::APInt size = ArrayTy->getSize();
if (!size.isStrictlyPositive())
return;
const Type* BaseType = getElementType(BaseExpr);
if (BaseType != EffectiveType) {
// Make sure we're comparing apples to apples when comparing index to size
uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
uint64_t array_typesize = Context.getTypeSize(BaseType);
// Handle ptrarith_typesize being zero, such as when casting to void*
if (!ptrarith_typesize) ptrarith_typesize = 1;
if (ptrarith_typesize != array_typesize) {
// There's a cast to a different size type involved
uint64_t ratio = array_typesize / ptrarith_typesize;
// TODO: Be smarter about handling cases where array_typesize is not a
// multiple of ptrarith_typesize
if (ptrarith_typesize * ratio == array_typesize)
size *= llvm::APInt(size.getBitWidth(), ratio);
}
}
if (size.getBitWidth() > index.getBitWidth())
index = index.zext(size.getBitWidth());
else if (size.getBitWidth() < index.getBitWidth())
size = size.zext(index.getBitWidth());
// For array subscripting the index must be less than size, but for pointer
// arithmetic also allow the index (offset) to be equal to size since
// computing the next address after the end of the array is legal and
// commonly done e.g. in C++ iterators and range-based for loops.
if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
return;
// Also don't warn for arrays of size 1 which are members of some
// structure. These are often used to approximate flexible arrays in C89
// code.
if (IsTailPaddedMemberArray(*this, size, ND))
return;
// Suppress the warning if the subscript expression (as identified by the
// ']' location) and the index expression are both from macro expansions
// within a system header.
if (ASE) {
SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
ASE->getRBracketLoc());
if (SourceMgr.isInSystemHeader(RBracketLoc)) {
SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
IndexExpr->getLocStart());
if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
return;
}
}
unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
if (ASE)
DiagID = diag::warn_array_index_exceeds_bounds;
DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
PDiag(DiagID) << index.toString(10, true)
<< size.toString(10, true)
<< (unsigned)size.getLimitedValue(~0U)
<< IndexExpr->getSourceRange());
} else {
unsigned DiagID = diag::warn_array_index_precedes_bounds;
if (!ASE) {
DiagID = diag::warn_ptr_arith_precedes_bounds;
if (index.isNegative()) index = -index;
}
DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
PDiag(DiagID) << index.toString(10, true)
<< IndexExpr->getSourceRange());
}
if (!ND) {
// Try harder to find a NamedDecl to point at in the note.
while (const ArraySubscriptExpr *ASE =
dyn_cast<ArraySubscriptExpr>(BaseExpr))
BaseExpr = ASE->getBase()->IgnoreParenCasts();
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
ND = dyn_cast<NamedDecl>(DRE->getDecl());
if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
}
if (ND)
DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
PDiag(diag::note_array_index_out_of_bounds)
<< ND->getDeclName());
}
void Sema::CheckArrayAccess(const Expr *expr) {
int AllowOnePastEnd = 0;
while (expr) {
expr = expr->IgnoreParenImpCasts();
switch (expr->getStmtClass()) {
case Stmt::ArraySubscriptExprClass: {
const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
AllowOnePastEnd > 0);
return;
}
case Stmt::OMPArraySectionExprClass: {
const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
if (ASE->getLowerBound())
CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
/*ASE=*/nullptr, AllowOnePastEnd > 0);
return;
}
case Stmt::UnaryOperatorClass: {
// Only unwrap the * and & unary operators
const UnaryOperator *UO = cast<UnaryOperator>(expr);
expr = UO->getSubExpr();
switch (UO->getOpcode()) {
case UO_AddrOf:
AllowOnePastEnd++;
break;
case UO_Deref:
AllowOnePastEnd--;
break;
default:
return;
}
break;
}
case Stmt::ConditionalOperatorClass: {
const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
if (const Expr *lhs = cond->getLHS())
CheckArrayAccess(lhs);
if (const Expr *rhs = cond->getRHS())
CheckArrayAccess(rhs);
return;
}
default:
return;
}
}
}
//===--- CHECK: Objective-C retain cycles ----------------------------------//
namespace {
struct RetainCycleOwner {
RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
VarDecl *Variable;
SourceRange Range;
SourceLocation Loc;
bool Indirect;
void setLocsFrom(Expr *e) {
Loc = e->getExprLoc();
Range = e->getSourceRange();
}
};
} // end anonymous namespace
/// Consider whether capturing the given variable can possibly lead to
/// a retain cycle.
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
// In ARC, it's captured strongly iff the variable has __strong
// lifetime. In MRR, it's captured strongly if the variable is
// __block and has an appropriate type.
if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
return false;
owner.Variable = var;
if (ref)
owner.setLocsFrom(ref);
return true;
}
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
while (true) {
e = e->IgnoreParens();
if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
switch (cast->getCastKind()) {
case CK_BitCast:
case CK_LValueBitCast:
case CK_LValueToRValue:
case CK_ARCReclaimReturnedObject:
e = cast->getSubExpr();
continue;
default:
return false;
}
}
if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
ObjCIvarDecl *ivar = ref->getDecl();
if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
return false;
// Try to find a retain cycle in the base.
if (!findRetainCycleOwner(S, ref->getBase(), owner))
return false;
if (ref->isFreeIvar()) owner.setLocsFrom(ref);
owner.Indirect = true;
return true;
}
if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
if (!var) return false;
return considerVariable(var, ref, owner);
}
if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
if (member->isArrow()) return false;
// Don't count this as an indirect ownership.
e = member->getBase();
continue;
}
if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
// Only pay attention to pseudo-objects on property references.
ObjCPropertyRefExpr *pre
= dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
->IgnoreParens());
if (!pre) return false;
if (pre->isImplicitProperty()) return false;
ObjCPropertyDecl *property = pre->getExplicitProperty();
if (!property->isRetaining() &&
!(property->getPropertyIvarDecl() &&
property->getPropertyIvarDecl()->getType()
.getObjCLifetime() == Qualifiers::OCL_Strong))
return false;
owner.Indirect = true;
if (pre->isSuperReceiver()) {
owner.Variable = S.getCurMethodDecl()->getSelfDecl();
if (!owner.Variable)
return false;
owner.Loc = pre->getLocation();
owner.Range = pre->getSourceRange();
return true;
}
e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
->getSourceExpr());
continue;
}
// Array ivars?
return false;
}
}
namespace {
struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
: EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Context(Context), Variable(variable), Capturer(nullptr),
VarWillBeReased(false) {}
ASTContext &Context;
VarDecl *Variable;
Expr *Capturer;
bool VarWillBeReased;
void VisitDeclRefExpr(DeclRefExpr *ref) {
if (ref->getDecl() == Variable && !Capturer)
Capturer = ref;
}
void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
if (Capturer) return;
Visit(ref->getBase());
if (Capturer && ref->isFreeIvar())
Capturer = ref;
}
void VisitBlockExpr(BlockExpr *block) {
// Look inside nested blocks
if (block->getBlockDecl()->capturesVariable(Variable))
Visit(block->getBlockDecl()->getBody());
}
void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
if (Capturer) return;
if (OVE->getSourceExpr())
Visit(OVE->getSourceExpr());
}
void VisitBinaryOperator(BinaryOperator *BinOp) {
if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
return;
Expr *LHS = BinOp->getLHS();
if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
if (DRE->getDecl() != Variable)
return;
if (Expr *RHS = BinOp->getRHS()) {
RHS = RHS->IgnoreParenCasts();
llvm::APSInt Value;
VarWillBeReased =
(RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
}
}
}
};
} // end anonymous namespace
/// Check whether the given argument is a block which captures a
/// variable.
static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
assert(owner.Variable && owner.Loc.isValid());
e = e->IgnoreParenCasts();
// Look through [^{...} copy] and Block_copy(^{...}).
if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
Selector Cmd = ME->getSelector();
if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
e = ME->getInstanceReceiver();
if (!e)
return nullptr;
e = e->IgnoreParenCasts();
}
} else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
if (CE->getNumArgs() == 1) {
FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
if (Fn) {
const IdentifierInfo *FnI = Fn->getIdentifier();
if (FnI && FnI->isStr("_Block_copy")) {
e = CE->getArg(0)->IgnoreParenCasts();
}
}
}
}
BlockExpr *block = dyn_cast<BlockExpr>(e);
if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
return nullptr;
FindCaptureVisitor visitor(S.Context, owner.Variable);
visitor.Visit(block->getBlockDecl()->getBody());
return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
}
static void diagnoseRetainCycle(Sema &S, Expr *capturer,
RetainCycleOwner &owner) {
assert(capturer);
assert(owner.Variable && owner.Loc.isValid());
S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
<< owner.Variable << capturer->getSourceRange();
S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
<< owner.Indirect << owner.Range;
}
/// Check for a keyword selector that starts with the word 'add' or
/// 'set'.
static bool isSetterLikeSelector(Selector sel) {
if (sel.isUnarySelector()) return false;
StringRef str = sel.getNameForSlot(0);
while (!str.empty() && str.front() == '_') str = str.substr(1);
if (str.startswith("set"))
str = str.substr(3);
else if (str.startswith("add")) {
// Specially whitelist 'addOperationWithBlock:'.
if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
return false;
str = str.substr(3);
}
else
return false;
if (str.empty()) return true;
return !isLowercase(str.front());
}
static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
ObjCMessageExpr *Message) {
bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(),
NSAPI::ClassId_NSMutableArray);
if (!IsMutableArray) {
return None;
}
Selector Sel = Message->getSelector();
Optional<NSAPI::NSArrayMethodKind> MKOpt =
S.NSAPIObj->getNSArrayMethodKind(Sel);
if (!MKOpt) {
return None;
}
NSAPI::NSArrayMethodKind MK = *MKOpt;
switch (MK) {
case NSAPI::NSMutableArr_addObject:
case NSAPI::NSMutableArr_insertObjectAtIndex:
case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
return 0;
case NSAPI::NSMutableArr_replaceObjectAtIndex:
return 1;
default:
return None;
}
return None;
}
static
Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
ObjCMessageExpr *Message) {
bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(),
NSAPI::ClassId_NSMutableDictionary);
if (!IsMutableDictionary) {
return None;
}
Selector Sel = Message->getSelector();
Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
S.NSAPIObj->getNSDictionaryMethodKind(Sel);
if (!MKOpt) {
return None;
}
NSAPI::NSDictionaryMethodKind MK = *MKOpt;
switch (MK) {
case NSAPI::NSMutableDict_setObjectForKey:
case NSAPI::NSMutableDict_setValueForKey:
case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
return 0;
default:
return None;
}
return None;
}
static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(),
NSAPI::ClassId_NSMutableSet);
bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(),
NSAPI::ClassId_NSMutableOrderedSet);
if (!IsMutableSet && !IsMutableOrderedSet) {
return None;
}
Selector Sel = Message->getSelector();
Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
if (!MKOpt) {
return None;
}
NSAPI::NSSetMethodKind MK = *MKOpt;
switch (MK) {
case NSAPI::NSMutableSet_addObject:
case NSAPI::NSOrderedSet_setObjectAtIndex:
case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
case NSAPI::NSOrderedSet_insertObjectAtIndex:
return 0;
case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
return 1;
}
return None;
}
void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
if (!Message->isInstanceMessage()) {
return;
}
Optional<int> ArgOpt;
if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
!(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
!(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
return;
}
int ArgIndex = *ArgOpt;
Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
Arg = OE->getSourceExpr()->IgnoreImpCasts();
}
if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
if (ArgRE->isObjCSelfExpr()) {
Diag(Message->getSourceRange().getBegin(),
diag::warn_objc_circular_container)
<< ArgRE->getDecl()->getName() << StringRef("super");
}
}
} else {
Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
Receiver = OE->getSourceExpr()->IgnoreImpCasts();
}
if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
ValueDecl *Decl = ReceiverRE->getDecl();
Diag(Message->getSourceRange().getBegin(),
diag::warn_objc_circular_container)
<< Decl->getName() << Decl->getName();
if (!ArgRE->isObjCSelfExpr()) {
Diag(Decl->getLocation(),
diag::note_objc_circular_container_declared_here)
<< Decl->getName();
}
}
}
} else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
ObjCIvarDecl *Decl = IvarRE->getDecl();
Diag(Message->getSourceRange().getBegin(),
diag::warn_objc_circular_container)
<< Decl->getName() << Decl->getName();
Diag(Decl->getLocation(),
diag::note_objc_circular_container_declared_here)
<< Decl->getName();
}
}
}
}
}
/// Check a message send to see if it's likely to cause a retain cycle.
void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
// Only check instance methods whose selector looks like a setter.
if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
return;
// Try to find a variable that the receiver is strongly owned by.
RetainCycleOwner owner;
if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
return;
} else {
assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
owner.Variable = getCurMethodDecl()->getSelfDecl();
owner.Loc = msg->getSuperLoc();
owner.Range = msg->getSuperLoc();
}
// Check whether the receiver is captured by any of the arguments.
for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
return diagnoseRetainCycle(*this, capturer, owner);
}
/// Check a property assign to see if it's likely to cause a retain cycle.
void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
RetainCycleOwner owner;
if (!findRetainCycleOwner(*this, receiver, owner))
return;
if (Expr *capturer = findCapturingExpr(*this, argument, owner))
diagnoseRetainCycle(*this, capturer, owner);
}
void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
RetainCycleOwner Owner;
if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
return;
// Because we don't have an expression for the variable, we have to set the
// location explicitly here.
Owner.Loc = Var->getLocation();
Owner.Range = Var->getSourceRange();
if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
diagnoseRetainCycle(*this, Capturer, Owner);
}
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
Expr *RHS, bool isProperty) {
// Check if RHS is an Objective-C object literal, which also can get
// immediately zapped in a weak reference. Note that we explicitly
// allow ObjCStringLiterals, since those are designed to never really die.
RHS = RHS->IgnoreParenImpCasts();
// This enum needs to match with the 'select' in
// warn_objc_arc_literal_assign (off-by-1).
Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
if (Kind == Sema::LK_String || Kind == Sema::LK_None)
return false;
S.Diag(Loc, diag::warn_arc_literal_assign)
<< (unsigned) Kind
<< (isProperty ? 0 : 1)
<< RHS->getSourceRange();
return true;
}
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
Qualifiers::ObjCLifetime LT,
Expr *RHS, bool isProperty) {
// Strip off any implicit cast added to get to the one ARC-specific.
while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
if (cast->getCastKind() == CK_ARCConsumeObject) {
S.Diag(Loc, diag::warn_arc_retained_assign)
<< (LT == Qualifiers::OCL_ExplicitNone)
<< (isProperty ? 0 : 1)
<< RHS->getSourceRange();
return true;
}
RHS = cast->getSubExpr();
}
if (LT == Qualifiers::OCL_Weak &&
checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
return true;
return false;
}
bool Sema::checkUnsafeAssigns(SourceLocation Loc,
QualType LHS, Expr *RHS) {
Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
return false;
if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
return true;
return false;
}
void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
Expr *LHS, Expr *RHS) {
QualType LHSType;
// PropertyRef on LHS type need be directly obtained from
// its declaration as it has a PseudoType.
ObjCPropertyRefExpr *PRE
= dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
if (PRE && !PRE->isImplicitProperty()) {
const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
if (PD)
LHSType = PD->getType();
}
if (LHSType.isNull())
LHSType = LHS->getType();
Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
if (LT == Qualifiers::OCL_Weak) {
if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
getCurFunction()->markSafeWeakUse(LHS);
}
if (checkUnsafeAssigns(Loc, LHSType, RHS))
return;
// FIXME. Check for other life times.
if (LT != Qualifiers::OCL_None)
return;
if (PRE) {
if (PRE->isImplicitProperty())
return;
const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
if (!PD)
return;
unsigned Attributes = PD->getPropertyAttributes();
if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
// when 'assign' attribute was not explicitly specified
// by user, ignore it and rely on property type itself
// for lifetime info.
unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
LHSType->isObjCRetainableType())
return;
while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
if (cast->getCastKind() == CK_ARCConsumeObject) {
Diag(Loc, diag::warn_arc_retained_property_assign)
<< RHS->getSourceRange();
return;
}
RHS = cast->getSubExpr();
}
}
else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
return;
}
}
}
//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
namespace {
bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
SourceLocation StmtLoc,
const NullStmt *Body) {
// Do not warn if the body is a macro that expands to nothing, e.g:
//
// #define CALL(x)
// if (condition)
// CALL(0);
//
if (Body->hasLeadingEmptyMacro())
return false;
// Get line numbers of statement and body.
bool StmtLineInvalid;
unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
&StmtLineInvalid);
if (StmtLineInvalid)
return false;
bool BodyLineInvalid;
unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
&BodyLineInvalid);
if (BodyLineInvalid)
return false;
// Warn if null statement and body are on the same line.
if (StmtLine != BodyLine)
return false;
return true;
}
} // end anonymous namespace
void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID) {
// Since this is a syntactic check, don't emit diagnostic for template
// instantiations, this just adds noise.
if (CurrentInstantiationScope)
return;
// The body should be a null statement.
const NullStmt *NBody = dyn_cast<NullStmt>(Body);
if (!NBody)
return;
// Do the usual checks.
if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
return;
Diag(NBody->getSemiLoc(), DiagID);
Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
}
void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody) {
assert(!CurrentInstantiationScope); // Ensured by caller
SourceLocation StmtLoc;
const Stmt *Body;
unsigned DiagID;
if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
StmtLoc = FS->getRParenLoc();
Body = FS->getBody();
DiagID = diag::warn_empty_for_body;
} else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
StmtLoc = WS->getCond()->getSourceRange().getEnd();
Body = WS->getBody();
DiagID = diag::warn_empty_while_body;
} else
return; // Neither `for' nor `while'.
// The body should be a null statement.
const NullStmt *NBody = dyn_cast<NullStmt>(Body);
if (!NBody)
return;
// Skip expensive checks if diagnostic is disabled.
if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
return;
// Do the usual checks.
if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
return;
// `for(...);' and `while(...);' are popular idioms, so in order to keep
// noise level low, emit diagnostics only if for/while is followed by a
// CompoundStmt, e.g.:
// for (int i = 0; i < n; i++);
// {
// a(i);
// }
// or if for/while is followed by a statement with more indentation
// than for/while itself:
// for (int i = 0; i < n; i++);
// a(i);
bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
if (!ProbableTypo) {
bool BodyColInvalid;
unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
PossibleBody->getLocStart(),
&BodyColInvalid);
if (BodyColInvalid)
return;
bool StmtColInvalid;
unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
S->getLocStart(),
&StmtColInvalid);
if (StmtColInvalid)
return;
if (BodyCol > StmtCol)
ProbableTypo = true;
}
if (ProbableTypo) {
Diag(NBody->getSemiLoc(), DiagID);
Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
}
}
//===--- CHECK: Warn on self move with std::move. -------------------------===//
/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc) {
if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
return;
if (!ActiveTemplateInstantiations.empty())
return;
// Strip parens and casts away.
LHSExpr = LHSExpr->IgnoreParenImpCasts();
RHSExpr = RHSExpr->IgnoreParenImpCasts();
// Check for a call expression
const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
if (!CE || CE->getNumArgs() != 1)
return;
// Check for a call to std::move
const FunctionDecl *FD = CE->getDirectCallee();
if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
!FD->getIdentifier()->isStr("move"))
return;
// Get argument from std::move
RHSExpr = CE->getArg(0);
const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
// Two DeclRefExpr's, check that the decls are the same.
if (LHSDeclRef && RHSDeclRef) {
if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
return;
if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
RHSDeclRef->getDecl()->getCanonicalDecl())
return;
Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
<< LHSExpr->getSourceRange()
<< RHSExpr->getSourceRange();
return;
}
// Member variables require a different approach to check for self moves.
// MemberExpr's are the same if every nested MemberExpr refers to the same
// Decl and that the base Expr's are DeclRefExpr's with the same Decl or
// the base Expr's are CXXThisExpr's.
const Expr *LHSBase = LHSExpr;
const Expr *RHSBase = RHSExpr;
const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
if (!LHSME || !RHSME)
return;
while (LHSME && RHSME) {
if (LHSME->getMemberDecl()->getCanonicalDecl() !=
RHSME->getMemberDecl()->getCanonicalDecl())
return;
LHSBase = LHSME->getBase();
RHSBase = RHSME->getBase();
LHSME = dyn_cast<MemberExpr>(LHSBase);
RHSME = dyn_cast<MemberExpr>(RHSBase);
}
LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
if (LHSDeclRef && RHSDeclRef) {
if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
return;
if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
RHSDeclRef->getDecl()->getCanonicalDecl())
return;
Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
<< LHSExpr->getSourceRange()
<< RHSExpr->getSourceRange();
return;
}
if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
<< LHSExpr->getSourceRange()
<< RHSExpr->getSourceRange();
}
//===--- Layout compatibility ----------------------------------------------//
namespace {
bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
/// \brief Check if two enumeration types are layout-compatible.
bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
// C++11 [dcl.enum] p8:
// Two enumeration types are layout-compatible if they have the same
// underlying type.
return ED1->isComplete() && ED2->isComplete() &&
C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
}
/// \brief Check if two fields are layout-compatible.
bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
return false;
if (Field1->isBitField() != Field2->isBitField())
return false;
if (Field1->isBitField()) {
// Make sure that the bit-fields are the same length.
unsigned Bits1 = Field1->getBitWidthValue(C);
unsigned Bits2 = Field2->getBitWidthValue(C);
if (Bits1 != Bits2)
return false;
}
return true;
}
/// \brief Check if two standard-layout structs are layout-compatible.
/// (C++11 [class.mem] p17)
bool isLayoutCompatibleStruct(ASTContext &C,
RecordDecl *RD1,
RecordDecl *RD2) {
// If both records are C++ classes, check that base classes match.
if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
// If one of records is a CXXRecordDecl we are in C++ mode,
// thus the other one is a CXXRecordDecl, too.
const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
// Check number of base classes.
if (D1CXX->getNumBases() != D2CXX->getNumBases())
return false;
// Check the base classes.
for (CXXRecordDecl::base_class_const_iterator
Base1 = D1CXX->bases_begin(),
BaseEnd1 = D1CXX->bases_end(),
Base2 = D2CXX->bases_begin();
Base1 != BaseEnd1;
++Base1, ++Base2) {
if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
return false;
}
} else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
// If only RD2 is a C++ class, it should have zero base classes.
if (D2CXX->getNumBases() > 0)
return false;
}
// Check the fields.
RecordDecl::field_iterator Field2 = RD2->field_begin(),
Field2End = RD2->field_end(),
Field1 = RD1->field_begin(),
Field1End = RD1->field_end();
for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
if (!isLayoutCompatible(C, *Field1, *Field2))
return false;
}
if (Field1 != Field1End || Field2 != Field2End)
return false;
return true;
}
/// \brief Check if two standard-layout unions are layout-compatible.
/// (C++11 [class.mem] p18)
bool isLayoutCompatibleUnion(ASTContext &C,
RecordDecl *RD1,
RecordDecl *RD2) {
llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
for (auto *Field2 : RD2->fields())
UnmatchedFields.insert(Field2);
for (auto *Field1 : RD1->fields()) {
llvm::SmallPtrSet<FieldDecl *, 8>::iterator
I = UnmatchedFields.begin(),
E = UnmatchedFields.end();
for ( ; I != E; ++I) {
if (isLayoutCompatible(C, Field1, *I)) {
bool Result = UnmatchedFields.erase(*I);
(void) Result;
assert(Result);
break;
}
}
if (I == E)
return false;
}
return UnmatchedFields.empty();
}
bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
if (RD1->isUnion() != RD2->isUnion())
return false;
if (RD1->isUnion())
return isLayoutCompatibleUnion(C, RD1, RD2);
else
return isLayoutCompatibleStruct(C, RD1, RD2);
}
/// \brief Check if two types are layout-compatible in C++11 sense.
bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
if (T1.isNull() || T2.isNull())
return false;
// C++11 [basic.types] p11:
// If two types T1 and T2 are the same type, then T1 and T2 are
// layout-compatible types.
if (C.hasSameType(T1, T2))
return true;
T1 = T1.getCanonicalType().getUnqualifiedType();
T2 = T2.getCanonicalType().getUnqualifiedType();
const Type::TypeClass TC1 = T1->getTypeClass();
const Type::TypeClass TC2 = T2->getTypeClass();
if (TC1 != TC2)
return false;
if (TC1 == Type::Enum) {
return isLayoutCompatible(C,
cast<EnumType>(T1)->getDecl(),
cast<EnumType>(T2)->getDecl());
} else if (TC1 == Type::Record) {
if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
return false;
return isLayoutCompatible(C,
cast<RecordType>(T1)->getDecl(),
cast<RecordType>(T2)->getDecl());
}
return false;
}
} // end anonymous namespace
//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
namespace {
/// \brief Given a type tag expression find the type tag itself.
///
/// \param TypeExpr Type tag expression, as it appears in user's code.
///
/// \param VD Declaration of an identifier that appears in a type tag.
///
/// \param MagicValue Type tag magic value.
bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
const ValueDecl **VD, uint64_t *MagicValue) {
while(true) {
if (!TypeExpr)
return false;
TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
switch (TypeExpr->getStmtClass()) {
case Stmt::UnaryOperatorClass: {
const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
TypeExpr = UO->getSubExpr();
continue;
}
return false;
}
case Stmt::DeclRefExprClass: {
const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
*VD = DRE->getDecl();
return true;
}
case Stmt::IntegerLiteralClass: {
const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
llvm::APInt MagicValueAPInt = IL->getValue();
if (MagicValueAPInt.getActiveBits() <= 64) {
*MagicValue = MagicValueAPInt.getZExtValue();
return true;
} else
return false;
}
case Stmt::BinaryConditionalOperatorClass:
case Stmt::ConditionalOperatorClass: {
const AbstractConditionalOperator *ACO =
cast<AbstractConditionalOperator>(TypeExpr);
bool Result;
if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
if (Result)
TypeExpr = ACO->getTrueExpr();
else
TypeExpr = ACO->getFalseExpr();
continue;
}
return false;
}
case Stmt::BinaryOperatorClass: {
const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
if (BO->getOpcode() == BO_Comma) {
TypeExpr = BO->getRHS();
continue;
}
return false;
}
default:
return false;
}
}
}
/// \brief Retrieve the C type corresponding to type tag TypeExpr.
///
/// \param TypeExpr Expression that specifies a type tag.
///
/// \param MagicValues Registered magic values.
///
/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
/// kind.
///
/// \param TypeInfo Information about the corresponding C type.
///
/// \returns true if the corresponding C type was found.
bool GetMatchingCType(
const IdentifierInfo *ArgumentKind,
const Expr *TypeExpr, const ASTContext &Ctx,
const llvm::DenseMap<Sema::TypeTagMagicValue,
Sema::TypeTagData> *MagicValues,
bool &FoundWrongKind,
Sema::TypeTagData &TypeInfo) {
FoundWrongKind = false;
// Variable declaration that has type_tag_for_datatype attribute.
const ValueDecl *VD = nullptr;
uint64_t MagicValue;
if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
return false;
if (VD) {
if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
if (I->getArgumentKind() != ArgumentKind) {
FoundWrongKind = true;
return false;
}
TypeInfo.Type = I->getMatchingCType();
TypeInfo.LayoutCompatible = I->getLayoutCompatible();
TypeInfo.MustBeNull = I->getMustBeNull();
return true;
}
return false;
}
if (!MagicValues)
return false;
llvm::DenseMap<Sema::TypeTagMagicValue,
Sema::TypeTagData>::const_iterator I =
MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
if (I == MagicValues->end())
return false;
TypeInfo = I->second;
return true;
}
} // end anonymous namespace
void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible,
bool MustBeNull) {
if (!TypeTagForDatatypeMagicValues)
TypeTagForDatatypeMagicValues.reset(
new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
TypeTagMagicValue Magic(ArgumentKind, MagicValue);
(*TypeTagForDatatypeMagicValues)[Magic] =
TypeTagData(Type, LayoutCompatible, MustBeNull);
}
namespace {
bool IsSameCharType(QualType T1, QualType T2) {
const BuiltinType *BT1 = T1->getAs<BuiltinType>();
if (!BT1)
return false;
const BuiltinType *BT2 = T2->getAs<BuiltinType>();
if (!BT2)
return false;
BuiltinType::Kind T1Kind = BT1->getKind();
BuiltinType::Kind T2Kind = BT2->getKind();
return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
(T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
(T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
(T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
}
} // end anonymous namespace
void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const Expr * const *ExprArgs) {
const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
bool IsPointerAttr = Attr->getIsPointer();
const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
bool FoundWrongKind;
TypeTagData TypeInfo;
if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
TypeTagForDatatypeMagicValues.get(),
FoundWrongKind, TypeInfo)) {
if (FoundWrongKind)
Diag(TypeTagExpr->getExprLoc(),
diag::warn_type_tag_for_datatype_wrong_kind)
<< TypeTagExpr->getSourceRange();
return;
}
const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
if (IsPointerAttr) {
// Skip implicit cast of pointer to `void *' (as a function argument).
if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
if (ICE->getType()->isVoidPointerType() &&
ICE->getCastKind() == CK_BitCast)
ArgumentExpr = ICE->getSubExpr();
}
QualType ArgumentType = ArgumentExpr->getType();
// Passing a `void*' pointer shouldn't trigger a warning.
if (IsPointerAttr && ArgumentType->isVoidPointerType())
return;
if (TypeInfo.MustBeNull) {
// Type tag with matching void type requires a null pointer.
if (!ArgumentExpr->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNotNull)) {
Diag(ArgumentExpr->getExprLoc(),
diag::warn_type_safety_null_pointer_required)
<< ArgumentKind->getName()
<< ArgumentExpr->getSourceRange()
<< TypeTagExpr->getSourceRange();
}
return;
}
QualType RequiredType = TypeInfo.Type;
if (IsPointerAttr)
RequiredType = Context.getPointerType(RequiredType);
bool mismatch = false;
if (!TypeInfo.LayoutCompatible) {
mismatch = !Context.hasSameType(ArgumentType, RequiredType);
// C++11 [basic.fundamental] p1:
// Plain char, signed char, and unsigned char are three distinct types.
//
// But we treat plain `char' as equivalent to `signed char' or `unsigned
// char' depending on the current char signedness mode.
if (mismatch)
if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
RequiredType->getPointeeType())) ||
(!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
mismatch = false;
} else
if (IsPointerAttr)
mismatch = !isLayoutCompatible(Context,
ArgumentType->getPointeeType(),
RequiredType->getPointeeType());
else
mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
if (mismatch)
Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
<< ArgumentType << ArgumentKind
<< TypeInfo.LayoutCompatible << RequiredType
<< ArgumentExpr->getSourceRange()
<< TypeTagExpr->getSourceRange();
}
|
#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_SCROLLBACK = 50;
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the tokenchain RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Truncate history from current position
history.erase(history.begin() + historyPtr, history.end());
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
|
/* DefinitionalRepresentation.cpp
* BRL-CAD
*
* Copyright (c) 1994-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file step/DefinitionalRepresentation.cpp
*
* Routines to convert STEP "DefinitionalRepresentation" to BRL-CAD BREP
* structures.
*
*/
#include "STEPWrapper.h"
#include "Factory.h"
#include "DefinitionalRepresentation.h"
#define CLASSNAME "DefinitionalRepresentation"
#define ENTITYNAME "Definitional_Representation"
string DefinitionalRepresentation::entityname = Factory::RegisterClass(ENTITYNAME, (FactoryMethod)DefinitionalRepresentation::Create);
DefinitionalRepresentation::DefinitionalRepresentation()
{
step = NULL;
id = 0;
}
DefinitionalRepresentation::DefinitionalRepresentation(STEPWrapper *sw, int step_id)
{
step = sw;
id = step_id;
}
DefinitionalRepresentation::~DefinitionalRepresentation()
{
}
bool
DefinitionalRepresentation::Load(STEPWrapper *sw, SDAI_Application_instance *sse)
{
step = sw;
id = sse->STEPfile_id;
if (!Representation::Load(sw, sse)) {
std::cout << CLASSNAME << ":Error loading baseclass Representation." << std::endl;
sw->entity_status[id] = STEP_LOAD_ERROR;
return false;
}
sw->entity_status[id] = STEP_LOADED;
return true;
}
void
DefinitionalRepresentation::Print(int level)
{
TAB(level);
std::cout << CLASSNAME << ":" << name << "(";
std::cout << "ID:" << STEPid() << ")" << std::endl;
TAB(level);
std::cout << "Inherited Attributes:" << std::endl;
Representation::Print(level + 1);
}
STEPEntity *
DefinitionalRepresentation::GetInstance(STEPWrapper *sw, int id)
{
return new DefinitionalRepresentation(sw, id);
}
STEPEntity *
DefinitionalRepresentation::Create(STEPWrapper *sw, SDAI_Application_instance *sse)
{
return STEPEntity::CreateEntity(sw, sse, GetInstance, CLASSNAME);
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
|
// Time-stamp: <2021-02-19 17:42:33 anup>
// Units: All SI units - seconds, Volts, Ampere, Meters, Simenes, Farads
// Description: This file will contain all the codes which will modify the variables or parameters at run time
// This script will implement the call to dynamic parameters and external currents
#include <vector>
#include <iostream>
#include <cmath>
#include "include/new_insilico.hpp"
#include "writing_conditions.hpp"
#include "data_types.hpp"
#include "physical_constants.hpp"
#include "global_variables.hpp"
void writing_conditions::current(state_type &variables, const state_type &dxdt, const double t, const unsigned index)
{
// Updates the RK4 counter function for cell
astron::globals::RK4CELL.counter_update(index,t);
// ------------------------------
// limit writing the output file
// double tstart = 200;
double tstart = 185;
double tstop = 300;
// double tstop = 210;
// --------------------------------
if( ((t >= tstart) && (t <= tstop))){
newinsilico::set_write_this_interval(true);
}
else{
newinsilico::set_write_this_interval(false);
}
// compulsory write when a release event occurs
// --------------------------------
double relflag = newinsilico::neuron_value(index, "syt45_relflag_glu");
if( ((t >= tstart) && (t <= tstop)) && (relflag >0)){
newinsilico::set_write_this_interval2(true);
}
else{
newinsilico::set_write_this_interval2(false);
}
// ----------------------------------
}
|
// See the file "COPYING" in the main distribution directory for copyright.
#include "zeek-config.h"
#include "zeek/DFA.h"
#include "zeek/EquivClass.h"
#include "zeek/Desc.h"
#include "zeek/Hash.h"
namespace zeek::detail {
unsigned int DFA_State::transition_counter = 0;
DFA_State::DFA_State(int arg_state_num, const EquivClass* ec,
NFA_state_list* arg_nfa_states,
AcceptingSet* arg_accept)
{
state_num = arg_state_num;
num_sym = ec->NumClasses();
nfa_states = arg_nfa_states;
accept = arg_accept;
mark = nullptr;
SymPartition(ec);
xtions = new DFA_State*[num_sym];
for ( int i = 0; i < num_sym; ++i )
xtions[i] = DFA_UNCOMPUTED_STATE_PTR;
}
DFA_State::~DFA_State()
{
delete [] xtions;
delete nfa_states;
delete accept;
delete meta_ec;
}
void DFA_State::AddXtion(int sym, DFA_State* next_state)
{
xtions[sym] = next_state;
}
void DFA_State::SymPartition(const EquivClass* ec)
{
// Partitioning is done by creating equivalence classes for those
// characters which have out-transitions from the given state. Thus
// we are really creating equivalence classes of equivalence classes.
meta_ec = new EquivClass(ec->NumClasses());
assert(nfa_states);
for ( int i = 0; i < nfa_states->length(); ++i )
{
NFA_State* n = (*nfa_states)[i];
int sym = n->TransSym();
if ( sym == SYM_EPSILON )
continue;
if ( sym != SYM_CCL )
{ // character transition
if ( ec->IsRep(sym) )
{
sym = ec->SymEquivClass(sym);
meta_ec->UniqueChar(sym);
}
continue;
}
// Character class.
meta_ec->CCL_Use(n->TransCCL());
}
meta_ec->BuildECs();
}
DFA_State* DFA_State::ComputeXtion(int sym, DFA_Machine* machine)
{
int equiv_sym = meta_ec->EquivRep(sym);
if ( xtions[equiv_sym] != DFA_UNCOMPUTED_STATE_PTR )
{
AddXtion(sym, xtions[equiv_sym]);
return xtions[sym];
}
const EquivClass* ec = machine->EC();
DFA_State* next_d;
NFA_state_list* ns = SymFollowSet(equiv_sym, ec);
if ( ns->length() > 0 )
{
NFA_state_list* state_set = epsilon_closure(ns);
if ( ! machine->StateSetToDFA_State(state_set, next_d, ec) )
delete state_set;
}
else
{
delete ns;
next_d = nullptr; // Jam
}
AddXtion(equiv_sym, next_d);
if ( sym != equiv_sym )
AddXtion(sym, next_d);
return xtions[sym];
}
void DFA_State::AppendIfNew(int sym, int_list* sym_list)
{
for ( auto value : *sym_list )
if ( value == sym )
return;
sym_list->push_back(sym);
}
NFA_state_list* DFA_State::SymFollowSet(int ec_sym, const EquivClass* ec)
{
NFA_state_list* ns = new NFA_state_list;
assert(nfa_states);
for ( int i = 0; i < nfa_states->length(); ++i )
{
NFA_State* n = (*nfa_states)[i];
if ( n->TransSym() == SYM_CCL )
{ // it's a character class
CCL* ccl = n->TransCCL();
int_list* syms = ccl->Syms();
if ( ccl->IsNegated() )
{
size_t j;
for ( j = 0; j < syms->size(); ++j )
{
// Loop through (sorted) negated
// character class, which has
// presumably already been converted
// over to equivalence classes.
if ( (*syms)[j] >= ec_sym )
break;
}
if ( j >= syms->size() || (*syms)[j] > ec_sym )
// Didn't find ec_sym in ccl.
n->AddXtionsTo(ns);
continue;
}
for ( auto sym : *syms )
{
if ( sym > ec_sym )
break;
if ( sym == ec_sym )
{
n->AddXtionsTo(ns);
break;
}
}
}
else if ( n->TransSym() == SYM_EPSILON )
{ // do nothing
}
else if ( ec->IsRep(n->TransSym()) )
{
if ( ec_sym == ec->SymEquivClass(n->TransSym()) )
n->AddXtionsTo(ns);
}
}
ns->resize(0);
return ns;
}
void DFA_State::ClearMarks()
{
if ( mark )
{
SetMark(nullptr);
for ( int i = 0; i < num_sym; ++i )
{
DFA_State* s = xtions[i];
if ( s && s != DFA_UNCOMPUTED_STATE_PTR )
xtions[i]->ClearMarks();
}
}
}
void DFA_State::Describe(ODesc* d) const
{
d->Add("DFA state");
}
void DFA_State::Dump(FILE* f, DFA_Machine* m)
{
if ( mark )
return;
fprintf(f, "\nDFA state %d:", StateNum());
if ( accept )
{
AcceptingSet::const_iterator it;
for ( it = accept->begin(); it != accept->end(); ++it )
fprintf(f, "%s accept #%d", it == accept->begin() ? "" : ",", *it);
}
fprintf(f, "\n");
int num_trans = 0;
for ( int sym = 0; sym < num_sym; ++sym )
{
DFA_State* s = xtions[sym];
if ( ! s )
continue;
// Look ahead for compression.
int i;
for ( i = sym + 1; i < num_sym; ++i )
if ( xtions[i] != s )
break;
char xbuf[512];
int r = m->Rep(sym);
if ( ! r )
r = '.';
if ( i == sym + 1 )
sprintf(xbuf, "'%c'", r);
else
sprintf(xbuf, "'%c'-'%c'", r, m->Rep(i-1));
if ( s == DFA_UNCOMPUTED_STATE_PTR )
fprintf(f, "%stransition on %s to <uncomputed>",
++num_trans == 1 ? "\t" : "\n\t", xbuf);
else
fprintf(f, "%stransition on %s to state %d",
++num_trans == 1 ? "\t" : "\n\t", xbuf,
s->StateNum());
sym = i - 1;
}
if ( num_trans > 0 )
fprintf(f, "\n");
SetMark(this);
for ( int sym = 0; sym < num_sym; ++sym )
{
DFA_State* s = xtions[sym];
if ( s && s != DFA_UNCOMPUTED_STATE_PTR )
s->Dump(f, m);
}
}
void DFA_State::Stats(unsigned int* computed, unsigned int* uncomputed)
{
for ( int sym = 0; sym < num_sym; ++sym )
{
DFA_State* s = xtions[sym];
if ( s == DFA_UNCOMPUTED_STATE_PTR )
(*uncomputed)++;
else
(*computed)++;
}
}
unsigned int DFA_State::Size()
{
return sizeof(*this)
+ util::pad_size(sizeof(DFA_State*) * num_sym)
+ (accept ? util::pad_size(sizeof(int) * accept->size()) : 0)
+ (nfa_states ? util::pad_size(sizeof(NFA_State*) * nfa_states->length()) : 0)
+ (meta_ec ? meta_ec->Size() : 0);
}
DFA_State_Cache::DFA_State_Cache()
{
hits = misses = 0;
}
DFA_State_Cache::~DFA_State_Cache()
{
for ( auto& entry : states )
{
assert(entry.second);
Unref(entry.second);
}
states.clear();
}
DFA_State* DFA_State_Cache::Lookup(const NFA_state_list& nfas, DigestStr* digest)
{
// We assume that state ID's don't exceed 10 digits, plus
// we allow one more character for the delimiter.
auto id_tag_buf = std::make_unique<u_char[]>(nfas.length() * 11 + 1);
auto id_tag = id_tag_buf.get();
u_char* p = id_tag;
for ( int i = 0; i < nfas.length(); ++i )
{
NFA_State* n = nfas[i];
if ( n->TransSym() != SYM_EPSILON || n->Accept() != NO_ACCEPT )
{
int id = n->ID();
do
{
*p++ = '0' + (char)(id % 10);
id /= 10;
}
while ( id > 0 );
*p++ = '&';
}
}
*p++ = '\0';
// We use the short MD5 instead of the full string for the
// HashKey because the data is copied into the key.
hash128_t hash;
KeyedHash::Hash128(id_tag, p - id_tag, &hash);
*digest = DigestStr(reinterpret_cast<const unsigned char*>(hash), 16);
auto entry = states.find(*digest);
if ( entry == states.end() )
{
++misses;
return nullptr;
}
++hits;
digest->clear();
return entry->second;
}
DFA_State* DFA_State_Cache::Insert(DFA_State* state, DigestStr digest)
{
states.emplace(std::move(digest), state);
return state;
}
void DFA_State_Cache::GetStats(Stats* s)
{
s->dfa_states = 0;
s->nfa_states = 0;
s->computed = 0;
s->uncomputed = 0;
s->mem = 0;
s->hits = hits;
s->misses = misses;
for ( const auto& state : states )
{
DFA_State* e = state.second;
++s->dfa_states;
s->nfa_states += e->NFAStateNum();
e->Stats(&s->computed, &s->uncomputed);
s->mem += util::pad_size(e->Size()) + padded_sizeof(*e);
}
}
DFA_Machine::DFA_Machine(NFA_Machine* n, EquivClass* arg_ec)
{
state_count = 0;
nfa = n;
Ref(n);
ec = arg_ec;
dfa_state_cache = new DFA_State_Cache();
NFA_state_list* ns = new NFA_state_list;
ns->push_back(n->FirstState());
if ( ns->length() > 0 )
{
NFA_state_list* state_set = epsilon_closure(ns);
StateSetToDFA_State(state_set, start_state, ec);
}
else
{
start_state = nullptr; // Jam
delete ns;
}
}
DFA_Machine::~DFA_Machine()
{
delete dfa_state_cache;
Unref(nfa);
}
void DFA_Machine::Describe(ODesc* d) const
{
d->Add("DFA machine");
}
void DFA_Machine::Dump(FILE* f)
{
start_state->Dump(f, this);
start_state->ClearMarks();
}
unsigned int DFA_Machine::MemoryAllocation() const
{
DFA_State_Cache::Stats s;
dfa_state_cache->GetStats(&s);
// FIXME: Count *ec?
return padded_sizeof(*this)
+ s.mem
+ padded_sizeof(*start_state)
+ nfa->MemoryAllocation();
}
bool DFA_Machine::StateSetToDFA_State(NFA_state_list* state_set,
DFA_State*& d, const EquivClass* ec)
{
DigestStr digest;
d = dfa_state_cache->Lookup(*state_set, &digest);
if ( d )
return false;
AcceptingSet* accept = new AcceptingSet;
for ( int i = 0; i < state_set->length(); ++i )
{
int acc = (*state_set)[i]->Accept();
if ( acc != NO_ACCEPT )
accept->insert(acc);
}
if ( accept->empty() )
{
delete accept;
accept = nullptr;
}
DFA_State* ds = new DFA_State(state_count++, ec, state_set, accept);
d = dfa_state_cache->Insert(ds, std::move(digest));
return true;
}
int DFA_Machine::Rep(int sym)
{
for ( int i = 0; i < NUM_SYM; ++i )
if ( ec->SymEquivClass(i) == sym )
return i;
return -1;
}
} // namespace zeek::detail
|
// Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2014-2017 XDN-project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "StdInputStream.h"
namespace Common {
StdInputStream::StdInputStream(std::istream& in) : in(in) {
}
size_t StdInputStream::readSome(void* data, size_t size) {
in.read(static_cast<char*>(data), size);
return in.gcount();
}
}
|
/*
Copyright (c) 2013, Philipp Krähenbühl
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Stanford University nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Philipp Krähenbühl ''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 Philipp Krähenbühl 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 "common.h"
#include <iostream>
#include <cstdlib>
#include <iostream>
#include <iomanip>
// Store the colors we read, so that we can write them again.
int nColors = 0;
int colors[255];
int getColor( const unsigned char * c ){
return c[0] + 256*c[1] + 256*256*c[2];
}
void putColor( unsigned char * c, int cc ){
c[0] = cc&0xff; c[1] = (cc>>8)&0xff; c[2] = (cc>>16)&0xff;
}
// Produce a color image from a bunch of labels
unsigned char * colorize( const VectorXs & labeling, int W, int H ){
unsigned char * r = new unsigned char[ W*H*3 ];
for( int k=0; k<W*H; k++ ){
int c = colors[ labeling[k] ];
putColor( r+3*k, c );
}
//printf("%d %d %d \n",r[0],r[1],r[2]);
return r;
}
// Read the labeling from a file
VectorXs getLabeling( const unsigned char * im, int N, int M ){
VectorXs res(N);
//printf("%d %d %d \n",im[0],im[1],im[2]);
for( int k=0; k<N; k++ ){
// Map the color to a label
const unsigned char * rgb = im + 3*k;
int c = getColor( im + 3*k );
int i;
for( i=0;i<nColors && c!=colors[i]; i++ );
if (c && i==nColors){
if (i<M) {
printf("RGB: %d %d %d \n", rgb[0], rgb[1], rgb[2]);
colors[nColors++] = c;
}
else
c=0;
}
// Include all pixels as classes (no IGNORE class defined)
// res[k] = c?i:-1;
res[k] = i;
}
return res;
}
// Prints image data to console
void print( VectorXs data, const int nrows, const int ncols) {
const uint32_t& truc = 130u;
std::cout << std::fixed;
std::cout << std::setprecision(6);
for( auto i = 100u; i <= truc && i < nrows; ++i )
{ // iterate rows
if ( i == truc ) { // add ellipsis for truncated rows
std::cout << " ... " << std::endl;
i = nrows - 1u;
}
for( auto j = 100u; j <= truc && j < ncols; ++j )
{ // iterate columns
if ( j == truc )
{ // add ellipsis for truncated cols
std::cout << "... ";
j = ncols - 1u;
}
std::cout << ' ' << data[ncols * i + j] << ' ';
}
std::cout << std::endl;
}
}
|
#include "Parser.h"
#include <stdexcept>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
using namespace std;
/* vector with each flag and their corresponding description */
vector<pair<string, string>> const options{
{"-h, --help", "Show this message."},
{"-t, --print-tree", "Print the expression tree."},
{"-p, --print-expression", "Print the inline expression."},
{"-e, --expand", "Expand all parenthesised operands\n"
"in multiplication statements."}
};
void show_help(string const& program)
{
cout << "Usage: " << program << " [OPTIONS]\n"
<< "A simple terminal based floating point calculator.\n"
<< "can handle +,-,* and /.\n"
<< "OPTIONS:\n";
for (auto const& p : options)
{
/* print flags */
cout << " " << left << setw(24) << p.first << " ";
/* print the description, handle line by line
* to make sure that the indentation is correct. */
istringstream iss{p.second};
string line;
/* simply print the first line */
getline(iss, line);
cout << line << endl;
/* all successive lines should be indented
* to make up for the flags column */
while (getline(iss, line))
{
cout << " " << setw(24) << "" << " " << line << endl;
}
}
}
int main(int argc, char* argv[]) try
{
/* all possible flags */
bool print_expression{false};
bool print_tree{false};
bool expand{false};
/* parse arguments */
for (int i{1}; i < argc; ++i)
{
string arg{argv[i]};
if (arg == "--help" || arg == "-h")
{
show_help(argv[0]);
return 1;
}
else if (arg == "--print-expression" || arg == "-p")
{
print_expression = true;
}
else if (arg == "--print-tree" || arg == "-t")
{
print_tree = true;
}
else if (arg == "--expand" || arg == "-e")
{
expand = true;
}
else
{
throw invalid_argument{
"Unknown argument '" + arg + "', try --help."};
}
}
/* get expression from user */
string input;
getline(cin, input);
/* parse the expression */
Expression result{parse(input)};
if (expand)
{
result.expand();
}
/* let the arguments decide what should be printed */
if (print_tree)
{
result.print_tree(cout);
}
else if (print_expression)
{
result.print(cout);
}
else
{
cout << result.evaluate();
}
cout << endl;
}
catch (invalid_argument& e)
{
cerr << "Error: " << e.what() << endl;
return 1;
}
catch (parser_error& e)
{
cerr << "Error during parse: " << e.what() << endl;
return 1;
}
catch (...)
{
cerr << "Unkown error occured." << endl;
return 1;
}
|
// ReDucTor is an awesome guy who helped me a lot
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Server.h"
#include "ClientHandle.h"
#include "Mobs/Monster.h"
#include "Root.h"
#include "World.h"
#include "Bindings/PluginManager.h"
#include "ChatColor.h"
#include "Entities/Player.h"
#include "Inventory.h"
#include "Item.h"
#include "FurnaceRecipe.h"
#include "WebAdmin.h"
#include "Protocol/ProtocolRecognizer.h"
#include "CommandOutput.h"
#include "FastRandom.h"
#include "IniFile.h"
#include <fstream>
#include <sstream>
#include <iostream>
////////////////////////////////////////////////////////////////////////////////
// cServerListenCallbacks:
class cServerListenCallbacks:
public cNetwork::cListenCallbacks
{
cServer & m_Server;
UInt16 m_Port;
virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) override
{
return m_Server.OnConnectionAccepted(a_RemoteIPAddress);
}
virtual void OnAccepted(cTCPLink & a_Link) override {}
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override
{
LOGWARNING("Cannot listen on port %d: %d (%s).", m_Port, a_ErrorCode, a_ErrorMsg.c_str());
}
public:
cServerListenCallbacks(cServer & a_Server, UInt16 a_Port):
m_Server(a_Server),
m_Port(a_Port)
{
}
};
////////////////////////////////////////////////////////////////////////////////
// cServer::cTickThread:
cServer::cTickThread::cTickThread(cServer & a_Server) :
Super("Server Ticker"),
m_Server(a_Server)
{
}
void cServer::cTickThread::Execute(void)
{
auto LastTime = std::chrono::steady_clock::now();
static const auto msPerTick = std::chrono::milliseconds(50);
while (!m_ShouldTerminate)
{
auto NowTime = std::chrono::steady_clock::now();
auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(NowTime - LastTime).count();
m_Server.Tick(static_cast<float>(msec));
auto TickTime = std::chrono::steady_clock::now() - NowTime;
if (TickTime < msPerTick)
{
// Stretch tick time until it's at least msPerTick
std::this_thread::sleep_for(msPerTick - TickTime);
}
LastTime = NowTime;
}
}
////////////////////////////////////////////////////////////////////////////////
// cServer:
cServer::cServer(void) :
m_PlayerCount(0),
m_ClientViewDistance(0),
m_bIsConnected(false),
m_RCONServer(*this),
m_MaxPlayers(0),
m_bIsHardcore(false),
m_TickThread(*this),
m_ShouldAuthenticate(false),
m_UpTime(0)
{
// Initialize the LuaStateTracker singleton before the app goes multithreaded:
cLuaStateTracker::GetStats();
}
void cServer::ClientMovedToWorld(const cClientHandle * a_Client)
{
cCSLock Lock(m_CSClients);
m_ClientsToRemove.push_back(const_cast<cClientHandle *>(a_Client));
}
void cServer::PlayerCreated()
{
m_PlayerCount++;
}
void cServer::PlayerDestroyed()
{
m_PlayerCount--;
}
bool cServer::InitServer(cSettingsRepositoryInterface & a_Settings, bool a_ShouldAuth)
{
m_Description = a_Settings.GetValueSet("Server", "Description", "Cuberite - in C++!");
m_ShutdownMessage = a_Settings.GetValueSet("Server", "ShutdownMessage", "Server shutdown");
m_MaxPlayers = static_cast<size_t>(a_Settings.GetValueSetI("Server", "MaxPlayers", 100));
m_bIsHardcore = a_Settings.GetValueSetB("Server", "HardcoreEnabled", false);
m_bAllowMultiLogin = a_Settings.GetValueSetB("Server", "AllowMultiLogin", false);
m_ResourcePackUrl = a_Settings.GetValueSet("Server", "ResourcePackUrl", "");
m_FaviconData = Base64Encode(cFile::ReadWholeFile(AString("favicon.png"))); // Will return empty string if file nonexistant; client doesn't mind
if (m_bIsConnected)
{
LOGERROR("ERROR: Trying to initialize server while server is already running!");
return false;
}
LOGINFO("Compatible clients: %s", MCS_CLIENT_VERSIONS);
LOGD("Compatible protocol versions %s", MCS_PROTOCOL_VERSIONS);
m_Ports = ReadUpgradeIniPorts(a_Settings, "Server", "Ports", "Port", "PortsIPv6", "25565");
m_RCONServer.Initialize(a_Settings);
m_bIsConnected = true;
m_ServerID = "-";
m_ShouldAuthenticate = a_ShouldAuth;
if (m_ShouldAuthenticate)
{
auto & rand = GetRandomProvider();
unsigned int r1 = rand.RandInt<unsigned int>(1000000000U, 0x7fffffffU);
unsigned int r2 = rand.RandInt<unsigned int>(1000000000U, 0x7fffffffU);
std::ostringstream sid;
sid << std::hex << r1;
sid << std::hex << r2;
m_ServerID = sid.str();
m_ServerID.resize(16, '0');
}
// Check if both BungeeCord and online mode are on, if so, warn the admin:
m_ShouldAllowBungeeCord = a_Settings.GetValueSetB("Authentication", "AllowBungeeCord", false);
if (m_ShouldAllowBungeeCord && m_ShouldAuthenticate)
{
LOGWARNING("WARNING: BungeeCord is allowed and server set to online mode. This is unsafe and will not work properly. Disable either authentication or BungeeCord in settings.ini.");
}
m_ShouldAllowMultiWorldTabCompletion = a_Settings.GetValueSetB("Server", "AllowMultiWorldTabCompletion", true);
m_ShouldLimitPlayerBlockChanges = a_Settings.GetValueSetB("AntiCheat", "LimitPlayerBlockChanges", true);
const auto ClientViewDistance = a_Settings.GetValueSetI("Server", "DefaultViewDistance", cClientHandle::DEFAULT_VIEW_DISTANCE);
if (ClientViewDistance < cClientHandle::MIN_VIEW_DISTANCE)
{
m_ClientViewDistance = cClientHandle::MIN_VIEW_DISTANCE;
LOGINFO("Setting default view distance to the minimum of %d", m_ClientViewDistance);
}
else if (ClientViewDistance > cClientHandle::MAX_VIEW_DISTANCE)
{
m_ClientViewDistance = cClientHandle::MAX_VIEW_DISTANCE;
LOGINFO("Setting default view distance to the maximum of %d", m_ClientViewDistance);
}
else
{
m_ClientViewDistance = ClientViewDistance;
}
PrepareKeys();
return true;
}
bool cServer::RegisterForgeMod(const AString & a_ModName, const AString & a_ModVersion, UInt32 a_ProtocolVersionNumber)
{
auto & Mods = RegisteredForgeMods(a_ProtocolVersionNumber);
return Mods.insert({a_ModName, a_ModVersion}).second;
}
void cServer::UnregisterForgeMod(const AString & a_ModName, UInt32 a_ProtocolVersionNumber)
{
auto & Mods = RegisteredForgeMods(a_ProtocolVersionNumber);
auto it = Mods.find(a_ModName);
if (it != Mods.end())
{
Mods.erase(it);
}
}
AStringMap & cServer::RegisteredForgeMods(const UInt32 a_Protocol)
{
auto it = m_ForgeModsByVersion.find(a_Protocol);
if (it == m_ForgeModsByVersion.end())
{
AStringMap mods;
m_ForgeModsByVersion.insert({a_Protocol, mods});
return m_ForgeModsByVersion.find(a_Protocol)->second;
}
return it->second;
}
const AStringMap & cServer::GetRegisteredForgeMods(const UInt32 a_Protocol)
{
return RegisteredForgeMods(a_Protocol);
}
bool cServer::IsPlayerInQueue(const AString & a_Username)
{
cCSLock Lock(m_CSClients);
for (const auto & client : m_Clients)
{
if ((client->GetUsername()).compare(a_Username) == 0)
{
return true;
}
}
return false;
}
void cServer::PrepareKeys(void)
{
LOGD("Generating protocol encryption keypair...");
VERIFY(m_PrivateKey.Generate(1024));
m_PublicKeyDER = m_PrivateKey.GetPubKeyDER();
}
cTCPLink::cCallbacksPtr cServer::OnConnectionAccepted(const AString & a_RemoteIPAddress)
{
LOGD("Client \"%s\" connected!", a_RemoteIPAddress.c_str());
cClientHandlePtr NewHandle = std::make_shared<cClientHandle>(a_RemoteIPAddress, m_ClientViewDistance);
cCSLock Lock(m_CSClients);
m_Clients.push_back(NewHandle);
return std::move(NewHandle);
}
void cServer::Tick(float a_Dt)
{
// Update server uptime
m_UpTime++;
// Send the tick to the plugins, as well as let the plugin manager reload, if asked to (issue #102):
cPluginManager::Get()->Tick(a_Dt);
// Process all the queued commands:
TickCommands();
// Tick all clients not yet assigned to a world:
TickClients(a_Dt);
// Process all queued tasks
TickQueuedTasks();
}
void cServer::TickClients(float a_Dt)
{
cClientHandlePtrs RemoveClients;
{
cCSLock Lock(m_CSClients);
// Remove clients that have moved to a world (the world will be ticking them from now on)
for (auto itr = m_ClientsToRemove.begin(), end = m_ClientsToRemove.end(); itr != end; ++itr)
{
for (auto itrC = m_Clients.begin(), endC = m_Clients.end(); itrC != endC; ++itrC)
{
if (itrC->get() == *itr)
{
m_Clients.erase(itrC);
break;
}
}
} // for itr - m_ClientsToRemove[]
m_ClientsToRemove.clear();
// Tick the remaining clients, take out those that have been destroyed into RemoveClients
for (auto itr = m_Clients.begin(); itr != m_Clients.end();)
{
auto & Client = *itr;
Client->ServerTick(a_Dt);
if (Client->IsDestroyed())
{
// Delete the client later, when CS is not held, to avoid deadlock: https://forum.cuberite.org/thread-374.html
RemoveClients.push_back(std::move(Client));
itr = m_Clients.erase(itr);
continue;
}
++itr;
} // for itr - m_Clients[]
}
// Delete the clients that have been destroyed
RemoveClients.clear();
}
bool cServer::Start(void)
{
for (const auto & port: m_Ports)
{
UInt16 PortNum;
if (!StringToInteger(port, PortNum))
{
LOGWARNING("Invalid port specified for server: \"%s\". Ignoring.", port.c_str());
continue;
}
auto Handle = cNetwork::Listen(PortNum, std::make_shared<cServerListenCallbacks>(*this, PortNum));
if (Handle->IsListening())
{
m_ServerHandles.push_back(Handle);
}
} // for port - Ports[]
if (m_ServerHandles.empty())
{
LOGERROR("Couldn't open any ports. Aborting the server");
return false;
}
m_TickThread.Start();
return true;
}
bool cServer::Command(cClientHandle & a_Client, AString & a_Cmd)
{
bool Res = cRoot::Get()->DoWithPlayerByUUID(
a_Client.GetUUID(),
[&](cPlayer & a_Player)
{
return cRoot::Get()->GetPluginManager()->CallHookChat(a_Player, a_Cmd);
}
);
return Res;
}
void cServer::QueueExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
// Put the command into a queue (Alleviates FS #363):
cCSLock Lock(m_CSPendingCommands);
m_PendingCommands.emplace_back(a_Cmd, &a_Output);
}
void cServer::ScheduleTask(cTickTime a_DelayTicks, std::function<void(cServer &)> a_Task)
{
const auto TargetTick = a_DelayTicks + m_UpTime;
// Insert the task into the list of scheduled tasks
{
cCSLock Lock(m_CSTasks);
m_Tasks.emplace_back(TargetTick, std::move(a_Task));
}
}
void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
AStringVector split = StringSplit(a_Cmd, " ");
if (split.empty())
{
return;
}
// "stop" and "restart" are handled in cRoot::ExecuteConsoleCommand, our caller, due to its access to controlling variables
// "help" and "reload" are to be handled by Cuberite, so that they work no matter what
if (split[0] == "help")
{
PrintHelp(split, a_Output);
a_Output.Finished();
return;
}
else if (split[0] == "reload")
{
if (split.size() > 1)
{
cPluginManager::Get()->ReloadPlugin(split[1]);
a_Output.Out("Plugin reload scheduled");
}
else
{
cPluginManager::Get()->ReloadPlugins();
}
a_Output.Finished();
return;
}
else if (split[0] == "reloadplugins")
{
cPluginManager::Get()->ReloadPlugins();
a_Output.Out("Plugins reloaded");
a_Output.Finished();
return;
}
else if (split[0] == "reloadweb")
{
cRoot::Get()->GetWebAdmin()->Reload();
a_Output.Out("WebAdmin configuration reloaded");
a_Output.Finished();
return;
}
else if (split[0] == "load")
{
if (split.size() > 1)
{
cPluginManager::Get()->RefreshPluginList(); // Refresh the plugin list, so that if the plugin was added just now, it is loadable
a_Output.Out(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin");
}
else
{
a_Output.Out("Usage: load <PluginFolder>");
}
a_Output.Finished();
return;
}
else if (split[0] == "unload")
{
if (split.size() > 1)
{
cPluginManager::Get()->UnloadPlugin(split[1]);
a_Output.Out("Plugin unload scheduled");
}
else
{
a_Output.Out("Usage: unload <PluginFolder>");
}
a_Output.Finished();
return;
}
if (split[0] == "destroyentities")
{
cRoot::Get()->ForEachWorld([](cWorld & a_World)
{
a_World.ForEachEntity([](cEntity & a_Entity)
{
if (!a_Entity.IsPlayer())
{
a_Entity.Destroy();
}
return false;
}
);
return false;
}
);
a_Output.Out("Destroyed all entities");
a_Output.Finished();
return;
}
// There is currently no way a plugin can do these (and probably won't ever be):
else if (split[0].compare("chunkstats") == 0)
{
cRoot::Get()->LogChunkStats(a_Output);
a_Output.Finished();
return;
}
else if (split[0].compare("luastats") == 0)
{
a_Output.Out(cLuaStateTracker::GetStats());
a_Output.Finished();
return;
}
else if (cPluginManager::Get()->ExecuteConsoleCommand(split, a_Output, a_Cmd))
{
a_Output.Finished();
return;
}
a_Output.Out("Unknown command, type 'help' for all commands.");
a_Output.Finished();
}
void cServer::PrintHelp(const AStringVector & a_Split, cCommandOutputCallback & a_Output)
{
UNUSED(a_Split);
typedef std::pair<AString, AString> AStringPair;
typedef std::vector<AStringPair> AStringPairs;
class cCallback :
public cPluginManager::cCommandEnumCallback
{
public:
cCallback(void) : m_MaxLen(0) {}
virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override
{
UNUSED(a_Plugin);
UNUSED(a_Permission);
if (!a_HelpString.empty())
{
m_Commands.push_back(AStringPair(a_Command, a_HelpString));
if (m_MaxLen < a_Command.length())
{
m_MaxLen = a_Command.length();
}
}
return false;
}
AStringPairs m_Commands;
size_t m_MaxLen;
} Callback;
cPluginManager::Get()->ForEachConsoleCommand(Callback);
std::sort(Callback.m_Commands.begin(), Callback.m_Commands.end());
for (AStringPairs::const_iterator itr = Callback.m_Commands.begin(), end = Callback.m_Commands.end(); itr != end; ++itr)
{
const AStringPair & cmd = *itr;
a_Output.Out(Printf("%-*s - %s\n", static_cast<int>(Callback.m_MaxLen), cmd.first.c_str(), cmd.second.c_str()));
} // for itr - Callback.m_Commands[]
}
void cServer::BindBuiltInConsoleCommands(void)
{
// Create an empty handler - the actual handling for the commands is performed before they are handed off to cPluginManager
class cEmptyHandler:
public cPluginManager::cCommandHandler
{
virtual bool ExecuteCommand(
const AStringVector & a_Split,
cPlayer * a_Player,
const AString & a_Command,
cCommandOutputCallback * a_Output = nullptr
) override
{
return false;
}
};
auto handler = std::make_shared<cEmptyHandler>();
// Register internal commands:
cPluginManager * PlgMgr = cPluginManager::Get();
PlgMgr->BindConsoleCommand("help", nullptr, handler, "Shows the available commands");
PlgMgr->BindConsoleCommand("reload", nullptr, handler, "Reloads all plugins");
PlgMgr->BindConsoleCommand("reloadweb", nullptr, handler, "Reloads the webadmin configuration");
PlgMgr->BindConsoleCommand("restart", nullptr, handler, "Restarts the server cleanly");
PlgMgr->BindConsoleCommand("stop", nullptr, handler, "Stops the server cleanly");
PlgMgr->BindConsoleCommand("chunkstats", nullptr, handler, "Displays detailed chunk memory statistics");
PlgMgr->BindConsoleCommand("load", nullptr, handler, "Adds and enables the specified plugin");
PlgMgr->BindConsoleCommand("unload", nullptr, handler, "Disables the specified plugin");
PlgMgr->BindConsoleCommand("destroyentities", nullptr, handler, "Destroys all entities in all worlds");
}
void cServer::Shutdown(void)
{
// Stop listening on all sockets:
for (const auto & srv: m_ServerHandles)
{
srv->Close();
}
m_ServerHandles.clear();
// Notify the tick thread and wait for it to terminate:
m_TickThread.Stop();
// Save all chunks in all worlds, wait for chunks to be sent to the ChunkStorage queue for each world:
cRoot::Get()->SaveAllChunksNow();
// Remove all clients:
cCSLock Lock(m_CSClients);
for (auto itr = m_Clients.begin(); itr != m_Clients.end(); ++itr)
{
(*itr)->Destroy();
}
m_Clients.clear();
}
void cServer::KickUser(int a_ClientID, const AString & a_Reason)
{
cCSLock Lock(m_CSClients);
for (auto itr = m_Clients.begin(); itr != m_Clients.end(); ++itr)
{
if ((*itr)->GetUniqueID() == a_ClientID)
{
(*itr)->Kick(a_Reason);
}
} // for itr - m_Clients[]
}
void cServer::AuthenticateUser(int a_ClientID, const AString & a_Name, const cUUID & a_UUID, const Json::Value & a_Properties)
{
cCSLock Lock(m_CSClients);
// Check max players condition within lock (expect server and authenticator thread to both call here)
if (GetNumPlayers() >= GetMaxPlayers())
{
KickUser(a_ClientID, "The server is currently full :(" "\n" "Try again later?");
return;
}
for (auto itr = m_Clients.begin(); itr != m_Clients.end(); ++itr)
{
if ((*itr)->GetUniqueID() == a_ClientID)
{
(*itr)->Authenticate(a_Name, a_UUID, a_Properties);
return;
}
} // for itr - m_Clients[]
}
void cServer::TickCommands(void)
{
decltype(m_PendingCommands) PendingCommands;
{
cCSLock Lock(m_CSPendingCommands);
std::swap(PendingCommands, m_PendingCommands);
}
// Execute any pending commands:
for (const auto & Command : PendingCommands)
{
ExecuteConsoleCommand(Command.first, *Command.second);
}
}
void cServer::TickQueuedTasks(void)
{
// Move the tasks to be executed to a seperate vector to avoid deadlocks on
// accessing m_Tasks
decltype(m_Tasks) Tasks;
{
cCSLock Lock(m_CSTasks);
if (m_Tasks.empty())
{
return;
}
// Partition everything to be executed by returning false to move to end
// of list if time reached
auto MoveBeginIterator = std::partition(
m_Tasks.begin(), m_Tasks.end(),
[this](const decltype(m_Tasks)::value_type & a_Task)
{
return a_Task.first >= m_UpTime;
});
// Cut all the due tasks from m_Tasks into Tasks:
Tasks.insert(
Tasks.end(), std::make_move_iterator(MoveBeginIterator),
std::make_move_iterator(m_Tasks.end()));
m_Tasks.erase(MoveBeginIterator, m_Tasks.end());
}
// Execute each task:
for (const auto & Task : Tasks)
{
Task.second(*this);
} // for itr - m_Tasks[]
}
|
//WAp to find cube of a number using function
#include <stdio.h>
int cube (int); // Function declaration
int main()
{
int n, c;
printf("Enter any number: ");
scanf("%d", &n); //Inputting number from user
c = cube(n);
printf("Cube of %d is %d", n, c);
}
cube(int n) //Function to find cube of any number
{
return (n * n * n);
}
|
#include "Sortings.hpp"
void main() {
int a[] = { 1, 3, 4 };
Sortings::MergeSort<int>(a, 3);
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/compositor/layer_animation_element.h"
#include "base/compiler_specific.h"
#include "cc/animation/animation.h"
#include "cc/animation/animation_id_provider.h"
#include "ui/base/animation/tween.h"
#include "ui/compositor/float_animation_curve_adapter.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_delegate.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/transform_animation_curve_adapter.h"
#include "ui/gfx/interpolated_transform.h"
namespace ui {
namespace {
// The factor by which duration is scaled up or down when
// ScopedAnimationDurationScaleMode::duration_scale_mode() is SLOW_DURATION or
// FAST_DURATION.
const int kSlowDurationScaleFactor = 4;
const int kFastDurationScaleFactor = 4;
// Pause -----------------------------------------------------------------------
class Pause : public LayerAnimationElement {
public:
Pause(const AnimatableProperties& properties, base::TimeDelta duration)
: LayerAnimationElement(properties, duration) {
}
virtual ~Pause() {}
private:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {}
virtual bool OnProgress(double t,
LayerAnimationDelegate* delegate) OVERRIDE {
return false;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
DISALLOW_COPY_AND_ASSIGN(Pause);
};
// TransformTransition ---------------------------------------------------------
class TransformTransition : public LayerAnimationElement {
public:
TransformTransition(const gfx::Transform& target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
target_(target) {
}
virtual ~TransformTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetTransformForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetTransformFromAnimation(
Tween::ValueBetween(t, start_, target_));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->transform = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::TRANSFORM);
return properties;
}
gfx::Transform start_;
const gfx::Transform target_;
DISALLOW_COPY_AND_ASSIGN(TransformTransition);
};
// InterpolatedTransformTransition ---------------------------------------------
class InterpolatedTransformTransition : public LayerAnimationElement {
public:
InterpolatedTransformTransition(InterpolatedTransform* interpolated_transform,
base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
interpolated_transform_(interpolated_transform) {
}
virtual ~InterpolatedTransformTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetTransformFromAnimation(
interpolated_transform_->Interpolate(static_cast<float>(t)));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->transform = interpolated_transform_->Interpolate(1.0f);
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::TRANSFORM);
return properties;
}
scoped_ptr<InterpolatedTransform> interpolated_transform_;
DISALLOW_COPY_AND_ASSIGN(InterpolatedTransformTransition);
};
// BoundsTransition ------------------------------------------------------------
class BoundsTransition : public LayerAnimationElement {
public:
BoundsTransition(const gfx::Rect& target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
target_(target) {
}
virtual ~BoundsTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetBoundsForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetBoundsFromAnimation(Tween::ValueBetween(t, start_, target_));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->bounds = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::BOUNDS);
return properties;
}
gfx::Rect start_;
const gfx::Rect target_;
DISALLOW_COPY_AND_ASSIGN(BoundsTransition);
};
// OpacityTransition -----------------------------------------------------------
class OpacityTransition : public LayerAnimationElement {
public:
OpacityTransition(float target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
start_(0.0f),
target_(target) {
}
virtual ~OpacityTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetOpacityForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetOpacityFromAnimation(Tween::ValueBetween(t, start_, target_));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->opacity = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::OPACITY);
return properties;
}
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(OpacityTransition);
};
// VisibilityTransition --------------------------------------------------------
class VisibilityTransition : public LayerAnimationElement {
public:
VisibilityTransition(bool target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
start_(false),
target_(target) {
}
virtual ~VisibilityTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetVisibilityForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetVisibilityFromAnimation(t == 1.0 ? target_ : start_);
return t == 1.0;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->visibility = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::VISIBILITY);
return properties;
}
bool start_;
const bool target_;
DISALLOW_COPY_AND_ASSIGN(VisibilityTransition);
};
// BrightnessTransition --------------------------------------------------------
class BrightnessTransition : public LayerAnimationElement {
public:
BrightnessTransition(float target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
start_(0.0f),
target_(target) {
}
virtual ~BrightnessTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetBrightnessForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetBrightnessFromAnimation(
Tween::ValueBetween(t, start_, target_));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->brightness = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::BRIGHTNESS);
return properties;
}
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(BrightnessTransition);
};
// GrayscaleTransition ---------------------------------------------------------
class GrayscaleTransition : public LayerAnimationElement {
public:
GrayscaleTransition(float target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
start_(0.0f),
target_(target) {
}
virtual ~GrayscaleTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetGrayscaleForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetGrayscaleFromAnimation(
Tween::ValueBetween(t, start_, target_));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->grayscale = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::GRAYSCALE);
return properties;
}
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(GrayscaleTransition);
};
// ColorTransition -------------------------------------------------------------
class ColorTransition : public LayerAnimationElement {
public:
ColorTransition(SkColor target, base::TimeDelta duration)
: LayerAnimationElement(GetProperties(), duration),
start_(SK_ColorBLACK),
target_(target) {
}
virtual ~ColorTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetColorForAnimation();
}
virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetColorFromAnimation(
SkColorSetARGB(
Tween::ValueBetween(t,
static_cast<int>(SkColorGetA(start_)),
static_cast<int>(SkColorGetA(target_))),
Tween::ValueBetween(t,
static_cast<int>(SkColorGetR(start_)),
static_cast<int>(SkColorGetR(target_))),
Tween::ValueBetween(t,
static_cast<int>(SkColorGetG(start_)),
static_cast<int>(SkColorGetG(target_))),
Tween::ValueBetween(t,
static_cast<int>(SkColorGetB(start_)),
static_cast<int>(SkColorGetB(target_)))));
return true;
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->color = target_;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::COLOR);
return properties;
}
SkColor start_;
const SkColor target_;
DISALLOW_COPY_AND_ASSIGN(ColorTransition);
};
// ThreadedLayerAnimationElement -----------------------------------------------
class ThreadedLayerAnimationElement : public LayerAnimationElement {
public:
ThreadedLayerAnimationElement(const AnimatableProperties& properties,
base::TimeDelta duration)
: LayerAnimationElement(properties, duration) {
}
virtual ~ThreadedLayerAnimationElement() {}
virtual bool IsThreaded() const OVERRIDE {
return (duration() != base::TimeDelta());
}
protected:
virtual bool OnProgress(double t,
LayerAnimationDelegate* delegate) OVERRIDE {
if (t < 1.0)
return false;
if (Started()) {
delegate->RemoveThreadedAnimation(animation_id());
}
OnEnd(delegate);
return true;
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {
if (delegate && Started()) {
delegate->RemoveThreadedAnimation(animation_id());
}
}
virtual void RequestEffectiveStart(
LayerAnimationDelegate* delegate) OVERRIDE {
DCHECK(animation_group_id());
if (duration() == base::TimeDelta()) {
set_effective_start_time(requested_start_time());
return;
}
set_effective_start_time(base::TimeTicks());
scoped_ptr<cc::Animation> animation = CreateCCAnimation();
animation->set_needs_synchronized_start_time(true);
delegate->AddThreadedAnimation(animation.Pass());
}
virtual void OnEnd(LayerAnimationDelegate* delegate) = 0;
virtual scoped_ptr<cc::Animation> CreateCCAnimation() = 0;
private:
DISALLOW_COPY_AND_ASSIGN(ThreadedLayerAnimationElement);
};
// ThreadedOpacityTransition ---------------------------------------------------
class ThreadedOpacityTransition : public ThreadedLayerAnimationElement {
public:
ThreadedOpacityTransition(float target, base::TimeDelta duration)
: ThreadedLayerAnimationElement(GetProperties(), duration),
start_(0.0f),
target_(target) {
}
virtual ~ThreadedOpacityTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetOpacityForAnimation();
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {
if (delegate && Started()) {
ThreadedLayerAnimationElement::OnAbort(delegate);
delegate->SetOpacityFromAnimation(Tween::ValueBetween(
Tween::CalculateValue(tween_type(), last_progressed_fraction()),
start_,
target_));
}
}
virtual void OnEnd(LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetOpacityFromAnimation(target_);
}
virtual scoped_ptr<cc::Animation> CreateCCAnimation() OVERRIDE {
scoped_ptr<cc::AnimationCurve> animation_curve(
new FloatAnimationCurveAdapter(tween_type(),
start_,
target_,
duration()));
scoped_ptr<cc::Animation> animation(
cc::Animation::Create(animation_curve.Pass(),
animation_id(),
animation_group_id(),
cc::Animation::Opacity));
return animation.Pass();
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->opacity = target_;
}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::OPACITY);
return properties;
}
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(ThreadedOpacityTransition);
};
// ThreadedTransformTransition -------------------------------------------------
class ThreadedTransformTransition : public ThreadedLayerAnimationElement {
public:
ThreadedTransformTransition(const gfx::Transform& target,
base::TimeDelta duration)
: ThreadedLayerAnimationElement(GetProperties(), duration),
target_(target) {
}
virtual ~ThreadedTransformTransition() {}
protected:
virtual void OnStart(LayerAnimationDelegate* delegate) OVERRIDE {
start_ = delegate->GetTransformForAnimation();
float device_scale_factor = delegate->GetDeviceScaleFactor();
cc_start_ = Layer::ConvertTransformToCCTransform(start_,
device_scale_factor);
cc_target_ = Layer::ConvertTransformToCCTransform(target_,
device_scale_factor);
}
virtual void OnAbort(LayerAnimationDelegate* delegate) OVERRIDE {
if (delegate && Started()) {
ThreadedLayerAnimationElement::OnAbort(delegate);
delegate->SetTransformFromAnimation(Tween::ValueBetween(
Tween::CalculateValue(tween_type(), last_progressed_fraction()),
start_,
target_));
}
}
virtual void OnEnd(LayerAnimationDelegate* delegate) OVERRIDE {
delegate->SetTransformFromAnimation(target_);
}
virtual scoped_ptr<cc::Animation> CreateCCAnimation() OVERRIDE {
scoped_ptr<cc::AnimationCurve> animation_curve(
new TransformAnimationCurveAdapter(tween_type(),
cc_start_,
cc_target_,
duration()));
scoped_ptr<cc::Animation> animation(
cc::Animation::Create(animation_curve.Pass(),
animation_id(),
animation_group_id(),
cc::Animation::Transform));
return animation.Pass();
}
virtual void OnGetTarget(TargetValue* target) const OVERRIDE {
target->transform = target_;
}
private:
static AnimatableProperties GetProperties() {
AnimatableProperties properties;
properties.insert(LayerAnimationElement::TRANSFORM);
return properties;
}
gfx::Transform start_;
gfx::Transform cc_start_;
const gfx::Transform target_;
gfx::Transform cc_target_;
DISALLOW_COPY_AND_ASSIGN(ThreadedTransformTransition);
};
} // namespace
// LayerAnimationElement::TargetValue ------------------------------------------
LayerAnimationElement::TargetValue::TargetValue()
: opacity(0.0f),
visibility(false),
brightness(0.0f),
grayscale(0.0f),
color(SK_ColorBLACK) {
}
LayerAnimationElement::TargetValue::TargetValue(
const LayerAnimationDelegate* delegate)
: bounds(delegate ? delegate->GetBoundsForAnimation() : gfx::Rect()),
transform(delegate ?
delegate->GetTransformForAnimation() : gfx::Transform()),
opacity(delegate ? delegate->GetOpacityForAnimation() : 0.0f),
visibility(delegate ? delegate->GetVisibilityForAnimation() : false),
brightness(delegate ? delegate->GetBrightnessForAnimation() : 0.0f),
grayscale(delegate ? delegate->GetGrayscaleForAnimation() : 0.0f),
color(delegate ? delegate->GetColorForAnimation() : 0.0f) {
}
// LayerAnimationElement -------------------------------------------------------
LayerAnimationElement::LayerAnimationElement(
const AnimatableProperties& properties,
base::TimeDelta duration)
: first_frame_(true),
properties_(properties),
duration_(GetEffectiveDuration(duration)),
tween_type_(Tween::LINEAR),
animation_id_(cc::AnimationIdProvider::NextAnimationId()),
animation_group_id_(0),
last_progressed_fraction_(0.0) {
}
LayerAnimationElement::~LayerAnimationElement() {
}
void LayerAnimationElement::Start(LayerAnimationDelegate* delegate,
int animation_group_id) {
DCHECK(requested_start_time_ != base::TimeTicks());
DCHECK(first_frame_);
animation_group_id_ = animation_group_id;
last_progressed_fraction_ = 0.0;
OnStart(delegate);
RequestEffectiveStart(delegate);
first_frame_ = false;
}
bool LayerAnimationElement::Progress(base::TimeTicks now,
LayerAnimationDelegate* delegate) {
DCHECK(requested_start_time_ != base::TimeTicks());
DCHECK(!first_frame_);
bool need_draw;
double t = 1.0;
if ((effective_start_time_ == base::TimeTicks()) ||
(now < effective_start_time_)) {
// This hasn't actually started yet.
need_draw = false;
last_progressed_fraction_ = 0.0;
return need_draw;
}
base::TimeDelta elapsed = now - effective_start_time_;
if ((duration_ > base::TimeDelta()) && (elapsed < duration_))
t = elapsed.InMillisecondsF() / duration_.InMillisecondsF();
need_draw = OnProgress(Tween::CalculateValue(tween_type_, t), delegate);
first_frame_ = t == 1.0;
last_progressed_fraction_ = t;
return need_draw;
}
bool LayerAnimationElement::IsFinished(base::TimeTicks time,
base::TimeDelta* total_duration) {
// If an effective start has been requested but the effective start time
// hasn't yet been set, the animation is not finished, regardless of the
// value of |time|.
if (!first_frame_ && (effective_start_time_ == base::TimeTicks()))
return false;
base::TimeDelta queueing_delay;
if (!first_frame_)
queueing_delay = effective_start_time_ - requested_start_time_;
base::TimeDelta elapsed = time - requested_start_time_;
if (elapsed >= duration_ + queueing_delay) {
*total_duration = duration_ + queueing_delay;
return true;
}
return false;
}
bool LayerAnimationElement::ProgressToEnd(LayerAnimationDelegate* delegate) {
if (first_frame_)
OnStart(delegate);
bool need_draw = OnProgress(1.0, delegate);
last_progressed_fraction_ = 1.0;
first_frame_ = true;
return need_draw;
}
void LayerAnimationElement::GetTargetValue(TargetValue* target) const {
OnGetTarget(target);
}
bool LayerAnimationElement::IsThreaded() const {
return false;
}
void LayerAnimationElement::Abort(LayerAnimationDelegate* delegate) {
OnAbort(delegate);
first_frame_ = true;
}
void LayerAnimationElement::RequestEffectiveStart(
LayerAnimationDelegate* delegate) {
DCHECK(requested_start_time_ != base::TimeTicks());
effective_start_time_ = requested_start_time_;
}
// static
LayerAnimationElement::AnimatableProperty
LayerAnimationElement::ToAnimatableProperty(
cc::Animation::TargetProperty property) {
switch (property) {
case cc::Animation::Transform:
return TRANSFORM;
case cc::Animation::Opacity:
return OPACITY;
default:
NOTREACHED();
return AnimatableProperty();
}
}
// static
base::TimeDelta LayerAnimationElement::GetEffectiveDuration(
const base::TimeDelta& duration) {
switch (ScopedAnimationDurationScaleMode::duration_scale_mode()) {
case ScopedAnimationDurationScaleMode::NORMAL_DURATION:
return duration;
case ScopedAnimationDurationScaleMode::FAST_DURATION:
return duration / kFastDurationScaleFactor;
case ScopedAnimationDurationScaleMode::SLOW_DURATION:
return duration * kSlowDurationScaleFactor;
case ScopedAnimationDurationScaleMode::ZERO_DURATION:
return base::TimeDelta();
default:
NOTREACHED();
return base::TimeDelta();
}
}
// static
LayerAnimationElement* LayerAnimationElement::CreateTransformElement(
const gfx::Transform& transform,
base::TimeDelta duration) {
return new ThreadedTransformTransition(transform, duration);
}
// static
LayerAnimationElement*
LayerAnimationElement::CreateInterpolatedTransformElement(
InterpolatedTransform* interpolated_transform,
base::TimeDelta duration) {
return new InterpolatedTransformTransition(interpolated_transform, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreateBoundsElement(
const gfx::Rect& bounds,
base::TimeDelta duration) {
return new BoundsTransition(bounds, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreateOpacityElement(
float opacity,
base::TimeDelta duration) {
return new ThreadedOpacityTransition(opacity, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreateVisibilityElement(
bool visibility,
base::TimeDelta duration) {
return new VisibilityTransition(visibility, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreateBrightnessElement(
float brightness,
base::TimeDelta duration) {
return new BrightnessTransition(brightness, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreateGrayscaleElement(
float grayscale,
base::TimeDelta duration) {
return new GrayscaleTransition(grayscale, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreatePauseElement(
const AnimatableProperties& properties,
base::TimeDelta duration) {
return new Pause(properties, duration);
}
// static
LayerAnimationElement* LayerAnimationElement::CreateColorElement(
SkColor color,
base::TimeDelta duration) {
return new ColorTransition(color, duration);
}
} // namespace ui
|
/*
Copyright (c) 2009-2012 Maximus5
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <windows.h>
#include <wchar.h>
#include "../common/Common.h"
#include "../common/RgnDetect.h"
#ifdef _DEBUG
#pragma warning( disable : 4995 )
#endif
#include "../common/pluginW1761.hpp"
#ifdef _DEBUG
#pragma warning( default : 4995 )
#endif
#include "PluginHeader.h"
// Можно бы добавить обработку Up/Down для перехода между пакетами
// сразу "жать" Esc, вызвать RestoreScreen (но без коммита на экран)
// и послать макрос "Down Enter" - фар сделает остальное
//
// Кнопочкой '*' при отображении дампа переключать режим
// = нормальный (отображается цветной текст, как был в консоли)
// = атрибутивный (отображаются ТОЛЬКО атрибуты, но как текст, а не как цвет)
//extern struct PluginStartupInfo *InfoW995;
//extern struct FarStandardFunctions *FSFW995;
CONSOLE_SCREEN_BUFFER_INFO csbi;
int gnPage = 0;
bool gbShowAttrsOnly = false;
BOOL CheckConInput(INPUT_RECORD* pr)
{
DWORD dwCount = 0;
memset(pr, 0, sizeof(INPUT_RECORD));
BOOL lbRc = ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), pr, 1, &dwCount);
if (!lbRc)
return FALSE;
if (pr->EventType == KEY_EVENT)
{
if (pr->Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE)
return FALSE;
}
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return TRUE;
}
void ShowConPacket(CESERVER_REQ* pReq)
{
// Где-то там с выравниванием проблема
INPUT_RECORD *r = (INPUT_RECORD*)calloc(sizeof(INPUT_RECORD),2);
HANDLE hO = GetStdHandle(STD_OUTPUT_HANDLE);
COORD cr;
DWORD dw, dwLen;
int nPage = 0;
BOOL lbNeedRedraw = TRUE;
wchar_t* pszText = (wchar_t*)calloc(200*100,2);
wchar_t* psz = NULL, *pszEnd = NULL;
CESERVER_CHAR *pceChar = NULL;
wchar_t* pszConData = NULL;
WORD* pnConData = NULL;
DWORD dwConDataBufSize = 0;
CONSOLE_SCREEN_BUFFER_INFO sbi = {{0,0}};
SetWindowText(FarHwnd, L"ConEmu packet dump");
psz = pszText;
switch(pReq->hdr.nCmd)
{
//case CECMD_GETSHORTINFO: pszEnd = L"CECMD_GETSHORTINFO"; break;
//case CECMD_GETFULLINFO: pszEnd = L"CECMD_GETFULLINFO"; break;
case CECMD_SETSIZESYNC: pszEnd = L"CECMD_SETSIZESYNC"; break;
case CECMD_CMDSTARTSTOP: pszEnd = L"CECMD_CMDSTARTSTOP"; break;
// case CECMD_GETGUIHWND: pszEnd = L"CECMD_GETGUIHWND"; break;
// case CECMD_RECREATE: pszEnd = L"CECMD_RECREATE"; break;
case CECMD_TABSCHANGED: pszEnd = L"CECMD_TABSCHANGED"; break;
case CECMD_CMDSTARTED: pszEnd = L"CECMD_CMDSTARTED"; break;
case CECMD_CMDFINISHED: pszEnd = L"CECMD_CMDFINISHED"; break;
default: pszEnd = L"???";
}
wsprintf(psz, L"Packet size: %i; Command: %i (%s); Version: %i\n",
pReq->hdr.cbSize, pReq->hdr.nCmd, pszEnd, pReq->hdr.nVersion);
psz += lstrlenW(psz);
r->EventType = WINDOW_BUFFER_SIZE_EVENT;
do
{
if (r->EventType == WINDOW_BUFFER_SIZE_EVENT)
{
r->EventType = 0; cr.X = 0; cr.Y = 0;
lbNeedRedraw = TRUE;
}
else if (r->EventType == KEY_EVENT && r->Event.KeyEvent.bKeyDown)
{
if (r->Event.KeyEvent.wVirtualKeyCode == VK_NEXT)
{
lbNeedRedraw = TRUE;
gnPage++;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
}
else if (r->Event.KeyEvent.wVirtualKeyCode == VK_PRIOR)
{
lbNeedRedraw = TRUE;
gnPage--;
}
}
if (gnPage<0) gnPage = 1; else if (gnPage>1) gnPage = 0;
if (lbNeedRedraw)
{
lbNeedRedraw = FALSE;
cr.X = 0; cr.Y = 0;
if (gnPage == 0)
{
FillConsoleOutputAttribute(hO, 7, csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
FillConsoleOutputCharacter(hO, L' ', csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
cr.X = 0; cr.Y = 0; psz = pszText;
while(*psz && cr.Y<csbi.dwSize.Y)
{
pszEnd = wcschr(psz, L'\n');
dwLen = min(((int)(pszEnd-psz)),csbi.dwSize.X);
SetConsoleCursorPosition(hO, cr);
if (dwLen>0)
WriteConsoleOutputCharacter(hO, psz, dwLen, cr, &dw);
cr.Y ++; psz = pszEnd + 1;
}
SetConsoleCursorPosition(hO, cr);
}
else if (gnPage == 1)
{
FillConsoleOutputAttribute(hO, 0x10, csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
FillConsoleOutputCharacter(hO, L' ', csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
int nMaxX = min(sbi.dwSize.X, csbi.dwSize.X);
int nMaxY = min(sbi.dwSize.Y, csbi.dwSize.Y);
if (pszConData && dwConDataBufSize)
{
wchar_t* pszSrc = pszConData;
wchar_t* pszEnd = pszConData + dwConDataBufSize;
WORD* pnSrc = pnConData;
cr.X = 0; cr.Y = 0;
while(cr.Y < nMaxY && pszSrc < pszEnd)
{
WriteConsoleOutputCharacter(hO, pszSrc, nMaxX, cr, &dw);
WriteConsoleOutputAttribute(hO, pnSrc, nMaxX, cr, &dw);
pszSrc += sbi.dwSize.X; pnSrc += sbi.dwSize.X; cr.Y++;
}
}
cr.Y = nMaxY-1;
SetConsoleCursorPosition(hO, cr);
}
}
}
while(CheckConInput(r));
free(pszText);
}
void ShowConDump(wchar_t* pszText)
{
INPUT_RECORD r[2];
BOOL lbNeedRedraw = TRUE;
HANDLE hO = GetStdHandle(STD_OUTPUT_HANDLE);
//CONSOLE_SCREEN_BUFFER_INFO sbi = {{0,0}};
COORD cr, crSize, crCursor;
WCHAR* pszBuffers[3];
void* pnBuffers[3];
WCHAR* pszDumpTitle, *pszRN, *pszSize, *pszTitle = NULL;
SetWindowText(FarHwnd, L"ConEmu screen dump");
pszDumpTitle = pszText;
pszRN = wcschr(pszDumpTitle, L'\r');
if (!pszRN) return;
*pszRN = 0;
pszSize = pszRN + 2;
if (wcsncmp(pszSize, L"Size: ", 6)) return;
pszRN = wcschr(pszSize, L'\r');
if (!pszRN) return;
pszBuffers[0] = pszRN + 2;
pszSize += 6;
//if ((pszRN = wcschr(pszSize, L'x'))==NULL) return;
//*pszRN = 0;
crSize.X = (SHORT)wcstol(pszSize, &pszRN, 10);
if (!pszRN || *pszRN!=L'x') return;
pszSize = pszRN + 1;
//if ((pszRN = wcschr(pszSize, L'\r'))==NULL) return;
//*pszRN = 0;
crSize.Y = (SHORT)wcstol(pszSize, &pszRN, 10);
if (!pszRN || (*pszRN!=L' ' && *pszRN!=L'\r')) return;
pszSize = pszRN;
crCursor.X = 0; crCursor.Y = crSize.Y-1;
if (*pszSize == L' ')
{
while(*pszSize == L' ') pszSize++;
if (wcsncmp(pszSize, L"Cursor: ", 8)==0)
{
pszSize += 8;
cr.X = (SHORT)wcstol(pszSize, &pszRN, 10);
if (!pszRN || *pszRN!=L'x') return;
pszSize = pszRN + 1;
cr.Y = (SHORT)wcstol(pszSize, &pszRN, 10);
if (cr.X>=0 && cr.Y>=0)
{
crCursor.X = cr.X; crCursor.Y = cr.Y;
}
}
}
pszTitle = (WCHAR*)calloc(lstrlenW(pszDumpTitle)+200,2);
DWORD dwConDataBufSize = crSize.X * crSize.Y;
DWORD dwConDataBufSizeEx = crSize.X * crSize.Y * sizeof(CharAttr);
pnBuffers[0] = (void*)(((WORD*)(pszBuffers[0])) + dwConDataBufSize);
pszBuffers[1] = (WCHAR*)(((LPBYTE)(pnBuffers[0])) + dwConDataBufSizeEx);
pnBuffers[1] = (void*)(((WORD*)(pszBuffers[1])) + dwConDataBufSize);
pszBuffers[2] = (WCHAR*)(((LPBYTE)(pnBuffers[1])) + dwConDataBufSizeEx);
pnBuffers[2] = (void*)(((WORD*)(pszBuffers[2])) + dwConDataBufSize);
r->EventType = WINDOW_BUFFER_SIZE_EVENT;
do
{
if (r->EventType == WINDOW_BUFFER_SIZE_EVENT)
{
r->EventType = 0;
lbNeedRedraw = TRUE;
}
else if (r->EventType == KEY_EVENT && r->Event.KeyEvent.bKeyDown)
{
if (r->Event.KeyEvent.wVirtualKeyCode == VK_NEXT)
{
lbNeedRedraw = TRUE;
gnPage++;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
}
else if (r->Event.KeyEvent.wVirtualKeyCode == VK_PRIOR)
{
lbNeedRedraw = TRUE;
gnPage--;
}
else if (r->Event.KeyEvent.uChar.UnicodeChar == L'*')
{
lbNeedRedraw = TRUE;
gbShowAttrsOnly = !gbShowAttrsOnly;
}
}
if (gnPage<0) gnPage = 3; else if (gnPage>3) gnPage = 0;
if (lbNeedRedraw)
{
lbNeedRedraw = FALSE;
cr.X = 0; cr.Y = 0;
DWORD dw = 0;
if (gnPage == 0)
{
FillConsoleOutputAttribute(hO, 7, csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
FillConsoleOutputCharacter(hO, L' ', csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
cr.X = 0; cr.Y = 0; SetConsoleCursorPosition(hO, cr);
//wprintf(L"Console screen dump viewer\nTitle: %s\nSize: {%i x %i}\n",
// pszDumpTitle, crSize.X, crSize.Y);
LPCWSTR psz = L"Console screen dump viewer";
WriteConsoleOutputCharacter(hO, psz, lstrlenW(psz), cr, &dw); cr.Y++;
psz = L"Title: ";
WriteConsoleOutputCharacter(hO, psz, lstrlenW(psz), cr, &dw); cr.X += lstrlenW(psz);
WriteConsoleOutputCharacter(hO, pszDumpTitle, lstrlenW(pszDumpTitle), cr, &dw); cr.X = 0; cr.Y++;
wchar_t szSize[64]; wsprintf(szSize, L"Size: {%i x %i}", crSize.X, crSize.Y);
WriteConsoleOutputCharacter(hO, szSize, lstrlenW(szSize), cr, &dw); cr.Y++;
SetConsoleCursorPosition(hO, cr);
}
else if (gnPage >= 1 && gnPage <= 3)
{
FillConsoleOutputAttribute(hO, gbShowAttrsOnly ? 0xF : 0x10, csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
FillConsoleOutputCharacter(hO, L' ', csbi.dwSize.X*csbi.dwSize.Y, cr, &dw);
int nMaxX = min(crSize.X, csbi.dwSize.X);
int nMaxY = min(crSize.Y, csbi.dwSize.Y);
wchar_t* pszConData = pszBuffers[gnPage-1];
void* pnConData = pnBuffers[gnPage-1];
LPBYTE pnTemp = (LPBYTE)malloc(nMaxX*2);
CharAttr *pSrcEx = (CharAttr*)pnConData;
if (pszConData && dwConDataBufSize)
{
wchar_t* pszSrc = pszConData;
wchar_t* pszEnd = pszConData + dwConDataBufSize;
LPBYTE pnSrc;
DWORD nAttrLineSize;
if (gnPage == 3)
{
pnSrc = (LPBYTE)pnConData;
nAttrLineSize = crSize.X * 2;
}
else
{
pnSrc = pnTemp;
nAttrLineSize = 0;
}
cr.X = 0; cr.Y = 0;
while(cr.Y < nMaxY && pszSrc < pszEnd)
{
if (!gbShowAttrsOnly)
{
WriteConsoleOutputCharacter(hO, pszSrc, nMaxX, cr, &dw);
if (gnPage < 3)
{
for(int i = 0; i < nMaxX; i++)
{
((WORD*)pnSrc)[i] = pSrcEx[i].nForeIdx | (pSrcEx[i].nBackIdx << 4);
}
pSrcEx += crSize.X;
}
WriteConsoleOutputAttribute(hO, (WORD*)pnSrc, nMaxX, cr, &dw);
}
else
{
WriteConsoleOutputCharacter(hO, (wchar_t*)pnSrc, nMaxX, cr, &dw);
}
pszSrc += crSize.X;
if (nAttrLineSize)
pnSrc += nAttrLineSize; //-V102
cr.Y++;
}
}
free(pnTemp);
//cr.Y = nMaxY-1;
SetConsoleCursorPosition(hO, crCursor);
}
}
}
while(CheckConInput(r));
free(pszTitle);
}
|
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright (C) 2019 Gwenhael Goavec-Merou <gwenhael.goavec-merou@trabucayre.com>
*/
#include <iostream>
#include <stdexcept>
#include "device.hpp"
using namespace std;
Device::Device(Jtag *jtag, string filename, const string &file_type,
bool verify, int8_t verbose):
_filename(filename),
_file_extension(filename.substr(filename.find_last_of(".") +1)),
_mode(NONE_MODE), _verify(verify), _verbose(verbose > 0),
_quiet(verbose < 0)
{
if (!file_type.empty())
_file_extension = file_type;
_jtag = jtag;
if (verbose > 0)
cout << "File type : " << _file_extension << endl;
}
Device::~Device() {}
void Device::reset()
{
throw std::runtime_error("Not implemented");
}
|
// Copyright (c) 2011-2018 The Earthcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/transactiondescdialog.h>
#include <qt/forms/ui_transactiondescdialog.h>
#include <qt/transactiontablemodel.h>
#include <QModelIndex>
#include <QDesktopServices>
#include <QUrl>
#include <QMessageBox>
TransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :
QDialog(parent),
ui(new Ui::TransactionDescDialog),
ipfsUrlPrefix(NULL)
{
ui->setupUi(this);
setWindowTitle(tr("Details for %1").arg(idx.data(TransactionTableModel::TxHashRole).toString()));
QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();
IPFS = idx.data(TransactionTableModel::IPFSRole).toString();
ui->detailText->setHtml(desc);
if (IPFS.length() < 1)
ui->openIPFSButton->hide();
}
TransactionDescDialog::~TransactionDescDialog()
{
delete ui;
}
void TransactionDescDialog::on_openIPFSButton_clicked()
{
QString URL = (ipfsUrlPrefix ? (*ipfsUrlPrefix) : "https://dweb.link/ipfs/") + IPFS;
QDesktopServices::openUrl(QUrl(URL));
}
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. 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.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/scenarios/lane_follow/lane_follow_stage.h"
#include <algorithm>
#include <limits>
#include <utility>
#include "cyber/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/time/time.h"
#include "modules/common/util/point_factory.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/ego_info.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker.h"
#include "modules/planning/tasks/deciders/lane_change_decider/lane_change_decider.h"
#include "modules/planning/tasks/deciders/path_decider/path_decider.h"
#include "modules/planning/tasks/deciders/speed_decider/speed_decider.h"
#include "modules/planning/tasks/optimizers/path_time_heuristic/path_time_heuristic_optimizer.h"
namespace apollo {
namespace planning {
namespace scenario {
namespace lane_follow {
using apollo::common::ErrorCode;
using apollo::common::SLPoint;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::time::Clock;
using apollo::common::util::PointFactory;
namespace {
constexpr double kPathOptimizationFallbackCost = 2e4;
constexpr double kSpeedOptimizationFallbackCost = 2e4;
constexpr double kStraightForwardLineCost = 10.0;
} // namespace
LaneFollowStage::LaneFollowStage(const ScenarioConfig::StageConfig& config)
: Stage(config) {}
void LaneFollowStage::RecordObstacleDebugInfo(
ReferenceLineInfo* reference_line_info) {
if (!FLAGS_enable_record_debug) {
ADEBUG << "Skip record debug info";
return;
}
auto ptr_debug = reference_line_info->mutable_debug();
const auto path_decision = reference_line_info->path_decision();
for (const auto obstacle : path_decision->obstacles().Items()) {
auto obstacle_debug = ptr_debug->mutable_planning_data()->add_obstacle();
obstacle_debug->set_id(obstacle->Id());
obstacle_debug->mutable_sl_boundary()->CopyFrom(
obstacle->PerceptionSLBoundary());
const auto& decider_tags = obstacle->decider_tags();
const auto& decisions = obstacle->decisions();
if (decider_tags.size() != decisions.size()) {
AERROR << "decider_tags size: " << decider_tags.size()
<< " different from decisions size:" << decisions.size();
}
for (size_t i = 0; i < decider_tags.size(); ++i) {
auto decision_tag = obstacle_debug->add_decision_tag();
decision_tag->set_decider_tag(decider_tags[i]);
decision_tag->mutable_decision()->CopyFrom(decisions[i]);
}
}
}
void LaneFollowStage::RecordDebugInfo(ReferenceLineInfo* reference_line_info,
const std::string& name,
const double time_diff_ms) {
if (!FLAGS_enable_record_debug) {
ADEBUG << "Skip record debug info";
return;
}
if (reference_line_info == nullptr) {
AERROR << "Reference line info is null.";
return;
}
auto ptr_latency_stats = reference_line_info->mutable_latency_stats();
auto ptr_stats = ptr_latency_stats->add_task_stats();
ptr_stats->set_name(name);
ptr_stats->set_time_ms(time_diff_ms);
}
Stage::StageStatus LaneFollowStage::Process(
const TrajectoryPoint& planning_start_point, Frame* frame) {
bool has_drivable_reference_line = false;
ADEBUG << "Number of reference lines:\t"
<< frame->mutable_reference_line_info()->size();
unsigned int count = 0;
for (auto& reference_line_info : *frame->mutable_reference_line_info()) {
// TODO(SHU): need refactor
if (count++ == frame->mutable_reference_line_info()->size()) {
break;
}
ADEBUG << "No: [" << count << "] Reference Line.";
ADEBUG << "IsChangeLanePath: " << reference_line_info.IsChangeLanePath();
if (has_drivable_reference_line) {
reference_line_info.SetDrivable(false);
break;
}
auto cur_status =
PlanOnReferenceLine(planning_start_point, frame, &reference_line_info);
if (cur_status.ok()) {
if (reference_line_info.IsChangeLanePath()) {
ADEBUG << "reference line is lane change ref.";
ADEBUG << "FLAGS_enable_smarter_lane_change: "
<< FLAGS_enable_smarter_lane_change;
if (reference_line_info.Cost() < kStraightForwardLineCost &&
(LaneChangeDecider::IsClearToChangeLane(&reference_line_info) ||
FLAGS_enable_smarter_lane_change)) {
// If the path and speed optimization succeed on target lane while
// under smart lane-change or IsClearToChangeLane under older version
has_drivable_reference_line = true;
reference_line_info.SetDrivable(true);
LaneChangeDecider::UpdatePreparationDistance(true, frame,
&reference_line_info);
ADEBUG << "\tclear for lane change";
} else {
LaneChangeDecider::UpdatePreparationDistance(false, frame,
&reference_line_info);
reference_line_info.SetDrivable(false);
ADEBUG << "\tlane change failed";
}
} else {
ADEBUG << "reference line is NOT lane change ref.";
has_drivable_reference_line = true;
}
} else {
reference_line_info.SetDrivable(false);
}
}
return has_drivable_reference_line ? StageStatus::RUNNING
: StageStatus::ERROR;
}
Status LaneFollowStage::PlanOnReferenceLine(
const TrajectoryPoint& planning_start_point, Frame* frame,
ReferenceLineInfo* reference_line_info) {
if (!reference_line_info->IsChangeLanePath()) {
reference_line_info->AddCost(kStraightForwardLineCost);
}
ADEBUG << "planning start point:" << planning_start_point.DebugString();
ADEBUG << "Current reference_line_info is IsChangeLanePath: "
<< reference_line_info->IsChangeLanePath();
auto ret = Status::OK();
for (auto* optimizer : task_list_) {
const double start_timestamp = Clock::NowInSeconds();
ret = optimizer->Execute(frame, reference_line_info);
if (!ret.ok()) {
AERROR << "Failed to run tasks[" << optimizer->Name()
<< "], Error message: " << ret.error_message();
break;
}
const double end_timestamp = Clock::NowInSeconds();
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
ADEBUG << "after optimizer " << optimizer->Name() << ":"
<< reference_line_info->PathSpeedDebugString();
ADEBUG << optimizer->Name() << " time spend: " << time_diff_ms << " ms.";
RecordDebugInfo(reference_line_info, optimizer->Name(), time_diff_ms);
// TODO(SHU): disable reference line order changes for now
// updated reference_line_info, because it is changed in
// lane_change_decider by PrioritizeChangeLane().
// reference_line_info = &frame->mutable_reference_line_info()->front();
// ADEBUG << "Current reference_line_info is IsChangeLanePath: "
// << reference_line_info->IsChangeLanePath();
}
RecordObstacleDebugInfo(reference_line_info);
// check path and speed results for path or speed fallback
reference_line_info->set_trajectory_type(ADCTrajectory::NORMAL);
if (!ret.ok()) {
PlanFallbackTrajectory(planning_start_point, frame, reference_line_info);
}
DiscretizedTrajectory trajectory;
if (!reference_line_info->CombinePathAndSpeedProfile(
planning_start_point.relative_time(),
planning_start_point.path_point().s(), &trajectory)) {
std::string msg("Fail to aggregate planning trajectory.");
AERROR << msg;
return Status(ErrorCode::PLANNING_ERROR, msg);
}
// determine if there is a destination on reference line.
double dest_stop_s = -1.0;
for (const auto* obstacle :
reference_line_info->path_decision()->obstacles().Items()) {
if (obstacle->LongitudinalDecision().has_stop() &&
obstacle->LongitudinalDecision().stop().reason_code() ==
STOP_REASON_DESTINATION) {
SLPoint dest_sl = GetStopSL(obstacle->LongitudinalDecision().stop(),
reference_line_info->reference_line());
dest_stop_s = dest_sl.s();
}
}
for (const auto* obstacle :
reference_line_info->path_decision()->obstacles().Items()) {
if (obstacle->IsVirtual()) {
continue;
}
if (!obstacle->IsStatic()) {
continue;
}
if (obstacle->LongitudinalDecision().has_stop()) {
bool add_stop_obstacle_cost = false;
if (dest_stop_s < 0.0) {
add_stop_obstacle_cost = true;
} else {
SLPoint stop_sl = GetStopSL(obstacle->LongitudinalDecision().stop(),
reference_line_info->reference_line());
if (stop_sl.s() < dest_stop_s) {
add_stop_obstacle_cost = true;
}
}
if (add_stop_obstacle_cost) {
static constexpr double kReferenceLineStaticObsCost = 1e3;
reference_line_info->AddCost(kReferenceLineStaticObsCost);
}
}
}
if (FLAGS_enable_trajectory_check) {
if (ConstraintChecker::ValidTrajectory(trajectory) !=
ConstraintChecker::Result::VALID) {
std::string msg("Current planning trajectory is not valid.");
AERROR << msg;
return Status(ErrorCode::PLANNING_ERROR, msg);
}
}
reference_line_info->SetTrajectory(trajectory);
reference_line_info->SetDrivable(true);
return Status::OK();
}
void LaneFollowStage::PlanFallbackTrajectory(
const TrajectoryPoint& planning_start_point, Frame* frame,
ReferenceLineInfo* reference_line_info) {
// path and speed fall back
if (reference_line_info->path_data().Empty()) {
AERROR << "Path fallback due to algorithm failure";
GenerateFallbackPathProfile(reference_line_info,
reference_line_info->mutable_path_data());
reference_line_info->AddCost(kPathOptimizationFallbackCost);
reference_line_info->set_trajectory_type(ADCTrajectory::PATH_FALLBACK);
}
if (reference_line_info->trajectory_type() != ADCTrajectory::PATH_FALLBACK) {
if (!RetrieveLastFramePathProfile(
reference_line_info, frame,
reference_line_info->mutable_path_data())) {
const auto& candidate_path_data =
reference_line_info->GetCandidatePathData();
for (const auto& path_data : candidate_path_data) {
if (path_data.path_label().find("self") != std::string::npos) {
*reference_line_info->mutable_path_data() = path_data;
AERROR << "Use current frame self lane path as fallback ";
break;
}
}
}
}
AERROR << "Speed fallback due to algorithm failure";
// TODO(Hongyi): refine the fall-back handling here.
// To use piecewise jerk speed fallback, stop distance here
// is an upper bound of s, not a target.
// TODO(Jiacheng): move this stop_path_threshold to a gflag
const double path_stop_distance =
reference_line_info->path_data().discretized_path().Length();
const double obstacle_stop_distance =
reference_line_info->st_graph_data().is_initialized()
? reference_line_info->st_graph_data().min_s_on_st_boundaries()
: std::numeric_limits<double>::infinity();
const double curr_speed_distance =
FLAGS_fallback_total_time *
std::min({reference_line_info->GetCruiseSpeed(),
reference_line_info->vehicle_state().linear_velocity()});
*reference_line_info->mutable_speed_data() =
SpeedProfileGenerator::GenerateFallbackSpeed(std::min(
{path_stop_distance, obstacle_stop_distance, curr_speed_distance}));
if (reference_line_info->trajectory_type() != ADCTrajectory::PATH_FALLBACK) {
reference_line_info->AddCost(kSpeedOptimizationFallbackCost);
reference_line_info->set_trajectory_type(ADCTrajectory::SPEED_FALLBACK);
}
}
void LaneFollowStage::GenerateFallbackPathProfile(
const ReferenceLineInfo* reference_line_info, PathData* path_data) {
const double unit_s = 1.0;
const auto& reference_line = reference_line_info->reference_line();
auto adc_point = EgoInfo::Instance()->start_point();
DCHECK(adc_point.has_path_point());
const auto adc_point_x = adc_point.path_point().x();
const auto adc_point_y = adc_point.path_point().y();
common::SLPoint adc_point_s_l;
if (!reference_line.XYToSL({adc_point_x, adc_point_y}, &adc_point_s_l)) {
AERROR << "Fail to project ADC to reference line when calculating path "
"fallback. Straight forward path is generated";
const auto adc_point_heading = adc_point.path_point().theta();
const auto adc_point_kappa = adc_point.path_point().kappa();
const auto adc_point_dkappa = adc_point.path_point().dkappa();
std::vector<common::PathPoint> path_points;
double adc_traversed_x = adc_point_x;
double adc_traversed_y = adc_point_y;
const double max_s = 100.0;
for (double s = 0; s < max_s; s += unit_s) {
path_points.push_back(PointFactory::ToPathPoint(
adc_traversed_x, adc_traversed_y, 0.0, s, adc_point_heading,
adc_point_kappa, adc_point_dkappa));
adc_traversed_x += unit_s * std::cos(adc_point_heading);
adc_traversed_y += unit_s * std::sin(adc_point_heading);
}
path_data->SetDiscretizedPath(DiscretizedPath(std::move(path_points)));
return;
}
// Generate a fallback path along the reference line direction
const auto adc_s = adc_point_s_l.s();
const auto& adc_ref_point =
reference_line.GetReferencePoint(adc_point_x, adc_point_y);
const double dx = adc_point_x - adc_ref_point.x();
const double dy = adc_point_y - adc_ref_point.y();
std::vector<common::PathPoint> path_points;
const double max_s = reference_line.Length();
for (double s = adc_s; s < max_s; s += unit_s) {
const auto& ref_point = reference_line.GetReferencePoint(s);
path_points.push_back(PointFactory::ToPathPoint(
ref_point.x() + dx, ref_point.y() + dy, 0.0, s - adc_s,
ref_point.heading(), ref_point.kappa(), ref_point.dkappa()));
}
path_data->SetDiscretizedPath(DiscretizedPath(std::move(path_points)));
}
bool LaneFollowStage::RetrieveLastFramePathProfile(
const ReferenceLineInfo* reference_line_info, const Frame* frame,
PathData* path_data) {
const auto* ptr_last_frame = FrameHistory::Instance()->Latest();
if (ptr_last_frame == nullptr) {
AERROR
<< "Last frame doesn't succeed, fail to retrieve last frame path data";
return false;
}
const auto& last_frame_discretized_path =
ptr_last_frame->current_frame_planned_path();
path_data->SetDiscretizedPath(last_frame_discretized_path);
const auto adc_frenet_frame_point_ =
reference_line_info->reference_line().GetFrenetPoint(
frame->PlanningStartPoint().path_point());
bool trim_success = path_data->LeftTrimWithRefS(adc_frenet_frame_point_);
if (!trim_success) {
AERROR << "Fail to trim path_data. adc_frenet_frame_point: "
<< adc_frenet_frame_point_.ShortDebugString();
return false;
}
AERROR << "Use last frame good path to do speed fallback";
return true;
}
SLPoint LaneFollowStage::GetStopSL(const ObjectStop& stop_decision,
const ReferenceLine& reference_line) const {
SLPoint sl_point;
reference_line.XYToSL(
{stop_decision.stop_point().x(), stop_decision.stop_point().y()},
&sl_point);
return sl_point;
}
} // namespace lane_follow
} // namespace scenario
} // namespace planning
} // namespace apollo
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "core/gestures/gesture_referee.h"
namespace OHOS::Ace {
void GestureScope::AddMember(const RefPtr<GestureRecognizer>& recognizer)
{
if (!recognizer) {
LOGE("recognizer is null, AddMember failed.");
return;
}
recognizers_.emplace_back(recognizer);
}
void GestureScope::ForceSelectRecipient()
{
// Forcibly select the first one as the recipient when no gesture recognizer requests adjudication during the
// entire gesture sequence. In this case, recognizers must not be empty.
if (recognizers_.empty()) {
LOGE("the recognizer collection is empty");
return;
}
recognizers_.front()->OnAccepted(touchId_);
recognizers_.pop_front();
for (const auto& rejectedItem : recognizers_) {
rejectedItem->OnRejected(touchId_);
}
recognizers_.clear();
}
void GestureScope::HandleGestureDisposal(const RefPtr<GestureRecognizer>& recognizer, const GestureDisposal disposal)
{
if (!recognizer) {
LOGE("recognizer is null, AddGestureRecognizer failed.");
return;
}
if (recognizers_.empty()) {
LOGE("the recognizer collection is empty");
return;
}
auto result = std::find(recognizers_.cbegin(), recognizers_.cend(), recognizer);
if (result == recognizers_.cend()) {
LOGE("can not find the recognizer");
return;
}
// First erases the find object.
recognizers_.erase(result);
// Handles recognizer callback.
if (disposal == GestureDisposal::REJECT) {
recognizer->OnRejected(touchId_);
} else {
recognizer->OnAccepted(touchId_);
for (const auto& rejectedItem : recognizers_) {
rejectedItem->OnRejected(touchId_);
}
recognizers_.clear();
}
}
void GestureScope::ForceClose()
{
if (recognizers_.empty()) {
return;
}
for (const auto& rejectedItem : recognizers_) {
rejectedItem->OnRejected(touchId_);
}
recognizers_.clear();
}
void GestureReferee::AddGestureRecognizer(size_t touchId, const RefPtr<GestureRecognizer>& recognizer)
{
if (!recognizer) {
LOGE("recognizer is null, AddGestureRecognizer failed.");
return;
}
LOGD("add gesture recognizer into scope, %{private}p", AceType::RawPtr(recognizer));
const auto iter = gestureScopes_.find(touchId);
if (iter != gestureScopes_.end()) {
iter->second.AddMember(recognizer);
} else {
GestureScope gestureScope(touchId);
gestureScope.AddMember(recognizer);
gestureScopes_.try_emplace(touchId, std::move(gestureScope));
}
}
void GestureReferee::AdjudicateGestureSequence(size_t touchId)
{
const auto iter = gestureScopes_.find(touchId);
if (iter != gestureScopes_.end()) {
if (!iter->second.IsEmpty()) {
iter->second.ForceSelectRecipient();
}
gestureScopes_.erase(iter);
}
}
void GestureReferee::CleanGestureScope(size_t touchId)
{
const auto iter = gestureScopes_.find(touchId);
if (iter != gestureScopes_.end()) {
if (!iter->second.IsEmpty()) {
iter->second.ForceClose();
}
gestureScopes_.erase(iter);
}
}
void GestureReferee::Adjudicate(size_t touchId, const RefPtr<GestureRecognizer>& recognizer, GestureDisposal disposal)
{
if (!recognizer) {
LOGE("recognizer is null, Adjudicate failed.");
return;
}
const auto iter = gestureScopes_.find(touchId);
if (iter != gestureScopes_.end()) {
iter->second.HandleGestureDisposal(recognizer, disposal);
} else {
LOGE("fail to find the gesture scope for %{public}zu session id", touchId);
}
}
} // namespace OHOS::Ace
|
/* Copyright 2003-2013 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/multi_index for library home page.
*/
#pragma once
#include <brigand/functions/if.hpp>
namespace multi_index{
namespace detail{
/* Until some official version of the ScopeGuard idiom makes it into Boost,
* we locally define our own. This is a merely reformated version of
* ScopeGuard.h as defined in:
* Alexandrescu, A., Marginean, P.:"Generic<Programming>: Change the Way You
* Write Exception-Safe Code - Forever", C/C++ Users Jornal, Dec 2000,
* http://www.drdobbs.com/184403758
* with the following modifications:
* - General pretty formatting (pretty to my taste at least.)
* - Naming style changed to standard C++ library requirements.
* - Added scope_guard_impl4 and obj_scope_guard_impl3, (Boost.MultiIndex
* needs them). A better design would provide guards for many more
* arguments through the Boost Preprocessor Library.
* - Added scope_guard_impl_base::touch (see below.)
* - Removed RefHolder and ByRef, whose functionality is provided
* already by Boost.Ref.
* - Removed static make_guard's and make_obj_guard's, so that the code
* will work even if BOOST_NO_MEMBER_TEMPLATES is defined. This forces
* us to move some private ctors to public, though.
*
* NB: CodeWarrior Pro 8 seems to have problems looking up safe_execute
* without an explicit qualification.
*
* We also define the following variants of the idiom:
*
* - make_guard_if_c<bool>( ... )
* - make_guard_if<IntegralConstant>( ... )
* - make_obj_guard_if_c<bool>( ... )
* - make_obj_guard_if<IntegralConstant>( ... )
* which may be used with a compile-time constant to yield
* a "null_guard" if the boolean compile-time parameter is false,
* or conversely, the guard is only constructed if the constant is true.
* This is useful to avoid extra tagging, because the returned
* null_guard can be optimzed comlpetely away by the compiler.
*/
class scope_guard_impl_base
{
public:
scope_guard_impl_base():dismissed_(false){}
void dismiss()const{dismissed_=true;}
/* This helps prevent some "unused variable" warnings under, for instance,
* GCC 3.2.
*/
void touch()const{}
protected:
~scope_guard_impl_base(){}
scope_guard_impl_base(const scope_guard_impl_base& other):
dismissed_(other.dismissed_)
{
other.dismiss();
}
template<typename J>
static void safe_execute(J& j){
try {
if(!j.dismissed_)j.execute();
}
catch(...){}
}
mutable bool dismissed_;
private:
scope_guard_impl_base& operator=(const scope_guard_impl_base&);
};
typedef const scope_guard_impl_base& scope_guard;
struct null_guard : public scope_guard_impl_base
{
template< class T1 >
null_guard( const T1& )
{ }
template< class T1, class T2 >
null_guard( const T1&, const T2& )
{ }
template< class T1, class T2, class T3 >
null_guard( const T1&, const T2&, const T3& )
{ }
template< class T1, class T2, class T3, class T4 >
null_guard( const T1&, const T2&, const T3&, const T4& )
{ }
template< class T1, class T2, class T3, class T4, class T5 >
null_guard( const T1&, const T2&, const T3&, const T4&, const T5& )
{ }
};
template< bool cond, class T >
struct null_guard_return
{
typedef typename brigand::if_c<cond,T,null_guard>::type type;
};
template<typename F>
class scope_guard_impl0:public scope_guard_impl_base
{
public:
scope_guard_impl0(F fun):fun_(fun){}
~scope_guard_impl0(){scope_guard_impl_base::safe_execute(*this);}
void execute(){fun_();}
protected:
F fun_;
};
template<typename F>
inline scope_guard_impl0<F> make_guard(F fun)
{
return scope_guard_impl0<F>(fun);
}
template<bool cond, typename F>
inline typename null_guard_return<cond,scope_guard_impl0<F> >::type
make_guard_if_c(F fun)
{
return typename null_guard_return<cond,scope_guard_impl0<F> >::type(fun);
}
template<typename C, typename F>
inline typename null_guard_return<C::value,scope_guard_impl0<F> >::type
make_guard_if(F fun)
{
return make_guard_if<C::value>(fun);
}
template<typename F,typename P1>
class scope_guard_impl1:public scope_guard_impl_base
{
public:
scope_guard_impl1(F fun,P1 p1):fun_(fun),p1_(p1){}
~scope_guard_impl1(){scope_guard_impl_base::safe_execute(*this);}
void execute(){fun_(p1_);}
protected:
F fun_;
const P1 p1_;
};
template<typename F,typename P1>
inline scope_guard_impl1<F,P1> make_guard(F fun,P1 p1)
{
return scope_guard_impl1<F,P1>(fun,p1);
}
template<bool cond, typename F,typename P1>
inline typename null_guard_return<cond,scope_guard_impl1<F,P1> >::type
make_guard_if_c(F fun,P1 p1)
{
return typename null_guard_return<cond,scope_guard_impl1<F,P1> >::type(fun,p1);
}
template<typename C, typename F,typename P1>
inline typename null_guard_return<C::value,scope_guard_impl1<F,P1> >::type
make_guard_if(F fun,P1 p1)
{
return make_guard_if_c<C::value>(fun,p1);
}
template<typename F,typename P1,typename P2>
class scope_guard_impl2:public scope_guard_impl_base
{
public:
scope_guard_impl2(F fun,P1 p1,P2 p2):fun_(fun),p1_(p1),p2_(p2){}
~scope_guard_impl2(){scope_guard_impl_base::safe_execute(*this);}
void execute(){fun_(p1_,p2_);}
protected:
F fun_;
const P1 p1_;
const P2 p2_;
};
template<typename F,typename P1,typename P2>
inline scope_guard_impl2<F,P1,P2> make_guard(F fun,P1 p1,P2 p2)
{
return scope_guard_impl2<F,P1,P2>(fun,p1,p2);
}
template<bool cond, typename F,typename P1,typename P2>
inline typename null_guard_return<cond,scope_guard_impl2<F,P1,P2> >::type
make_guard_if_c(F fun,P1 p1,P2 p2)
{
return typename null_guard_return<cond,scope_guard_impl2<F,P1,P2> >::type(fun,p1,p2);
}
template<typename C, typename F,typename P1,typename P2>
inline typename null_guard_return<C::value,scope_guard_impl2<F,P1,P2> >::type
make_guard_if(F fun,P1 p1,P2 p2)
{
return make_guard_if_c<C::value>(fun,p1,p2);
}
template<typename F,typename P1,typename P2,typename P3>
class scope_guard_impl3:public scope_guard_impl_base
{
public:
scope_guard_impl3(F fun,P1 p1,P2 p2,P3 p3):fun_(fun),p1_(p1),p2_(p2),p3_(p3){}
~scope_guard_impl3(){scope_guard_impl_base::safe_execute(*this);}
void execute(){fun_(p1_,p2_,p3_);}
protected:
F fun_;
const P1 p1_;
const P2 p2_;
const P3 p3_;
};
template<typename F,typename P1,typename P2,typename P3>
inline scope_guard_impl3<F,P1,P2,P3> make_guard(F fun,P1 p1,P2 p2,P3 p3)
{
return scope_guard_impl3<F,P1,P2,P3>(fun,p1,p2,p3);
}
template<bool cond,typename F,typename P1,typename P2,typename P3>
inline typename null_guard_return<cond,scope_guard_impl3<F,P1,P2,P3> >::type
make_guard_if_c(F fun,P1 p1,P2 p2,P3 p3)
{
return typename null_guard_return<cond,scope_guard_impl3<F,P1,P2,P3> >::type(fun,p1,p2,p3);
}
template<typename C,typename F,typename P1,typename P2,typename P3>
inline typename null_guard_return< C::value,scope_guard_impl3<F,P1,P2,P3> >::type
make_guard_if(F fun,P1 p1,P2 p2,P3 p3)
{
return make_guard_if_c<C::value>(fun,p1,p2,p3);
}
template<typename F,typename P1,typename P2,typename P3,typename P4>
class scope_guard_impl4:public scope_guard_impl_base
{
public:
scope_guard_impl4(F fun,P1 p1,P2 p2,P3 p3,P4 p4):
fun_(fun),p1_(p1),p2_(p2),p3_(p3),p4_(p4){}
~scope_guard_impl4(){scope_guard_impl_base::safe_execute(*this);}
void execute(){fun_(p1_,p2_,p3_,p4_);}
protected:
F fun_;
const P1 p1_;
const P2 p2_;
const P3 p3_;
const P4 p4_;
};
template<typename F,typename P1,typename P2,typename P3,typename P4>
inline scope_guard_impl4<F,P1,P2,P3,P4> make_guard(
F fun,P1 p1,P2 p2,P3 p3,P4 p4)
{
return scope_guard_impl4<F,P1,P2,P3,P4>(fun,p1,p2,p3,p4);
}
template<bool cond, typename F,typename P1,typename P2,typename P3,typename P4>
inline typename null_guard_return<cond,scope_guard_impl4<F,P1,P2,P3,P4> >::type
make_guard_if_c(
F fun,P1 p1,P2 p2,P3 p3,P4 p4)
{
return typename null_guard_return<cond,scope_guard_impl4<F,P1,P2,P3,P4> >::type(fun,p1,p2,p3,p4);
}
template<typename C, typename F,typename P1,typename P2,typename P3,typename P4>
inline typename null_guard_return<C::value,scope_guard_impl4<F,P1,P2,P3,P4> >::type
make_guard_if(
F fun,P1 p1,P2 p2,P3 p3,P4 p4)
{
return make_guard_if_c<C::value>(fun,p1,p2,p3,p4);
}
template<class Obj,typename MemFun>
class obj_scope_guard_impl0:public scope_guard_impl_base
{
public:
obj_scope_guard_impl0(Obj& obj,MemFun mem_fun):obj_(obj),mem_fun_(mem_fun){}
~obj_scope_guard_impl0(){scope_guard_impl_base::safe_execute(*this);}
void execute(){(obj_.*mem_fun_)();}
protected:
Obj& obj_;
MemFun mem_fun_;
};
template<class Obj,typename MemFun>
inline obj_scope_guard_impl0<Obj,MemFun> make_obj_guard(Obj& obj,MemFun mem_fun)
{
return obj_scope_guard_impl0<Obj,MemFun>(obj,mem_fun);
}
template<bool cond, class Obj,typename MemFun>
inline typename null_guard_return<cond,obj_scope_guard_impl0<Obj,MemFun> >::type
make_obj_guard_if_c(Obj& obj,MemFun mem_fun)
{
return typename null_guard_return<cond,obj_scope_guard_impl0<Obj,MemFun> >::type(obj,mem_fun);
}
template<typename C, class Obj,typename MemFun>
inline typename null_guard_return<C::value,obj_scope_guard_impl0<Obj,MemFun> >::type
make_obj_guard_if(Obj& obj,MemFun mem_fun)
{
return make_obj_guard_if_c<C::value>(obj,mem_fun);
}
template<class Obj,typename MemFun,typename P1>
class obj_scope_guard_impl1:public scope_guard_impl_base
{
public:
obj_scope_guard_impl1(Obj& obj,MemFun mem_fun,P1 p1):
obj_(obj),mem_fun_(mem_fun),p1_(p1){}
~obj_scope_guard_impl1(){scope_guard_impl_base::safe_execute(*this);}
void execute(){(obj_.*mem_fun_)(p1_);}
protected:
Obj& obj_;
MemFun mem_fun_;
const P1 p1_;
};
template<class Obj,typename MemFun,typename P1>
inline obj_scope_guard_impl1<Obj,MemFun,P1> make_obj_guard(
Obj& obj,MemFun mem_fun,P1 p1)
{
return obj_scope_guard_impl1<Obj,MemFun,P1>(obj,mem_fun,p1);
}
template<bool cond, class Obj,typename MemFun,typename P1>
inline typename null_guard_return<cond,obj_scope_guard_impl1<Obj,MemFun,P1> >::type
make_obj_guard_if_c( Obj& obj,MemFun mem_fun,P1 p1)
{
return typename null_guard_return<cond,obj_scope_guard_impl1<Obj,MemFun,P1> >::type(obj,mem_fun,p1);
}
template<typename C, class Obj,typename MemFun,typename P1>
inline typename null_guard_return<C::value,obj_scope_guard_impl1<Obj,MemFun,P1> >::type
make_obj_guard_if( Obj& obj,MemFun mem_fun,P1 p1)
{
return make_obj_guard_if_c<C::value>(obj,mem_fun,p1);
}
template<class Obj,typename MemFun,typename P1,typename P2>
class obj_scope_guard_impl2:public scope_guard_impl_base
{
public:
obj_scope_guard_impl2(Obj& obj,MemFun mem_fun,P1 p1,P2 p2):
obj_(obj),mem_fun_(mem_fun),p1_(p1),p2_(p2)
{}
~obj_scope_guard_impl2(){scope_guard_impl_base::safe_execute(*this);}
void execute(){(obj_.*mem_fun_)(p1_,p2_);}
protected:
Obj& obj_;
MemFun mem_fun_;
const P1 p1_;
const P2 p2_;
};
template<class Obj,typename MemFun,typename P1,typename P2>
inline obj_scope_guard_impl2<Obj,MemFun,P1,P2>
make_obj_guard(Obj& obj,MemFun mem_fun,P1 p1,P2 p2)
{
return obj_scope_guard_impl2<Obj,MemFun,P1,P2>(obj,mem_fun,p1,p2);
}
template<bool cond, class Obj,typename MemFun,typename P1,typename P2>
inline typename null_guard_return<cond,obj_scope_guard_impl2<Obj,MemFun,P1,P2> >::type
make_obj_guard_if_c(Obj& obj,MemFun mem_fun,P1 p1,P2 p2)
{
return typename null_guard_return<cond,obj_scope_guard_impl2<Obj,MemFun,P1,P2> >::type(obj,mem_fun,p1,p2);
}
template<typename C, class Obj,typename MemFun,typename P1,typename P2>
inline typename null_guard_return<C::value,obj_scope_guard_impl2<Obj,MemFun,P1,P2> >::type
make_obj_guard_if(Obj& obj,MemFun mem_fun,P1 p1,P2 p2)
{
return make_obj_guard_if_c<C::value>(obj,mem_fun,p1,p2);
}
template<class Obj,typename MemFun,typename P1,typename P2,typename P3>
class obj_scope_guard_impl3:public scope_guard_impl_base
{
public:
obj_scope_guard_impl3(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3):
obj_(obj),mem_fun_(mem_fun),p1_(p1),p2_(p2),p3_(p3)
{}
~obj_scope_guard_impl3(){scope_guard_impl_base::safe_execute(*this);}
void execute(){(obj_.*mem_fun_)(p1_,p2_,p3_);}
protected:
Obj& obj_;
MemFun mem_fun_;
const P1 p1_;
const P2 p2_;
const P3 p3_;
};
template<class Obj,typename MemFun,typename P1,typename P2,typename P3>
inline obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3>
make_obj_guard(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3)
{
return obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3>(obj,mem_fun,p1,p2,p3);
}
template<bool cond, class Obj,typename MemFun,typename P1,typename P2,typename P3>
inline typename null_guard_return<cond,obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3> >::type
make_obj_guard_if_c(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3)
{
return typename null_guard_return<cond,obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3> >::type(obj,mem_fun,p1,p2,p3);
}
template<typename C, class Obj,typename MemFun,typename P1,typename P2,typename P3>
inline typename null_guard_return<C::value,obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3> >::type
make_obj_guard_if(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3)
{
return make_obj_guard_if_c<C::value>(obj,mem_fun,p1,p2,p3);
}
} /* namespace multi_index::detail */
} /* namespace multi_index */
|
// Copyright (c) 2018 The PIVX developers
// Copyright (c) 2018 The Midas developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "multisigdialog.h"
#include "forms/ui_multisigdialog.h"
#include "askpassphrasedialog.h"
#include "primitives/transaction.h"
#include "addressbookpage.h"
#include "utilstrencodings.h"
#include "core_io.h"
#include "script/script.h"
#include "base58.h"
#include "coins.h"
#include "keystore.h"
#include "init.h"
#include "wallet.h"
#include "script/sign.h"
#include "script/interpreter.h"
#include "utilmoneystr.h"
#include "guiutil.h"
#include "qvalidatedlineedit.h"
#include "bitcoinamountfield.h"
#include <QVariant>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QToolButton>
#include <QSpinBox>
#include <QClipboard>
#include <QDebug>
#include <QArgument>
#include <QtGlobal>
#include <QString>
MultisigDialog::MultisigDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::MultisigDialog),
model(0)
{
ui->setupUi(this);
multisigTx = CMutableTransaction();
//flag to show keyScrollArea on first priv key added
isFirstPrivKey = true;
isFirstRawTx = true;
ui->keyScrollArea->hide();
ui->txInputsScrollArea->hide();
connect(ui->commitButton, SIGNAL(clicked()), this, SLOT(commitMultisigTx()));
//populate lists with initial objects
on_addAddressButton_clicked();
on_addAddressButton_clicked();
on_addDestinationButton_clicked();
this->setStyleSheet(GUIUtil::loadStyleSheet());
}
MultisigDialog::~MultisigDialog()
{
delete ui;
}
void MultisigDialog::setModel(WalletModel *model)
{
this->model = model;
}
void MultisigDialog::showTab(int index)
{
ui->multisigTabWidget->setCurrentIndex(index);
this->show();
}
void MultisigDialog::updateCoinControl(CAmount nAmount, unsigned int nQuantity)
{
ui->labelAmount_int->setText(QString::fromStdString(FormatMoney(nAmount)));
ui->labelQuantity_int->setText(QString::number(nQuantity));
}
/**
* Private Slots
*/
//slot for pasting addresses
void MultisigDialog::pasteText()
{
QWidget* pasteButton = qobject_cast<QWidget*>(sender());
if(!pasteButton)return;
QFrame* addressFrame = qobject_cast<QFrame*>(pasteButton->parentWidget());
if(!addressFrame)return;
QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address");
if(!vle)return;
vle->setText(QApplication::clipboard()->text());
}
//slot for deleting QFrames with the delete buttons
void MultisigDialog::deleteFrame()
{
QWidget *buttonWidget = qobject_cast<QWidget*>(sender());
if(!buttonWidget)return;
//if deleting last raw input/priv key, hide scroll area
if(buttonWidget->objectName() == "inputDeleteButton" && ui->inputsList->count() == 1){
isFirstRawTx = true;
ui->txInputsScrollArea->hide();
}else if(buttonWidget->objectName() == "keyDeleteButton" && ui->keyList->count() == 1){
isFirstPrivKey = true;
ui->keyScrollArea->hide();
}
QFrame* frame = qobject_cast<QFrame*>(buttonWidget->parentWidget());
if(!frame)return;
//figure out which frame was updated so we can update the correct list
bool destinationFrame = false, addressFrame = false, keyFrame = false, txInputFrame = false;
if (frame->objectName() == QString::fromStdString("destinationFrame"))
destinationFrame = true;
else if (frame->objectName() == QString::fromStdString("addressFrame"))
addressFrame = true;
else if (frame->objectName() == QString::fromStdString("keyFrame"))
keyFrame = true;
else if (frame->objectName() == QString::fromStdString("txInputFrame"))
txInputFrame = true;
delete frame;
//update the correct list inputs
//using else-if instead of else to stop accidental Seg faults
//if method is called on a frame that isn't a destinationFrame, addressFrame, keyFrame, txInputFrame
if (addressFrame) {
for (int i = 0; i < ui->addressList->count(); i++) {
QWidget *input = qobject_cast<QWidget *>(ui->addressList->itemAt(i)->widget());
QLabel *addressLabel = input->findChild<QLabel *>("addressLabel");
addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", i + 1).c_str(), 0));
}
}
else if (destinationFrame) {
for (int i = 0; i < ui->destinationsList->count(); i++) {
QWidget *input = qobject_cast<QWidget *>(ui->destinationsList->itemAt(i)->widget());
QLabel *destinationAddressLabel = input->findChild<QLabel *>("destinationAddressLabel");
destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", i + 1).c_str(), 0));
}
}
else if (keyFrame) {
for (int i = 0; i < ui->keyList->count(); i++) {
QWidget *input = qobject_cast<QWidget *>(ui->keyList->itemAt(i)->widget());
QLabel *keyListLabel = input->findChild<QLabel *>("keyLabel");
keyListLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", i + 1).c_str(), 0));
}
}
else if (txInputFrame) {
for (int i = 0; i < ui->inputsList->count(); i++) {
QWidget *input = qobject_cast<QWidget *>(ui->inputsList->itemAt(i)->widget());
QLabel *txInputIdLabel = input->findChild<QLabel *>("txInputIdLabel");
txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", i + 1).c_str(), 0));
}
}
}
//slot to open address book dialog
void MultisigDialog::addressBookButtonReceiving()
{
QWidget* addressButton = qobject_cast<QWidget*>(sender());
if(!addressButton)return;
QFrame* addressFrame = qobject_cast<QFrame*>(addressButton->parentWidget());
if(!addressFrame)return;
QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address");
if(!vle)return;
if (model && model->getAddressTableModel()) {
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec()) {
vle->setText(dlg.getReturnValue());
}
}
}
//create address
void MultisigDialog::on_addMultisigButton_clicked()
{
if(!model)
return;
int m = ui->enterMSpinbox->value();
vector<string> keys;
for (int i = 0; i < ui->addressList->count(); i++) {
QWidget* address = qobject_cast<QWidget*>(ui->addressList->itemAt(i)->widget());
QValidatedLineEdit* vle = address->findChild<QValidatedLineEdit*>("address");
if(!vle->text().isEmpty()){
keys.push_back(vle->text().toStdString());
}
}
addMultisig(m, keys);
}
void MultisigDialog::on_importAddressButton_clicked(){
if(!model)
return;
string sRedeem = ui->importRedeem->text().toStdString();
if(sRedeem.empty()){
ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }");
ui->addMultisigStatus->setText("Import box empty!");
return;
}
vector<string> vRedeem;
size_t pos = 0;
//search redeem input delimited by space
while ((pos = sRedeem.find(" ")) != std::string::npos) {
vRedeem.push_back(sRedeem.substr(0, pos));
sRedeem.erase(0, pos + 1);
}
vector<string> keys(vRedeem.begin()+1, vRedeem.end()-1);
addMultisig(stoi(vRedeem[0]), keys);
// rescan to find txs associated with imported address
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
bool MultisigDialog::addMultisig(int m, vector<string> keys){
try{
string error;
CScript redeem;
if(!createRedeemScript(m, keys, redeem, error)){
throw runtime_error(error.data());
}
if (::IsMine(*pwalletMain, redeem) == ISMINE_SPENDABLE){
throw runtime_error("The wallet already contains this script");
}
if(!pwalletMain->AddCScript(redeem)){
throw runtime_error("Failure: address invalid or already exists");
}
CScriptID innerID(redeem);
string label = ui->multisigAddressLabel->text().toStdString();
pwalletMain->SetAddressBook(innerID, label, "receive");
if (!pwalletMain->AddMultiSig(redeem)){
throw runtime_error("Failure: unable to add address as watch only");
}
ui->addMultisigStatus->setStyleSheet("QLabel { color: black; }");
ui->addMultisigStatus->setText("Multisignature address " +
QString::fromStdString(CBitcoinAddress(innerID).ToString()) +
" has been added to the wallet.\nSend the redeem below for other owners to import:\n" +
QString::fromStdString(redeem.ToString()));
}catch(const runtime_error& e) {
ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }");
ui->addMultisigStatus->setText(tr(e.what()));
return false;
}
return true;
}
//spend
void MultisigDialog::on_createButton_clicked()
{
if(!model)
return;
vector<CTxIn> vUserIn;
vector<CTxOut> vUserOut;
try{
//Add inputs from Coin Control if any are selected
if (CoinControlDialog::coinControl->HasSelected()) {
vector<COutPoint> vSelected;
CoinControlDialog::coinControl->ListSelected(vSelected);
for (auto outpoint : vSelected)
vUserIn.emplace_back(CTxIn(outpoint));
}else{//check for raw inputs
for(int i = 0; i < ui->inputsList->count(); i++){
QWidget* input = qobject_cast<QWidget*>(ui->inputsList->itemAt(i)->widget());
QLineEdit* txIdLine = input->findChild<QLineEdit*>("txInputId");
if(txIdLine->text().isEmpty()){
ui->createButtonStatus->setStyleSheet("QLabel { color: red; }");
ui->createButtonStatus->setText(tr("Invalid Tx Hash."));
return;
}
QSpinBox* txVoutLine = input->findChild<QSpinBox*>("txInputVout");
int nOutput = txVoutLine->value();
if(nOutput < 0){
ui->createButtonStatus->setStyleSheet("QLabel { color: red; }");
ui->createButtonStatus->setText(tr("Vout position must be positive."));
return;
}
uint256 txid = uint256S(txIdLine->text().toStdString());
CTxIn in(COutPoint(txid, nOutput));
vUserIn.emplace_back(in);
}
}
//validate destinations
bool validInput = true;
for(int i = 0; i < ui->destinationsList->count(); i++){
QWidget* dest = qobject_cast<QWidget*>(ui->destinationsList->itemAt(i)->widget());
QValidatedLineEdit* addr = dest->findChild<QValidatedLineEdit*>("destinationAddress");
BitcoinAmountField* amt = dest->findChild<BitcoinAmountField*>("destinationAmount");
CBitcoinAddress address;
bool validDest = true;
if(!model->validateAddress(addr->text())){
addr->setValid(false);
validDest = false;
}else{
address = CBitcoinAddress(addr->text().toStdString());
}
if(!amt->validate()){
amt->setValid(false);
validDest = false;
}
if(!validDest){
validInput = false;
continue;
}
CScript scriptPubKey = GetScriptForDestination(address.Get());
CTxOut out(amt->value(), scriptPubKey);
vUserOut.push_back(out);
}
//if all user data valid create a multisig tx
if(validInput){
//clear member variable
multisigTx = CMutableTransaction();
string error;
string fee;
if(!createMultisigTransaction(vUserIn, vUserOut, fee, error)){
throw runtime_error(error);
}
//display status string
ui->createButtonStatus->setStyleSheet("QTextEdit{ color: black }");
QString status(strprintf("Transaction has successfully created with a fee of %s.\n"
"The transaction has been automatically imported to the sign tab.\n"
"Please continue on to sign the tx from this wallet, to access the hex to send to other owners.", fee).c_str());
ui->createButtonStatus->setText(status);
ui->transactionHex->setText(QString::fromStdString(EncodeHexTx(multisigTx)));
}
}catch(const runtime_error& e){
ui->createButtonStatus->setStyleSheet("QTextEdit{ color: red }");
ui->createButtonStatus->setText(tr(e.what()));
}
}
bool MultisigDialog::createMultisigTransaction(vector<CTxIn> vUserIn, vector<CTxOut> vUserOut, string& feeStringRet, string& errorRet)
{
try{
//attempt to access the given inputs
CCoinsViewCache view = getInputsCoinsViewCache(vUserIn);
//retrieve total input val and change dest
CAmount totalIn = 0;
vector<CAmount> vInputVals;
CScript changePubKey;
bool fFirst = true;
for(CTxIn in : vUserIn){
const CCoins* coins = view.AccessCoins(in.prevout.hash);
if(!coins->IsAvailable(in.prevout.n) || coins == NULL){
continue;
}
CTxOut prevout = coins->vout[in.prevout.n];
CScript privKey = prevout.scriptPubKey;
vInputVals.push_back(prevout.nValue);
totalIn += prevout.nValue;
if(!fFirst){
if(privKey != changePubKey){
throw runtime_error("Address mismatch! Inputs must originate from the same multisignature address.");
}
}else{
fFirst = false;
changePubKey = privKey;
}
}
CAmount totalOut = 0;
//retrieve total output val
for(CTxOut out : vUserOut){
totalOut += out.nValue;
}
if(totalIn < totalOut){
throw runtime_error("Not enough Midas provided as input to complete transaction (including fee).");
}
//calculate change amount
CAmount changeAmount = totalIn - totalOut;
CTxOut change(changeAmount, changePubKey);
//generate random position for change
unsigned int changeIndex = rand() % (vUserOut.size() + 1);
//insert change into random position
if(changeIndex < vUserOut.size()){
vUserOut.insert(vUserOut.begin() + changeIndex, change);
}else{
vUserOut.emplace_back(change);
}
//populate tx
CMutableTransaction tx;
tx.vin = vUserIn;
tx.vout = vUserOut;
const CCoins* coins = view.AccessCoins(tx.vin[0].prevout.hash);
if(coins == NULL || !coins->IsAvailable(tx.vin[0].prevout.n)){
throw runtime_error("Coins unavailable (unconfirmed/spent)");
}
CScript prevPubKey = coins->vout[tx.vin[0].prevout.n].scriptPubKey;
//get payment destination
CTxDestination address;
if(!ExtractDestination(prevPubKey, address)){
throw runtime_error("Could not find address for destination.");
}
CScriptID hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (!pwalletMain->GetCScript(hash, redeemScript)){
throw runtime_error("could not redeem");
}
txnouttype type;
vector<CTxDestination> addresses;
int nReq;
if(!ExtractDestinations(redeemScript, type, addresses, nReq)){
throw runtime_error("Could not extract destinations from redeem script.");
}
for(CTxIn& in : tx.vin){
in.scriptSig.clear();
//scale estimate to account for multisig scriptSig
for(unsigned int i = 0; i < 50*(nReq+addresses.size()); i++){
in.scriptSig << INT64_MAX;
}
}
//calculate fee
unsigned int nBytes = tx.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
CAmount fee = ::minRelayTxFee.GetFee(nBytes);
if(tx.vout.at(changeIndex).nValue > fee){
tx.vout.at(changeIndex).nValue -= fee;
feeStringRet = strprintf("%d",((double)fee)/COIN).c_str();
}else{
throw runtime_error("Not enough Midas provided to cover fee");
}
//clear junk from script sigs
for(CTxIn& in : tx.vin){
in.scriptSig.clear();
}
multisigTx = tx;
}catch(const runtime_error& e){
errorRet = e.what();
return false;
}
return true;
}
//sign
void MultisigDialog::on_signButton_clicked()
{
if(!model)
return;
try{
//parse tx hex
CTransaction txRead;
if(!DecodeHexTx(txRead, ui->transactionHex->text().toStdString())){
throw runtime_error("Failed to decode transaction hex!");
}
CMutableTransaction tx(txRead);
//check if transaction is already fully verified
if(isFullyVerified(tx)){
this->multisigTx = tx;
ui->commitButton->setEnabled(true);
ui->signButtonStatus->setText("This transaction is ready to commit. \nThe commit button in now enabled.");
return;
}
string errorOut = string();
bool fComplete = signMultisigTx(tx, errorOut, ui->keyList);
if(!errorOut.empty()){
throw runtime_error(errorOut.data());
}else{
this->multisigTx = tx;
}
ui->signButtonStatus->setStyleSheet("QTextEdit{ color: black }");
ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx));
}catch(const runtime_error& e){
ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }");
ui->signButtonStatus->setText(tr(e.what()));
}
}
/***
*private helper functions
*/
QString MultisigDialog::buildMultisigTxStatusString(bool fComplete, const CMutableTransaction& tx)
{
string sTxHex = EncodeHexTx(tx);
if(fComplete){
ui->commitButton->setEnabled(true);
string sTxId = tx.GetHash().GetHex();
string sTxComplete = "Complete: true!\n"
"The commit button has now been enabled for you to finalize the transaction.\n"
"Once the commit button is clicked, the transaction will be published and coins transferred "
"to their destinations.\nWARNING: THE ACTIONS OF THE COMMIT BUTTON ARE FINAL AND CANNOT BE REVERSED.";
return QString(strprintf("%s\nTx Id:\n%s\nTx Hex:\n%s",sTxComplete, sTxId, sTxHex).c_str());
} else {
string sTxIncomplete = "Complete: false.\n"
"You may now send the hex below to another owner to sign.\n"
"Keep in mind the transaction must be passed from one owner to the next for signing.\n"
"Ensure all owners have imported the redeem before trying to sign. (besides creator)";
return QString(strprintf("%s\nTx Hex: %s", sTxIncomplete, sTxHex).c_str());
}
}
CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const vector<CTxIn>& vin)
{
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache& viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for(const CTxIn& txin : vin) {
const uint256& prevHash = txin.prevout.hash;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
return view;
}
bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, QVBoxLayout* keyList)
{
//will be set false if all inputs are not fully signed(valid)
bool fComplete = true;
//if keyslist is not default value AND has items in list then true
bool fGivenKeys = (keyList != nullptr) && (keyList->count() > 0);
try{
//copy of vin for reference before vin is mutated
vector<CTxIn> oldVin(tx.vin);
CBasicKeyStore privKeystore;
//if keys were given, attempt to collect redeem and scriptpubkey
if(fGivenKeys){
for(int i = 0; i < keyList->count(); i++){
QWidget* keyFrame = qobject_cast<QWidget*>(keyList->itemAt(i)->widget());
QLineEdit* key = keyFrame->findChild<QLineEdit*>("key");
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(key->text().toStdString()))
throw runtime_error("Invalid private key");
CKey cKey = vchSecret.GetKey();
if (!cKey.IsValid())
throw runtime_error("Private key outside allowed range");
privKeystore.AddKey(cKey);
}
for(CTxIn& txin : tx.vin){
//get inputs
CTransaction txVin;
uint256 hashBlock;
if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true))
throw runtime_error("txin could not be found");
if (hashBlock == 0)
throw runtime_error("txin is unconfirmed");
//get pubkey from input
CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey;
//get payment destination
CTxDestination address;
if(!ExtractDestination(prevPubKey, address)){
throw runtime_error("Could not find address for destination.");
}
//get redeem script related to destination
CScriptID hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (!pwalletMain->GetCScript(hash, redeemScript)){
errorOut = "could not redeem";
}
privKeystore.AddCScript(redeemScript);
}
}else{
if (model->getEncryptionStatus() == model->Locked) {
if (!model->requestUnlock(AskPassphraseDialog::Context::Multi_Sig, true).isValid()) {
// Unlock wallet was cancelled
throw runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first.");
}
}
}
//choose between local wallet and provided
const CKeyStore& keystore = fGivenKeys ? privKeystore : *pwalletMain;
//attempt to sign each input from local wallet
int nIn = 0;
for(CTxIn& txin : tx.vin){
//get inputs
CTransaction txVin;
uint256 hashBlock;
if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true))
throw runtime_error("txin could not be found");
if (hashBlock == 0)
throw runtime_error("txin is unconfirmed");
txin.scriptSig.clear();
CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey;
//sign what we can
SignSignature(keystore, prevPubKey, tx, nIn);
//merge in any previous signatures
txin.scriptSig = CombineSignatures(prevPubKey, tx, nIn, txin.scriptSig, oldVin[nIn].scriptSig);
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){
fComplete = false;
}
nIn++;
}
ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx));
}catch(const runtime_error& e){
errorOut = string(e.what());
fComplete = false;
}
return fComplete;
}
// quick check for an already fully signed tx
bool MultisigDialog::isFullyVerified(CMutableTransaction& tx){
try{
int nIn = 0;
for(CTxIn& txin : tx.vin){
CTransaction txVin;
uint256 hashBlock;
if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)){
throw runtime_error("txin could not be found");
}
if (hashBlock == 0){
throw runtime_error("txin is unconfirmed");
}
//get pubkey from this input as output in last tx
CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){
return false;
}
nIn++;
}
}catch(const runtime_error& e){
return false;
}
return true;
}
void MultisigDialog::commitMultisigTx()
{
CMutableTransaction tx(multisigTx);
try{
#ifdef ENABLE_WALLET
CWalletTx wtx(pwalletMain, tx);
CReserveKey keyChange(pwalletMain);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw runtime_error(string("Transaction rejected - Failed to commit"));
#else
uint256 hashTx = tx.GetHash();
CCoinsViewCache& view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fOverrideFees = false;
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
if (state.IsInvalid())
throw runtime_error(strprintf("Transaction rejected - %i: %s", state.GetRejectCode(), state.GetRejectReason()));
else
throw runtime_error(string("Transaction rejected - ") + state.GetRejectReason());
}
} else if (fHaveChain) {
throw runtime_error("transaction already in block chain");
}
RelayTransaction(tx);
#endif
//disable commit if successfully committed
ui->commitButton->setEnabled(false);
ui->signButtonStatus->setText(strprintf("Transaction has been successfully published with transaction ID:\n %s", tx.GetHash().GetHex()).c_str());
}catch(const runtime_error& e){
ui->signButtonStatus->setText(e.what());
}
}
bool MultisigDialog::createRedeemScript(int m, vector<string> vKeys, CScript& redeemRet, string& errorRet)
{
try{
int n = vKeys.size();
//gather pub keys
if (n < 1)
throw runtime_error("a Multisignature address must require at least one key to redeem");
if (n < m)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %d keys, but need at least %d to redeem)",
m, n));
if (n > 15)
throw runtime_error("Number of addresses involved in the Multisignature address creation > 15\nReduce the number");
vector<CPubKey> pubkeys;
pubkeys.resize(n);
int i = 0;
for(vector<string>::iterator it = vKeys.begin(); it != vKeys.end(); ++it) {
string keyString = *it;
#ifdef ENABLE_WALLET
// Case 1: Midas address and we have full public key:
CBitcoinAddress address(keyString);
if (pwalletMain && address.IsValid()) {
CKeyID keyID;
if (!address.GetKeyID(keyID)) {
throw runtime_error(
strprintf("%s does not refer to a key", keyString));
}
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s", keyString));
if (!vchPubKey.IsFullyValid()){
string sKey = keyString.empty()?"(empty)":keyString;
throw runtime_error(" Invalid public key: " + sKey );
}
pubkeys[i++] = vchPubKey;
}
//case 2: hex pub key
else
#endif
if (IsHex(keyString)) {
CPubKey vchPubKey(ParseHex(keyString));
if (!vchPubKey.IsFullyValid()){
throw runtime_error(" Invalid public key: " + keyString);
}
pubkeys[i++] = vchPubKey;
} else {
throw runtime_error(" Invalid public key: " + keyString);
}
}
//populate redeem script
//OP_N for required signatures
redeemRet << redeemRet.EncodeOP_N(m);
//public keys
for(CPubKey& key : pubkeys){
vector<unsigned char> vKey= ToByteVector(key);
redeemRet << vKey;
}
//OP_N for total pubkeys
redeemRet << redeemRet.EncodeOP_N(pubkeys.size());
redeemRet << OP_CHECKMULTISIG;
return true;
}catch(const runtime_error& e){
errorRet = string(e.what());
return false;
}
}
/***
* Begin QFrame object creation methods
*/
//creates an address object on the create tab
void MultisigDialog::on_addAddressButton_clicked()
{
//max addresses 15
if(ui->addressList->count() >= 15){
ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }");
ui->addMultisigStatus->setText(tr("Maximum possible addresses reached. (15)"));
return;
}
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
QFrame* addressFrame = new QFrame();
sizePolicy.setHeightForWidth(addressFrame->sizePolicy().hasHeightForWidth());
addressFrame->setSizePolicy(sizePolicy);
addressFrame->setFrameShape(QFrame::StyledPanel);
addressFrame->setFrameShadow(QFrame::Raised);
addressFrame->setObjectName(QStringLiteral("addressFrame"));
QVBoxLayout* frameLayout = new QVBoxLayout(addressFrame);
frameLayout->setSpacing(1);
frameLayout->setObjectName(QStringLiteral("frameLayout"));
frameLayout->setContentsMargins(6, 6, 6, 6);
QHBoxLayout* addressLayout = new QHBoxLayout();
addressLayout->setSpacing(2);
addressLayout->setObjectName(QStringLiteral("addressLayout"));
QLabel* addressLabel = new QLabel(addressFrame);
addressLabel->setObjectName(QStringLiteral("addressLabel"));
addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", ui->addressList->count()+1).c_str() , 0));
addressLayout->addWidget(addressLabel);
QValidatedLineEdit* address = new QValidatedLineEdit(addressFrame);
address->setObjectName(QStringLiteral("address"));
addressLayout->addWidget(address);
QToolButton* addressBookButton = new QToolButton(addressFrame);
addressBookButton->setObjectName(QStringLiteral("addressBookButton"));
QIcon icon3;
icon3.addFile(QStringLiteral(":/icons/address-book"), QSize(), QIcon::Normal, QIcon::Off);
addressBookButton->setIcon(icon3);
connect(addressBookButton, SIGNAL(clicked()), this, SLOT(addressBookButtonReceiving()));
addressLayout->addWidget(addressBookButton);
QToolButton* addressPasteButton = new QToolButton(addressFrame);
addressPasteButton->setObjectName(QStringLiteral("addressPasteButton"));
QIcon icon4;
icon4.addFile(QStringLiteral(":/icons/editpaste"), QSize(), QIcon::Normal, QIcon::Off);
addressPasteButton->setIcon(icon4);
connect(addressPasteButton, SIGNAL(clicked()), this, SLOT(pasteText()));
addressLayout->addWidget(addressPasteButton);
QToolButton* addressDeleteButton = new QToolButton(addressFrame);
addressDeleteButton->setObjectName(QStringLiteral("addressDeleteButton"));
QIcon icon5;
icon5.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
addressDeleteButton->setIcon(icon5);
connect(addressDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
addressLayout->addWidget(addressDeleteButton);
frameLayout->addLayout(addressLayout);
ui->addressList->addWidget(addressFrame);
}
void MultisigDialog::on_pushButtonCoinControl_clicked()
{
CoinControlDialog coinControlDialog(this, true);
coinControlDialog.setModel(model);
coinControlDialog.exec();
}
void MultisigDialog::on_addInputButton_clicked()
{
if(isFirstRawTx){
isFirstRawTx = false;
ui->txInputsScrollArea->show();
}
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
QFrame* txInputFrame = new QFrame(ui->txInputsWidget);
sizePolicy.setHeightForWidth(txInputFrame->sizePolicy().hasHeightForWidth());
txInputFrame->setFrameShape(QFrame::StyledPanel);
txInputFrame->setFrameShadow(QFrame::Raised);
txInputFrame->setObjectName(QStringLiteral("txInputFrame"));
QVBoxLayout* frameLayout = new QVBoxLayout(txInputFrame);
frameLayout->setSpacing(1);
frameLayout->setObjectName(QStringLiteral("txInputFrameLayout"));
frameLayout->setContentsMargins(6, 6, 6, 6);
QHBoxLayout* txInputLayout = new QHBoxLayout();
txInputLayout->setSpacing(2);
txInputLayout->setObjectName(QStringLiteral("txInputLayout"));
QLabel* txInputIdLabel = new QLabel(txInputFrame);
txInputIdLabel->setObjectName(QStringLiteral("txInputIdLabel"));
txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", ui->inputsList->count()+1).c_str(), 0));
txInputLayout->addWidget(txInputIdLabel);
QLineEdit* txInputId = new QLineEdit(txInputFrame);
txInputId->setObjectName(QStringLiteral("txInputId"));
txInputLayout->addWidget(txInputId);
QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);
txInputLayout->addItem(horizontalSpacer);
QLabel* txInputVoutLabel = new QLabel(txInputFrame);
txInputVoutLabel->setObjectName(QStringLiteral("txInputVoutLabel"));
txInputVoutLabel->setText(QApplication::translate("MultisigDialog", "Vout Position: ", 0));
txInputLayout->addWidget(txInputVoutLabel);
QSpinBox* txInputVout = new QSpinBox(txInputFrame);
txInputVout->setObjectName("txInputVout");
sizePolicy.setHeightForWidth(txInputVout->sizePolicy().hasHeightForWidth());
txInputVout->setSizePolicy(sizePolicy);
txInputLayout->addWidget(txInputVout);
QToolButton* inputDeleteButton = new QToolButton(txInputFrame);
inputDeleteButton->setObjectName(QStringLiteral("inputDeleteButton"));
QIcon icon;
icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
inputDeleteButton->setIcon(icon);
connect(inputDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
txInputLayout->addWidget(inputDeleteButton);
frameLayout->addLayout(txInputLayout);
ui->inputsList->addWidget(txInputFrame);
}
void MultisigDialog::on_addDestinationButton_clicked()
{
QFrame* destinationFrame = new QFrame(ui->destinationsScrollAreaContents);
destinationFrame->setObjectName(QStringLiteral("destinationFrame"));
destinationFrame->setFrameShape(QFrame::StyledPanel);
destinationFrame->setFrameShadow(QFrame::Raised);
QVBoxLayout* frameLayout = new QVBoxLayout(destinationFrame);
frameLayout->setObjectName(QStringLiteral("destinationFrameLayout"));
QHBoxLayout* destinationLayout = new QHBoxLayout();
destinationLayout->setSpacing(0);
destinationLayout->setObjectName(QStringLiteral("destinationLayout"));
QLabel* destinationAddressLabel = new QLabel(destinationFrame);
destinationAddressLabel->setObjectName(QStringLiteral("destinationAddressLabel"));
destinationLayout->addWidget(destinationAddressLabel);
QValidatedLineEdit* destinationAddress = new QValidatedLineEdit(destinationFrame);
destinationAddress->setObjectName(QStringLiteral("destinationAddress"));
destinationLayout->addWidget(destinationAddress);
QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);
destinationLayout->addItem(horizontalSpacer);
QLabel* destinationAmountLabel = new QLabel(destinationFrame);
destinationAmountLabel->setObjectName(QStringLiteral("destinationAmountLabel"));
destinationLayout->addWidget(destinationAmountLabel);
BitcoinAmountField* destinationAmount = new BitcoinAmountField(destinationFrame);
destinationAmount->setObjectName(QStringLiteral("destinationAmount"));
destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", ui->destinationsList->count()+1).c_str(), 0));
destinationAmountLabel->setText(QApplication::translate("MultisigDialog", "Amount: ", 0));
destinationLayout->addWidget(destinationAmount);
QToolButton* destinationDeleteButton = new QToolButton(destinationFrame);
destinationDeleteButton->setObjectName(QStringLiteral("destinationDeleteButton"));
QIcon icon;
icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
destinationDeleteButton->setIcon(icon);
connect(destinationDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
destinationLayout->addWidget(destinationDeleteButton);
frameLayout->addLayout(destinationLayout);
ui->destinationsList->addWidget(destinationFrame);
}
void MultisigDialog::on_addPrivKeyButton_clicked()
{
if(isFirstPrivKey){//on first click the scroll area must show
isFirstPrivKey = false;
ui->keyScrollArea->show();
}
if(ui->keyList->count() >= 15){
ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }");
ui->signButtonStatus->setText(tr("Maximum (15)"));
return;
}
QFrame* keyFrame = new QFrame(ui->keyScrollAreaContents);
keyFrame->setObjectName(QStringLiteral("keyFrame"));
keyFrame->setFrameShape(QFrame::StyledPanel);
keyFrame->setFrameShadow(QFrame::Raised);
QHBoxLayout* keyLayout = new QHBoxLayout(keyFrame);
keyLayout->setObjectName(QStringLiteral("keyLayout"));
QLabel* keyLabel = new QLabel(keyFrame);
keyLabel->setObjectName(QStringLiteral("keyLabel"));
keyLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", (ui->keyList->count()+1)).c_str(), 0));
keyLayout->addWidget(keyLabel);
QLineEdit* key = new QLineEdit(keyFrame);
key->setObjectName(QStringLiteral("key"));
key->setEchoMode(QLineEdit::Password);
keyLayout->addWidget(key);
QToolButton* keyDeleteButton = new QToolButton(keyFrame);
keyDeleteButton->setObjectName(QStringLiteral("keyDeleteButton"));
QIcon icon;
icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
keyDeleteButton->setIcon(icon);
connect(keyDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
keyLayout->addWidget(keyDeleteButton);
ui->keyList->addWidget(keyFrame);
}
|
/*
* utils.cc
* Copyright (C) 2019 Marc Kirchner
*
* Distributed under terms of the MIT license.
*/
#include "utils.h"
Vec3 reflect(const Vec3& v, const Vec3& n) {
return v - 2*Vec3::dot(v, n)*n;
}
bool refract(const Vec3& v, const Vec3& n, float nRatio, Vec3& refracted) {
// nRatio is the ratio of refraction indexes
Vec3 u = v.normalized();
float dt = Vec3::dot(u, n);
float discriminant = 1.0 - nRatio*nRatio * (1.0-dt*dt);
if (discriminant > 0.0) {
refracted = nRatio * (u - n*dt) - n*sqrt(discriminant);
return true;
}
return false;
};
Vec3 sample_from_unit_sphere() {
// Sample from the unit cube and reject until we find a point
// inside the sphere.
Vec3 p;
do {
p = 2.0 * Vec3(drand48(), drand48(), drand48()) - Vec3(1.0, 1.0, 0.0);
} while (p.squared_norm() >= 1.0);
return p;
}
Vec3 sample_from_xy_unit_disk() {
// rejection sampling from the unit square until we hit the circle
Vec3 p;
do {
p = 2.0 * Vec3(drand48(), drand48(), 0.0) - Vec3(1.0, 1.0, 0.0);
} while (Vec3::dot(p,p) >= 1.0);
return p;
}
float schlick(float cosine, float refractiveIndex) {
float r0 = (1 - refractiveIndex) / (1 + refractiveIndex);
r0 *= r0;
return r0 + (1-r0)*pow(1-cosine, 5);
}
|
/*
* Copyright 2019-2020 Hewlett Packard Enterprise Development LP.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#include <fcntl.h>
#include <fstream>
#include <sstream>
#include <iterator>
#include <iostream>
#include <memory>
#include <cstdlib>
#include "cti_fe_function_test.hpp"
#include "common_tools_fe.h"
std::string g_systemSpecificArguments = "";
/* cti frontend C interface tests */
// set up g_systemSpecificArguments for further use.
// this is called from main() with a command line argument
void setSysArguments(const std::string &argv) {
g_systemSpecificArguments = argv;
std::cout << "Set system specific arguments to \"" << g_systemSpecificArguments << "\".\n";
}
// take a vector of strings and prepend the system specific arguements to it
std::vector<std::string> createSystemArgv(const std::vector<std::string>& argv) {
// split system specific args by whitespace and insert into fullArgv
std::istringstream iss(g_systemSpecificArguments);
auto fullArgv = std::vector<std::string>{std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>()};
// append passed in argv
std::copy(argv.begin(), argv.end(), std::back_inserter(fullArgv));
for (const auto &str : fullArgv) {
std::cout << str << " ";
}
std::cout << std::endl;
return fullArgv;
}
// take a vector of strings, copy their c_str() pointers to a new vector,
// and add a nullptr at the end. the return value can then be used in
// ctiLaunchApp and similar via "return_value.data()"
std::vector<const char*> cstrVector(const std::vector<std::string> &v) {
std::vector<const char*> r;
for (const auto &str : v) {
r.push_back(str.c_str());
}
r.push_back(nullptr);
return r;
}
// Find my external IP
static auto getExternalAddress()
{
// Get information structs about all network interfaces
struct ifaddrs *ifaddr = nullptr;
if (getifaddrs(&ifaddr) < 0) {
throw std::runtime_error(strerror(errno));
}
// Find the first IP address that isn't localhost
for (struct ifaddrs* ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) {
continue;
}
// Limit to IPv4 and IPv6
auto const family = ifa->ifa_addr->sa_family;
if ((family == AF_INET) || (family == AF_INET6)) {
// Skip if loopback
if (ifa->ifa_flags & IFF_LOOPBACK) {
continue;
}
// Get hostname for interface
char address[NI_MAXHOST];
auto const sockaddr_size = (family == AF_INET)
? sizeof(struct sockaddr_in)
: sizeof(struct sockaddr_in6);
if (auto const rc = getnameinfo(ifa->ifa_addr, sockaddr_size,
address, NI_MAXHOST, nullptr, 0, NI_NUMERICHOST)) {
// Clean up ifaddr
freeifaddrs(ifaddr);
throw std::runtime_error(strerror(errno));
}
// Clean up ifaddr
freeifaddrs(ifaddr);
return std::string{address};
}
}
// Clean up ifaddr
freeifaddrs(ifaddr);
throw std::runtime_error("failed to find any external address");
}
static auto bindAny(std::string const& address)
{
// setup hints
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
// uses external_ip in order to bind socket to external IP and not localhost
// if NULL is used this will ALWAYS give localhost which is not non-wbox compatible
struct addrinfo *raw_listener = nullptr;
if (auto const rc = getaddrinfo(address.c_str(), "0", &hints, &raw_listener)) {
throw std::runtime_error(gai_strerror(rc));
}
auto listener = std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)>(std::move(raw_listener), freeaddrinfo);
raw_listener = nullptr;
// Create the socket
auto const socketFd = socket(listener->ai_family, listener->ai_socktype, listener->ai_protocol);
if (socketFd < 0) {
throw std::runtime_error(strerror(errno));
}
// Bind the socket
if (bind(socketFd, listener->ai_addr, listener->ai_addrlen) < 0) {
throw std::runtime_error(strerror(errno));
}
return socketFd;
}
static void
testSocketDaemon(cti_session_id_t sessionId, char const* daemonPath, std::vector<char const*> extra_argv, std::string const& expecting, int times=1) {
// Wait for any previous cleanups to finish (see PE-26018)
sleep(5);
std::cout << "Getting address and starting to listen...\n";
// Get address accessible from compute node
auto const address = getExternalAddress();
// build 'server' socket
auto const test_socket = bindAny(address);
// Begin listening on socket
ASSERT_EQ(listen(test_socket, 1), 0) << "Failed to listen on test_socket socket";
// get my sockets info
struct sockaddr_in sa;
socklen_t sa_len = sizeof(sa);
memset(&sa, 0, sizeof(sa));
ASSERT_EQ(getsockname(test_socket, (struct sockaddr*) &sa, &sa_len), 0);
// build required parameters for launching external app
{
std::cout << "Launching app...\n";
// create manifest and args
auto const manifestId = cti_createManifest(sessionId);
ASSERT_EQ(cti_manifestIsValid(manifestId), true) << cti_error_str();
std::vector<char const*> v_argv = {address.c_str(), std::to_string(ntohs(sa.sin_port)).c_str()};
v_argv.insert(v_argv.end(), extra_argv.begin(), extra_argv.end());
v_argv.push_back(nullptr);
// launch app
ASSERT_EQ(cti_execToolDaemon(manifestId, daemonPath, v_argv.data(), nullptr), SUCCESS) << cti_error_str();
std::cout << "App launched. Net info: " << address << " " << std::to_string(ntohs(sa.sin_port)) << "\n";
}
// accept recently launched applications connection
std::cout << "Waiting for communication from app...\n";
int app_socket;
struct sockaddr_in wa;
socklen_t wa_len = sizeof(wa);
for (int i = 0; i < times; ++i) {
ASSERT_GE(app_socket = accept(test_socket, (struct sockaddr*) &wa, &wa_len), 0);
// read data returned from app
std::cout << "Reading data...\n";
char buffer[16] = {0};
int length = read(app_socket, buffer, 16);
ASSERT_LT(length, 16);
buffer[length] = '\0';
// check for correctness
std::cout << "Checking for correctness...\n";
ASSERT_STREQ(buffer, expecting.c_str());
}
// close socket
std::cout << "Closing socket...\n";
close(test_socket);
std::cout << "Done!\n";
}
// Test that an app can launch two tool daemons using different libraries with the same name
// This test is at the start to avoid a race condition that causes failure if ran later
TEST_F(CTIFEFunctionTest, DaemonLibDir) {
// set up app
auto const argv = createSystemArgv({"../src/hello_mpi"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// create app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
// create app's session
auto const sessionId = cti_createSession(appId);
ASSERT_EQ(cti_sessionIsValid(sessionId), true) << cti_error_str();
// run printing daemons
testSocketDaemon(sessionId, "../../test_support/one_socket", {}, "1");
testSocketDaemon(sessionId, "../../test_support/two_socket", {}, "2");
// cleanup
EXPECT_EQ(cti_destroySession(sessionId), SUCCESS) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
}
// Tests that the frontend type was correctly detected.
TEST_F(CTIFEFunctionTest, HaveValidFrontend) {
ASSERT_NE(cti_current_wlm(), CTI_WLM_NONE) << cti_error_str();
}
// Test that LD_PRELOAD is restored to environment of job
// one_socket is dynamically linked to message_one/libmessage.so
// libmessage implements get_message() that will return a value of 1, then sent over socket to FE.
// The test will first verify that one_socket normally sends a value of 1.
// Then, it will LD_PRELOAD message_two/libmessage.so, which implements get_message() returning value 2.
// The test will then verify that LD_PRELOAD overrides the get_message() impl. to send a value of 2.
TEST_F(CTIFEFunctionTest, LdPreloadSet)
{
// Wait for any previous cleanups to finish (see PE-26018)
sleep(5);
auto port = std::string{};
// Get address accessible from compute node
auto const address = getExternalAddress();
// build 'server' socket
auto const test_socket = bindAny(address);
// Begin listening on socket
ASSERT_EQ(listen(test_socket, 1), 0) << "Failed to listen on test_socket socket";
// get my sockets info
struct sockaddr_in sa;
socklen_t sa_len = sizeof(sa);
memset(&sa, 0, sizeof(sa));
ASSERT_EQ(getsockname(test_socket, (struct sockaddr*) &sa, &sa_len), 0);
port = std::to_string(ntohs(sa.sin_port));
// doing the C way to get cwd so we don't have to include internal headers
char buf[PATH_MAX + 1];
auto const cwd_cstr = getcwd(buf, PATH_MAX);
ASSERT_NE(cwd_cstr, nullptr) << "getcwd failed.";
std::string cwd = std::string(cwd_cstr);
// Get program and library paths
auto const testSupportPath = cwd + "/../../test_support/";
auto const oneSocketPath = testSupportPath + "one_socket";
auto const messageTwoPath = testSupportPath + "message_two/libmessage.so";
auto const ldPreload = "LD_PRELOAD=" + messageTwoPath;
auto ldLibPath = "LD_LIBRARY_PATH=" + testSupportPath + "message_one";
if (std::getenv("LD_LIBRARY_PATH") != nullptr) {
if (std::string(std::getenv("LD_LIBRARY_PATH")) != "") {
ldLibPath += ":" + std::string(std::getenv("LD_LIBRARY_PATH"));
}
}
std::cout << "Lib path is: " << ldLibPath << std::endl;
{ // Launch application without preload, expect response of 1
// set up app
auto const argv = createSystemArgv({"../src/mpi_wrapper", oneSocketPath, address, port});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* envList[] = {ldLibPath.c_str(), nullptr};
// create app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
// count number of sockets launched
int num_pes = cti_getNumAppPEs(appId);
EXPECT_NE(num_pes, 0) << cti_error_str();
std::cout << num_pes << " sockets launched...\n";
// accept recently launched applications connection
int app_socket;
struct sockaddr_in wa;
socklen_t wa_len = sizeof(wa);
for (int i = 0; i < num_pes; ++i) {
ASSERT_GE(app_socket = accept(test_socket, (struct sockaddr*) &wa, &wa_len), 0);
std::cout << "Got something...\n";
// read data returned from app
char buffer[16] = {0};
int length = read(app_socket, buffer, 16);
std::cout << "Read " << length << " bytes.\n";
ASSERT_LT(length, 16);
buffer[length] = '\0';
std::cout << "Got: " << buffer << std::endl;
// check for correctness
ASSERT_STREQ(buffer, "1");
}
}
{ // Launch application with preload, expect response of 2
// set up app
auto const argv = createSystemArgv({"../src/mpi_wrapper", oneSocketPath.c_str(), address.c_str(), port.c_str()});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const envList[] = {ldLibPath.c_str(), ldPreload.c_str(), nullptr};
// create app
auto const appId = replaceApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
// count number of sockets launched
int num_pes = cti_getNumAppPEs(appId);
EXPECT_NE(num_pes, 0) << cti_error_str();
std::cout << num_pes << " sockets launched...\n";
// accept recently launched applications connection
int app_socket;
struct sockaddr_in wa;
socklen_t wa_len = sizeof(wa);
for (int i = 0; i < num_pes; ++i) {
ASSERT_GE(app_socket = accept(test_socket, (struct sockaddr*) &wa, &wa_len), 0);
// read data returned from app
char buffer[16] = {0};
int length = read(app_socket, buffer, 16);
std::cout << "Read " << length << " bytes.\n";
ASSERT_LT(length, 16);
buffer[length] = '\0';
std::cout << "Got: " << buffer << std::endl;
// check for correctness
ASSERT_STREQ(buffer, "2");
}
}
// close socket
close(test_socket);
}
// Test that an app can launch successfully
TEST_F(CTIFEFunctionTest, Launch) {
auto const argv = createSystemArgv({"sleep", "10"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
auto const appId = watchApp(cti_launchApp(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
}
// Test that an app can launch successfully with the MPIR shim
// This is only supported on SLURM systems. The check for that is done by avocado.
TEST_F(CTIFEFunctionTest, LaunchMPIRShim) {
auto const argv = createSystemArgv({"sleep", "10"});
// Set env vars to use MPIR shim
::setenv("CTI_LAUNCHER_WRAPPER", "wrapper_script.sh", 1);
auto oldPath = std::string{::getenv("PATH") ? ::getenv("PATH") : ""};
auto newPath = "../../test_support" + (oldPath != "" ? ":" + oldPath : "");
::setenv("PATH", newPath.c_str(), 1);
auto const appId = watchApp(cti_launchApp(cstrVector(argv).data(), -1, -1, nullptr, nullptr, nullptr));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
}
// Test that an app can't be released twice
TEST_F(CTIFEFunctionTest, DoubleRelease) {
auto const argv = createSystemArgv({"../src/hello_mpi"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), FAILURE) << cti_error_str();
}
// Test that an app can redirect stdout
TEST_F(CTIFEFunctionTest, StdoutPipe) {
// set up string contents
auto const echoString = std::to_string(getpid());
int pipes[2];
int r = 0;
r = pipe(pipes);
ASSERT_EQ(r, 0) << "Failed to create a pipe.";
FILE *piperead = fdopen(pipes[0], "r");
ASSERT_NE(piperead, nullptr) << "Failed to open pipe for reading.";
// set up launch arguments
std::vector<std::string> argv = createSystemArgv({"../src/mpi_wrapper", "/usr/bin/echo", echoString.c_str()});
auto const stdoutFd = pipes[1];
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// launch app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
ASSERT_EQ(cti_appIsValid(appId), true) << cti_error_str();
ASSERT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
char buf[64];
memset(buf, '\0', 64);
// count number of pes launched
int num_pes = cti_getNumAppPEs(appId);
ASSERT_GT(num_pes, 0) << cti_error_str();
std::cout << num_pes << " pes launched...\n";
// get app output
for (int i = 0; i < num_pes; ++i) {
ASSERT_NE(fgets(buf, 64, piperead), nullptr) << "Failed to read app output from pipe.";
std::cout << "Got: " << buf;
ASSERT_EQ(std::string(buf), echoString + "\n");
}
fclose(piperead);
close(pipes[0]);
close(pipes[1]);
}
// // Test that an app can read input from a file
TEST_F(CTIFEFunctionTest, InputFile) {
int pipes[2];
int r = 0;
r = pipe(pipes);
ASSERT_EQ(r, 0) << "Failed to create a pipe.";
FILE *piperead = fdopen(pipes[0], "r");
ASSERT_NE(piperead, nullptr) << "Failed to open pipe for reading.";
auto const argv = createSystemArgv({"../src/mpi_wrapper", "/usr/bin/cat"});
auto const stdoutFd = pipes[1];
auto const stderrFd = -1;
char const* inputFile = "../src/inputFileData.txt";
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// launch app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
ASSERT_EQ(cti_appIsValid(appId), true) << cti_error_str();
ASSERT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
char buf[128];
memset(buf, '\0', 128);
// get app output
ASSERT_NE(fgets(buf, 128, piperead), nullptr) << "Failed to read app output from pipe.";
std::cout << "Got: " << buf;
ASSERT_EQ(std::string(buf), "see InputFile in cti_fe_function_test.cpp\n");
fclose(piperead);
close(pipes[0]);
close(pipes[1]);
}
// Test that an app can read input from file descriptor
TEST_F(CTIFEFunctionTest, StdinPipe) {
// set up string contents
auto const echoString = std::to_string(getpid()) + "\n";
int stdin_pipe[2];
int stdout_pipe[2];
int r = 0;
r = pipe(stdin_pipe);
ASSERT_EQ(r, 0) << "Failed to create a pipe.";
r = pipe(stdout_pipe);
ASSERT_EQ(r, 0) << "Failed to create a pipe.";
FILE *job_stdout = fdopen(stdout_pipe[0], "r");
ASSERT_NE(job_stdout, nullptr) << "Failed to open pipe for reading.";
// set up launch arguments
std::vector<std::string> argv = createSystemArgv({"../src/mpi_wrapper", "/usr/bin/cat"});
auto const stdoutFd = stdout_pipe[1];
auto const stderrFd = -1;
auto const stdinFd = stdin_pipe[0];
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// launch app
auto const appId = watchApp(cti_launchAppBarrier_fd(cstrVector(argv).data(), stdoutFd, stderrFd, stdinFd, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
ASSERT_EQ(cti_appIsValid(appId), true) << cti_error_str();
ASSERT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
// write app input
write(stdin_pipe[1], echoString.c_str(), echoString.length() + 1);
close(stdin_pipe[1]);
// get app output
char buf[64];
memset(buf, '\0', 64);
ASSERT_NE(fgets(buf, sizeof(buf) - 1, job_stdout), nullptr) << "Failed to read app output from pipe.";
ASSERT_EQ(std::string(buf), echoString);
}
// // Test that an app can forward environment variables
TEST_F(CTIFEFunctionTest, EnvVars) {
// set up string contents
auto const envVar = std::string{"CTI_TEST_VAR"};
auto const envVal = std::to_string(getpid());
auto const envString = envVar + "=" + envVal;
int pipes[2];
int r = 0;
r = pipe(pipes);
ASSERT_EQ(r, 0) << "Failed to create a pipe.";
FILE *piperead = fdopen(pipes[0], "r");
ASSERT_NE(piperead, nullptr) << "Failed to open pipe for reading.";
// set up launch arguments
auto const argv = createSystemArgv({"../src/mpi_wrapper", "/usr/bin/env"});
auto const stdoutFd = pipes[1];
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const envList[] = {envString.c_str(), nullptr};
// launch app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
char buf[512];
memset(buf, '\0', 512);
// count number of pes launched
int num_pes = cti_getNumAppPEs(appId);
ASSERT_GT(num_pes, 0) << cti_error_str();
std::cout << num_pes << " pes launched...\n";
// get app output
bool found = false;
for (int i = 0; i < num_pes; ++i) {
while (fgets(buf, 512, piperead) != nullptr) {
std::string line = std::string(buf);
auto const var = line.substr(0, line.find('='));
auto const val = line.substr(line.find('=') + 1);
if (!var.compare(envVar) && !val.compare(envVal + '\n')) {
found = true;
break;
}
}
ASSERT_TRUE(found);
}
fclose(piperead);
close(pipes[0]);
close(pipes[1]);
}
// Test that an app can create a transfer session
TEST_F(CTIFEFunctionTest, CreateSession) {
// set up app
auto const argv = createSystemArgv({"../src/hello_mpi"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// create app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
// create app's session
auto const sessionId = cti_createSession(appId);
ASSERT_EQ(cti_sessionIsValid(sessionId), true) << cti_error_str();
// cleanup
EXPECT_EQ(cti_destroySession(sessionId), SUCCESS) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
}
// Test that an app can create a transfer manifest
TEST_F(CTIFEFunctionTest, CreateManifest) {
// set up app
auto const argv = createSystemArgv({"../src/hello_mpi"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// create app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
// create app's session
auto const sessionId = cti_createSession(appId);
ASSERT_EQ(cti_sessionIsValid(sessionId), true) << cti_error_str();
// create manifest
auto const manifestId = cti_createManifest(sessionId);
ASSERT_EQ(cti_manifestIsValid(manifestId), true) << cti_error_str();
// cleanup
EXPECT_EQ(cti_destroySession(sessionId), SUCCESS) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
}
// Test that an app can run a tool daemon
TEST_F(CTIFEFunctionTest, ExecToolDaemon) {
// set up app
auto const argv = createSystemArgv({"../src/hello_mpi"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
// create app
auto const appId = watchApp(cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList));
ASSERT_GT(appId, 0) << cti_error_str();
EXPECT_EQ(cti_appIsValid(appId), true) << cti_error_str();
// create app's session
auto const sessionId = cti_createSession(appId);
ASSERT_EQ(cti_sessionIsValid(sessionId), true) << cti_error_str();
// run printing daemons
testSocketDaemon(sessionId, "../../test_support/one_socket", {}, "1");
// cleanup
EXPECT_EQ(cti_destroySession(sessionId), SUCCESS) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(appId), SUCCESS) << cti_error_str();
}
// Test transferring a file in a manifest
TEST_F(CTIFEFunctionTest, Transfer) {
auto const argv = createSystemArgv({"../src/hello_mpi"});
auto const stdoutFd = -1;
auto const stderrFd = -1;
char const* inputFile = nullptr;
char const* chdirPath = nullptr;
char const* const* envList = nullptr;
char const* filename = "../src/testing.info";
char * file_loc;
int r;
auto const myapp = cti_launchAppBarrier(cstrVector(argv).data(), stdoutFd, stderrFd, inputFile, chdirPath, envList);
ASSERT_NE(myapp, 0) << cti_error_str();
// Ensure app is valid
ASSERT_NE(cti_appIsValid(myapp), 0);
// Create a new session based on the app_id
auto const mysid = cti_createSession(myapp);
ASSERT_NE(mysid, 0) << cti_error_str();
// Ensure session is valid
ASSERT_NE(cti_sessionIsValid(mysid), 0);
// Create a manifest based on the session
auto const mymid = cti_createManifest(mysid);
ASSERT_NE(mymid, 0) << cti_error_str();
// Ensure manifest is valid
ASSERT_NE(cti_manifestIsValid(mymid), 0);
// Add the file to the manifest
r = cti_addManifestFile(mymid, filename);
ASSERT_EQ(r, 0) << cti_error_str();
// Ensure manifest is valid
ASSERT_NE(cti_manifestIsValid(mymid), 0);
// Send the manifest to the compute node
r = cti_sendManifest(mymid);
ASSERT_EQ(r, 0) << cti_error_str();
// Ensure manifest is no longer valid
ASSERT_EQ(cti_manifestIsValid(mymid), 0);
// Get the location of the directory where the file now resides on the
// compute node
file_loc = cti_getSessionFileDir(mysid);
ASSERT_NE(file_loc, nullptr) << cti_error_str();
auto const file = std::string(file_loc) + "/testing.info";
std::cout << "Sent testing.info to " << file << " on the compute node(s).\n";
testSocketDaemon(mysid, "../../test_support/remote_filecheck", {file.c_str()}, "1");
EXPECT_EQ(cti_destroySession(mysid), SUCCESS) << cti_error_str();
EXPECT_EQ(cti_releaseAppBarrier(myapp), SUCCESS) << cti_error_str();
}
|
#include "Precomp.h"
#include "CPPBuild.h"
#include <iostream>
int main(int argc, char** argv)
{
try
{
std::vector<std::string> args;
for (int i = 0; i < argc; i++)
args.push_back(argv[i]);
CPPBuild app;
if (args.size() == 2 && args[1] == "generate")
{
app.generate();
return 0;
}
else if (args.size() == 3 && args[1] == "build")
{
app.build(args[2]);
return 0;
}
else if (args.size() == 3 && args[1] == "clean")
{
app.clean(args[2]);
return 0;
}
else if (args.size() == 3 && args[1] == "rebuild")
{
app.rebuild(args[2]);
return 0;
}
else
{
std::cout << "cppbuild generate" << std::endl;
std::cout << "cppbuild build <target>" << std::endl;
std::cout << "cppbuild clean <target>" << std::endl;
std::cout << "cppbuild rebuild <target>" << std::endl;
return 1;
}
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
return 255;
}
}
|
#include <eosiolib/chain.h>
#include <eosiolib/dispatcher.hpp>
#include <eosiolib/singleton.hpp>
#include <eosiolib/table.hpp>
#include <eosiolib/vector.hpp>
#include <identity/identity.hpp>
namespace identity_test {
using eosio::action_meta;
using eosio::singleton;
using std::string;
using std::vector;
class contract {
public:
static const uint64_t code = N(identitytest);
typedef identity::contract< N(identity) > identity_contract;
typedef identity_contract::identity_name identity_name;
typedef identity_contract::property_name property_name;
struct get_owner_for_identity : public action_meta< code, N(getowner) >
{
uint64_t identity;
EOSLIB_SERIALIZE( get_owner_for_identity, (identity) )
};
struct get_identity_for_account : public action_meta< code, N(getidentity) >
{
account_name account ;
EOSLIB_SERIALIZE( get_identity_for_account, (account) )
};
typedef singleton<code, N(result), code, uint64_t> result_table;
static void on( const get_owner_for_identity& c ) {
account_name owner = identity_contract::get_owner_for_identity(c.identity);
result_table::set(owner, 0); //use scope = 0 for simplicity
}
static void on( const get_identity_for_account& c ) {
identity_name idnt = identity_contract::get_identity_for_account(c.account);
result_table::set(idnt, 0); //use scope = 0 for simplicity
}
static void apply( account_name c, action_name act) {
eosio::dispatch<contract, get_owner_for_identity, get_identity_for_account>(c,act);
}
};
} /// namespace identity
extern "C" {
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t code, uint64_t action ) {
identity_test::contract::apply( code, action );
}
}
|
/* iPIC3D was originally developed by Stefano Markidis and Giovanni Lapenta.
* This release was contributed by Alec Johnson and Ivy Bo Peng.
* Publications that use results from iPIC3D need to properly cite
* 'S. Markidis, G. Lapenta, and Rizwan-uddin. "Multi-scale simulations of
* plasma with iPIC3D." Mathematics and Computers in Simulation 80.7 (2010): 1509-1519.'
*
* Copyright 2015 KTH Royal Institute of Technology
* 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 <mpi.h>
#include <stdarg.h>
#include "TimeTasks.h"
#include "asserts.h"
#include "MPIdata.h" // for get_rank
#include "parallel.h"
#include "debug.h"
#include "errors.h"
#include "Collective.h"
#include "string.h" // for strcmp
/** implementation of declarations in utility/TimeTasks.h **/
TimeTasks timeTasks;
static const char *taskNames[] = // order must agree with Tasks in TimeTasks.h
{
"none = 0",
//
"fields",
"particles",
"moments",
"AFTER_EXCLUSIVE",
//
"communicating",
"BEFORE_COMMUNICATION",
"flds_comm",
"flds_mpi_allreduce",
"flds_mpi_sendrecv",
"pcls_comm",
"pcls_mpi_allreduce",
"pcls_mpi_sendrecv",
"moms_comm",
"moms_mpi_allreduce",
"moms_mpi_sendrecv",
//
"BEFORE_REPORT_LIST",
"reduce_fields",
"bfield",
"moment_pcl_sorting",
"moment_accumulation",
"moment_reduction",
"mover_pcl_sorting",
"mover_pcl_moving",
"transpose_pcls_to_aos",
"transpose_pcls_to_soa",
"write_fields",
"write_particles",
"PCLS_MPI_Isend",
"PCLS_MPI_Irecv",
"PCLS_MPI_Wait",
"PCLS_MPI_Cancel",
"PCLS_MPI_Request_free",
"PCLS_MPI_Test",
"PCLS_MPI_Waitany",
//
"number_of_tasks"
};
const char* TimeTasks::get_taskname(int arg)
{
assert_le(arg,NUMBER_OF_TASKS);
return taskNames[arg];
}
void TimeTasks::resetCycle()
{
assert(!strcmp(taskNames[NUMBER_OF_TASKS],"number_of_tasks"));
for(int e=0;e<NUMBER_OF_TASKS;e++)
{
task_duration[e]=0.;
//communicate[e]=0.;
//sendrecv[e]=0.;
//allreduce[e]=0.;
active[e]=false;
stack_depth[e]=0;
start_times[e]=0.;
}
active_task=NONE;
//communicating=false;
}
void TimeTasks::start_main_task(TimeTasks::Tasks taskid)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
assert(is_exclusive(taskid));
assert_ne(active_task, taskid);
active_task = taskid;
assert(!active[taskid]);
active[taskid]=true;
}
void TimeTasks::start_task(TimeTasks::Tasks taskid)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
assert(!is_exclusive(taskid));
assert(!active[taskid]);
active[taskid]=true;
// special behavior per task
switch(taskid)
{
default:
break;
// trigger appropriate communication task
case COMMUNICATING:
switch(active_task)
{
default:
invalid_value_error(active_task);
case FIELDS:
timeTasks.start_task(FLDS_COMM);
break;
case PARTICLES:
timeTasks.start_task(PCLS_COMM);
break;
case MOMENTS:
timeTasks.start_task(MOMS_COMM);
break;
}
break;
case REDUCE_FIELDS:
assert_eq(active_task, FIELDS);
break;
}
}
// have to manage the task stack explicitly
void TimeTasks::start_task(TimeTasks::Tasks taskid, double start_time)
{
if(omp_get_thread_num()) return;
if(stack_depth[taskid]==0)
{
start_times[taskid]=start_time;
start_task(taskid);
}
stack_depth[taskid]++;
}
void TimeTasks::end_main_task(TimeTasks::Tasks taskid, double start_time)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
end_task(taskid, start_time);
active_task = NONE;
}
void TimeTasks::end_task(TimeTasks::Tasks taskid, double start_time)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
assert(active[taskid]);
double now = MPI_Wtime();
// compute time spent on task
task_duration[taskid] += now - start_time;
active[taskid] = false;
switch(taskid)
{
default:
break;
// trigger appropriate communication task
case COMMUNICATING:
switch(active_task)
{
default:
invalid_value_error(active_task);
case FIELDS:
timeTasks.end_task(FLDS_COMM, start_time);
break;
case PARTICLES:
timeTasks.end_task(PCLS_COMM, start_time);
break;
case MOMENTS:
timeTasks.end_task(MOMS_COMM, start_time);
break;
}
break;
case REDUCE_FIELDS:
assert_eq(active_task, FIELDS);
break;
}
}
// have to manage the task stack explicitly
void TimeTasks::end_task(TimeTasks::Tasks taskid)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
stack_depth[taskid]--;
assert_ge(stack_depth[taskid],0);
if(stack_depth[taskid]==0)
{
end_task(taskid, start_times[taskid]);
}
}
// update appropriate XXXX_MPI_SENDRECV task
//
void TimeTasks::end_sendrecv(double start_time)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
int sendrecv_task;
switch(active_task)
{
default:
unsupported_value_error(get_taskname(active_task));
case FIELDS:
sendrecv_task = FLDS_MPI_SENDRECV;
break;
case PARTICLES:
sendrecv_task = PCLS_MPI_SENDRECV;
break;
case MOMENTS:
sendrecv_task = MOMS_MPI_SENDRECV;
break;
}
const double additional_time = MPI_Wtime()-start_time;
task_duration[sendrecv_task] += additional_time;
}
void TimeTasks::end_allreduce(double start_time)
{
assert(!omp_get_thread_num()); //if(omp_get_thread_num()) return;
assert_eq(active_task,FIELDS);
double additional_communication_time = MPI_Wtime()-start_time;
task_duration[FLDS_MPI_ALLREDUCE] += additional_communication_time;
}
void TimeTasks::print_cycle_times(int cycle,
double* tskdur,
const char* reduce_mode)
{
// restrict output to master process
//
if(MPIdata::get_rank()) return;
FILE* file = stdout;
{
fflush(file);
double commun[NUMBER_OF_TASKS];
double sndrcv[NUMBER_OF_TASKS];
double allred[NUMBER_OF_TASKS];
//commun[NUMBER_OF_TASKS];
commun[FIELDS] = tskdur[FLDS_COMM];
sndrcv[FIELDS] = tskdur[FLDS_MPI_SENDRECV];
allred[FIELDS] = tskdur[FLDS_MPI_ALLREDUCE];
commun[PARTICLES] = tskdur[PCLS_COMM];
sndrcv[PARTICLES] = tskdur[PCLS_MPI_SENDRECV];
allred[PARTICLES] = tskdur[PCLS_MPI_ALLREDUCE];
commun[MOMENTS] = tskdur[MOMS_COMM];
sndrcv[MOMENTS] = tskdur[MOMS_MPI_SENDRECV];
allred[MOMENTS] = tskdur[MOMS_MPI_ALLREDUCE];
sndrcv[PARTICLES] +=
tskdur[PCLS_MPI_Isend]+
tskdur[PCLS_MPI_Irecv]+
tskdur[PCLS_MPI_Wait]+
tskdur[PCLS_MPI_Cancel]+
tskdur[PCLS_MPI_Request_free]+
tskdur[PCLS_MPI_Test]+
tskdur[PCLS_MPI_Waitany];
double tskdurtot=0.;
double computtot=0.;
double communtot=0.;
double allredtot=0.;
double sndrcvtot=0.;
fprintf(file, "%s_|total comput commun task\n", reduce_mode);
assert_eq(FIELDS+2,MOMENTS);
for(int e=FIELDS; e<=MOMENTS; e++)
{
const double comput = tskdur[e]-commun[e];
tskdurtot += tskdur[e];
computtot += comput;
communtot += commun[e];
allredtot += allred[e];
sndrcvtot += sndrcv[e];
fprintf(file, "%s_|%6.3f %6.3f %6.3f %s\n",
reduce_mode,
tskdur[e],
comput,
commun[e],
//loccom[e],
get_taskname(e));
}
// report total times
fprintf(file, "%s_|%6.3f %6.3f %6.3f %s\n",
reduce_mode,
tskdurtot,
computtot,
communtot,
//loccomtot,
"[total times]");
fflush(file);
}
}
static void reduce_doubles(int len, MPI_Op mpi_op, void* inbuff, void* outbuff)
{
MPI_Allreduce(inbuff,outbuff,
len,MPI_DOUBLE,mpi_op,MPIdata::get_PicGlobalComm());
}
void TimeTasks::print_cycle_times(int cycle, const char* reduce_mode)
{
MPI_Op mpi_op;
if(!strcmp(reduce_mode,"max"))
mpi_op = MPI_MAX;
else if(!strcmp(reduce_mode,"min"))
mpi_op = MPI_MIN;
else if(!strcmp(reduce_mode,"avg"))
mpi_op = MPI_SUM;
else
invalid_value_error(reduce_mode);
// assume that only main thread is active
assert(!omp_get_thread_num());
// perform all-reduce to get max times for all processes
double reported_task_duration[NUMBER_OF_TASKS];
reduce_doubles(NUMBER_OF_TASKS, mpi_op, task_duration, reported_task_duration);
if(!strcmp(reduce_mode,"avg"))
{
const int nprocs = MPIdata::get_nprocs();
for(int i=0;i<NUMBER_OF_TASKS;i++)
{
reported_task_duration[i] /=nprocs;
}
}
print_cycle_times(cycle, reported_task_duration, reduce_mode);
}
void TimeTasks::print_cycle_times(int cycle)
{
assert(!omp_get_thread_num());
if(!MPIdata::get_rank()) fflush(stdout);
//printf0("=== times for cycle %d (main process) ===\n", cycle);
//print_cycle_times(cycle, task_duration, "main");
//printf0("=== times for cycle %d (maximum over all processes) ===\n", cycle);
//print_cycle_times(cycle, task_duration, "max");
printf0("=== times for cycle %d (averaged over all processes) ===\n", cycle);
print_cycle_times(cycle, task_duration, "avg");
//printf0("=== times for cycle %d (minimum over all processes) ===\n", cycle);
//print_cycle_times(cycle, task_duration, "min");
if(!MPIdata::get_rank()) fflush(stdout);
}
// The following three methods provide for a hack by which
// the timeTasks copies of all threads are averaged.
//
void TimeTasks::operator/=(int num)
{
assert(false); // this method is not in use.
for(int e=NONE+1;e<NUMBER_OF_TASKS;e++)
{
task_duration[e]/=num;
start_times[e]/=num;
}
}
void TimeTasks::operator+=(const TimeTasks& arg)
{
assert(false); // this method is not in use.
active_task = arg.active_task;
for(int e=NONE+1;e<NUMBER_OF_TASKS;e++)
{
assert_eq(active[e], arg.active[e]);
assert_eq(stack_depth[e], arg.stack_depth[e]);
task_duration[e]+=arg.task_duration[e];
start_times[e]+=arg.start_times[e];
}
}
void TimeTasks::operator=(const TimeTasks& arg)
{
assert(false); // this method is not in use.
active_task = arg.active_task;
for(int e=NONE+1;e<NUMBER_OF_TASKS;e++)
{
active[e] = arg.active[e];
task_duration[e]=arg.task_duration[e];
stack_depth[e] = arg.stack_depth[e];
start_times[e] = arg.start_times[e];
}
}
TimeTasks_caller_to_set_main_task_for_scope::
TimeTasks_caller_to_set_main_task_for_scope(TimeTasks::Tasks _task) :
task(_task)
{
//if(omp_get_thread_num()) return;
// assume that only one thread is active
assert(!omp_get_thread_num());
start_time = MPI_Wtime();
timeTasks.start_main_task(task);
}
TimeTasks_caller_to_set_main_task_for_scope::
~TimeTasks_caller_to_set_main_task_for_scope()
{
//if(omp_get_thread_num()) return;
// assume that only one thread is active
assert(!omp_get_thread_num());
timeTasks.end_main_task(task, start_time);
}
TimeTasks_caller_to_set_task_for_scope::
TimeTasks_caller_to_set_task_for_scope(TimeTasks::Tasks task_)
{
assert(!omp_get_thread_num()); // if(omp_get_thread_num()) return;
task = task_;
already_active = timeTasks.is_active(task);
// if the task is already active then
// we cannot tell timeTasks to start it.
if(already_active)
return;
//#pragma omp barrier
start_time = MPI_Wtime();
timeTasks.start_task(task);
}
TimeTasks_caller_to_set_task_for_scope::
~TimeTasks_caller_to_set_task_for_scope()
{
assert(!omp_get_thread_num()); // if(omp_get_thread_num()) return;
if(already_active)
{
assert(timeTasks.is_active(task));
return;
}
//#pragma omp barrier
timeTasks.end_task(task, start_time);
}
|
#include <bits/stdc++.h>
using namespace std;
/**
* Suffix Array
*
* Source: https://cp-algorithms.com/string/suffix-array.html
*/
/**
* Construction O(n log n)
*
* Idea: Order by cyclic shift
*
* String: dabbb
* 1: abbb$d abbb
* 4: b$dabb b
* 3: bb$dab bb
* 2: bbb$da bbb
* 0: dabbb$ dabbb
*
* Algorithm: We sort the n cyclic substrings of s of length 2^k for
* ceil(log n) + 1 iterations,
*
* p[i] = the index of the i-th substring (starting at i with length 2^k)
* c[i] = equivalence class to which the substring belongs
*/
vector<int> sort_cyclic_shifts(string const& s) {
int n = s.size();
const int alphabet = 256;
// 0-th iteration, sort cyclic of length 1
// counting sort
vector<int> p(n), c(n), cnt(max(alphabet, n), 0);
for (int i = 0; i < n; i++) cnt[s[i]]++;
for (int i = 1; i < alphabet; i++) cnt[i] += cnt[i - 1];
for (int i = 0; i < n; i++) p[--cnt[s[i]]] = i;
c[p[0]] = 0;
int classes = 1;
for (int i = 1; i < n; i++) {
if (s[p[i]] != s[p[i - 1]]) classes++;
c[p[i]] = classes - 1;
}
// iteration step: to compare two substrings of length 2^k starting at i and
// j we need to know (c[i], c[i+2^(k-1)]) and (c[j], c[j+2^(k-1)])
vector<int> pn(n), cn(n);
for (int h = 0; (1 << h) < n; ++h) {
for (int i = 0; i < n; i++) {
pn[i] = p[i] - (1 << h);
if (pn[i] < 0) pn[i] += n;
}
fill(cnt.begin(), cnt.begin() + classes, 0);
for (int i = 0; i < n; i++) cnt[c[pn[i]]]++;
for (int i = 1; i < classes; i++) cnt[i] += cnt[i - 1];
for (int i = n - 1; i >= 0; i--) p[--cnt[c[pn[i]]]] = pn[i];
cn[p[0]] = 0;
classes = 1;
for (int i = 1; i < n; i++) {
pair<int, int> cur = {c[p[i]], c[(p[i] + (1 << h)) % n]};
pair<int, int> prev = {c[p[i - 1]], c[(p[i - 1] + (1 << h)) % n]};
if (cur != prev) ++classes;
cn[p[i]] = classes - 1;
}
c.swap(cn);
}
return p;
}
vector<int> suffix_array_construction(string s) {
s += "$";
vector<int> sorted_shifts = sort_cyclic_shifts(s);
sorted_shifts.erase(sorted_shifts.begin());
return sorted_shifts;
}
/**
* Finding the smallest cyclic shift
*
* Sol: p[0]
*/
/**
* Finding a substring in a string
*
* Sol: binary search on prefix
*/
int main() {
auto sa = suffix_array_construction("aaba");
assert(sa == vector<int>({3, 0, 1, 2}));
return 0;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82a.cpp
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__dest.label.xml
Template File: sources-sink-82a.tmpl.cpp
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Set data pointer to the bad buffer
* GoodSource: Set data pointer to the good buffer
* Sinks: cpy
* BadSink : Copy string to data using wcscpy
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#include "std_testcase.h"
#include "CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82.h"
namespace CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t));
wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
/* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination
* buffer in various memory copying functions using a "large" source buffer. */
data = dataBadBuffer;
data[0] = L'\0'; /* null terminate */
CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82_base* baseObject = new CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82_bad;
baseObject->action(data);
delete baseObject;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t));
wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
/* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */
data = dataGoodBuffer;
data[0] = L'\0'; /* null terminate */
CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82_base* baseObject = new CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82_goodG2B;
baseObject->action(data);
delete baseObject;
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE121_Stack_Based_Buffer_Overflow__dest_wchar_t_alloca_cpy_82; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/try_chrome_dialog_win/button_layout.h"
#include "base/check_op.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/view.h"
ButtonLayout::ButtonLayout(int view_width) : view_width_(view_width) {}
ButtonLayout::~ButtonLayout() = default;
void ButtonLayout::Layout(views::View* host) {
const gfx::Size& host_size = host->bounds().size();
// Layout of the host within its parent must size it based on the |view_width|
// given to this layout manager at creation. If it happens to be different,
// the buttons will be sized and positioned based on the host's true size.
// This will result in either stretching or compressing the buttons, and may
// lead to elision of their text.
DCHECK_EQ(host_size.width(), view_width_);
// The buttons are all equal-sized.
const gfx::Size max_child_size = GetMaxChildPreferredSize(host);
gfx::Size button_size(host_size.width(), max_child_size.height());
const auto& children = host->children();
if (UseWideButtons(host_size.width(), max_child_size.width())) {
children[0]->SetBoundsRect({gfx::Point(), button_size});
if (children.size() > 1) {
int bottom_y = button_size.height() + kPaddingBetweenButtons;
children[1]->SetBoundsRect({{0, bottom_y}, button_size});
}
} else {
button_size.set_width((host_size.width() - kPaddingBetweenButtons) / 2);
// The offset of the right-side narrow button.
const int right_x = button_size.width() + kPaddingBetweenButtons;
auto right_button = children.begin();
if (children.size() > 1) {
children[0]->SetBoundsRect({gfx::Point(), button_size});
++right_button;
}
(*right_button)->SetBoundsRect({{right_x, 0}, button_size});
}
}
gfx::Size ButtonLayout::GetPreferredSize(const views::View* host) const {
const gfx::Size max_child_size = GetMaxChildPreferredSize(host);
// |view_width_| is a hard limit; the buttons will be sized and positioned to
// fill it.
if ((host->children().size() > 1) &&
UseWideButtons(view_width_, max_child_size.width())) {
// Two rows of equal height with padding between them.
return {view_width_, max_child_size.height() * 2 + kPaddingBetweenButtons};
}
// Only one button or the widest of two is sufficiently narrow, so only one
// row is needed.
return {view_width_, max_child_size.height()};
}
// static
gfx::Size ButtonLayout::GetMaxChildPreferredSize(const views::View* host) {
const auto& children = host->children();
gfx::Size max_child_size = children[0]->GetPreferredSize();
if (children.size() > 1)
max_child_size.SetToMax(children[1]->GetPreferredSize());
return max_child_size;
}
// static
bool ButtonLayout::UseWideButtons(int host_width, int max_child_width) {
return max_child_width > (host_width - kPaddingBetweenButtons) / 2;
}
|
extern int global;
/*
OUTPUT:
{
"includes": [],
"skipped_by_preprocessor": [],
"types": [{
"id": 0,
"usr": 17,
"detailed_name": "",
"short_name": "",
"kind": 0,
"declarations": [],
"bases": [],
"derived": [],
"types": [],
"funcs": [],
"vars": [],
"instances": [0],
"uses": []
}],
"funcs": [],
"vars": [{
"id": 0,
"usr": 9937941849651546906,
"detailed_name": "int global",
"short_name": "global",
"declarations": ["1:12-1:18|-1|1|1"],
"type": 0,
"uses": [],
"kind": 13,
"storage": 2
}]
}
*/
|
// ---------------------------------------------------------------------------
// IMLAB
// ---------------------------------------------------------------------------
#include "imlab/buffer_manage/buffer_manager.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <atomic>
#include <cstring>
#include <memory>
#include <random>
#include <thread> // NOLINT
#include <vector>
#define DEBUG 1
// ---------------------------------------------------------------------------------------------------
namespace {
// ---------------------------------------------------------------------------------------------------
#ifdef DEBUG
// NOLINTNEXTLINE
TEST(BufferManagerTest, AlignmentTest) {
/// New 10000 BufferManager object
/// assert in the BufferManager constructor to check to data alignment
for (size_t i = 0; i < 10000; ++i) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, FixSingle) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
std::vector<uint64_t> expected_values(1024 / sizeof(uint64_t), 123);
{
auto& page = buffer_manager.fix_page(1, true);
ASSERT_TRUE(page.get_data());
std::memcpy(page.get_data(), expected_values.data(), 1024);
buffer_manager.unfix_page(page, true);
EXPECT_EQ(std::vector<uint64_t>{1}, buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
{
std::vector<uint64_t> values(1024 / sizeof(uint64_t));
auto& page = buffer_manager.fix_page(1, false);
std::memcpy(values.data(), page.get_data(), 1024);
buffer_manager.unfix_page(page, true);
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ(std::vector<uint64_t>{1}, buffer_manager.get_lru_list());
ASSERT_EQ(expected_values, values);
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, PersistentRestart) {
auto buffer_manager = std::make_unique<imlab::BufferManager>(1024, 10, imlab::unique_ptr_aligned<char[]>(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper));
for (uint16_t segment = 0; segment < 3; ++segment) {
for (uint64_t segment_page = 0; segment_page < 10; ++segment_page) {
uint64_t page_id = (static_cast<uint64_t>(segment) << 48) | segment_page;
auto& page = buffer_manager->fix_page(page_id, true);
ASSERT_TRUE(page.get_data());
uint64_t& value = *reinterpret_cast<uint64_t*>(page.get_data());
value = segment * 10 + segment_page;
buffer_manager->unfix_page(page, true);
}
}
// Destroy the buffer manager and create a new one.
buffer_manager = std::make_unique<imlab::BufferManager>(1024, 10, imlab::unique_ptr_aligned<char[]>(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper));
for (uint16_t segment = 0; segment < 3; ++segment) {
for (uint64_t segment_page = 0; segment_page < 10; ++segment_page) {
uint64_t page_id = (static_cast<uint64_t>(segment) << 48) | segment_page;
auto& page = buffer_manager->fix_page(page_id, false);
ASSERT_TRUE(page.get_data());
uint64_t value = *reinterpret_cast<uint64_t*>(page.get_data());
buffer_manager->unfix_page(page, false);
EXPECT_EQ(segment * 10 + segment_page, value);
}
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, FIFOEvict) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
for (uint64_t i = 1; i < 11; ++i) {
auto& page = buffer_manager.fix_page(i, false);
buffer_manager.unfix_page(page, false);
}
{
std::vector<uint64_t> expected_fifo{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
EXPECT_EQ(expected_fifo, buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
{
auto& page = buffer_manager.fix_page(11, false);
buffer_manager.unfix_page(page, false);
}
{
std::vector<uint64_t> expected_fifo{2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
EXPECT_EQ(expected_fifo, buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, BufferFull) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
std::vector<imlab::BufferFrame*> pages;
pages.reserve(10);
for (uint64_t i = 1; i < 11; ++i) {
auto& page = buffer_manager.fix_page(i, false);
pages.push_back(&page);
}
EXPECT_THROW(buffer_manager.fix_page(11, false), imlab::buffer_full_error);
for (auto* page : pages) {
buffer_manager.unfix_page(*page, false);
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MoveToLRU) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
auto& fifo_page = buffer_manager.fix_page(1, false);
auto* lru_page = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(fifo_page, false);
buffer_manager.unfix_page(*lru_page, false);
EXPECT_EQ((std::vector<uint64_t>{1, 2}), buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
lru_page = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(*lru_page, false);
EXPECT_EQ(std::vector<uint64_t>{1}, buffer_manager.get_fifo_list());
EXPECT_EQ(std::vector<uint64_t>{2}, buffer_manager.get_lru_list());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, LRURefresh) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
auto* page1 = &buffer_manager.fix_page(1, false);
buffer_manager.unfix_page(*page1, false);
page1 = &buffer_manager.fix_page(1, false);
buffer_manager.unfix_page(*page1, false);
auto* page2 = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(*page2, false);
page2 = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(*page2, false);
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ((std::vector<uint64_t>{1, 2}), buffer_manager.get_lru_list());
page1 = &buffer_manager.fix_page(1, false);
buffer_manager.unfix_page(*page1, false);
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ((std::vector<uint64_t>{2, 1}), buffer_manager.get_lru_list());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadParallelFix) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager] {
ASSERT_NO_THROW(
auto& page1 = buffer_manager.fix_page(i, false);
auto& page2 = buffer_manager.fix_page(i + 4, false);
buffer_manager.unfix_page(page1, false);
buffer_manager.unfix_page(page2, false););
});
}
for (auto& thread : threads) {
thread.join();
}
auto fifo_list = buffer_manager.get_fifo_list();
std::sort(fifo_list.begin(), fifo_list.end());
std::vector<uint64_t> expected_fifo{0, 1, 2, 3, 4, 5, 6, 7};
EXPECT_EQ(expected_fifo, fifo_list);
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadExclusiveAccess) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
{
auto& page = buffer_manager.fix_page(0, true);
ASSERT_TRUE(page.get_data());
std::memset(page.get_data(), 0, 1024);
buffer_manager.unfix_page(page, true);
}
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([&buffer_manager] {
for (size_t j = 0; j < 1000; ++j) {
auto& page = buffer_manager.fix_page(0, true);
ASSERT_TRUE(page.get_data());
uint64_t& value = *reinterpret_cast<uint64_t*>(page.get_data());
++value;
buffer_manager.unfix_page(page, true);
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ(std::vector<uint64_t>{0}, buffer_manager.get_lru_list());
auto& page = buffer_manager.fix_page(0, false);
ASSERT_TRUE(page.get_data());
uint64_t value = *reinterpret_cast<uint64_t*>(page.get_data());
buffer_manager.unfix_page(page, false);
EXPECT_EQ(4000, value);
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadBufferFull) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
std::atomic<uint64_t> num_buffer_full = 0;
std::atomic<uint64_t> finished_threads = 0;
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager, &num_buffer_full, &finished_threads] {
std::vector<imlab::BufferFrame*> pages;
pages.reserve(4);
for (size_t j = 0; j < 4; ++j) {
try {
pages.push_back(&buffer_manager.fix_page(i + j * 4, false));
} catch (const imlab::buffer_full_error&) {
++num_buffer_full;
}
}
++finished_threads;
// Busy wait until all threads have finished.
while (finished_threads.load() < 4) {}
for (auto* page : pages) {
buffer_manager.unfix_page(*page, false);
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_EQ(10, buffer_manager.get_fifo_list().size());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
EXPECT_EQ(6, num_buffer_full.load());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadManyPages) {
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager] {
std::mt19937_64 engine{i}; // pseudo-random number generators
std::geometric_distribution<uint64_t> distr{0.1};
for (size_t j = 0; j < 10000; ++j) {
ASSERT_NO_THROW(
auto& page = buffer_manager.fix_page(distr(engine), false);
buffer_manager.unfix_page(page, false););
}
});
}
for (auto& thread : threads) {
thread.join();
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadReaderWriter) {
{
// Zero out all pages first
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
for (uint16_t segment = 0; segment <= 3; ++segment) {
for (uint64_t segment_page = 0; segment_page <= 100; ++segment_page) {
uint64_t page_id = (static_cast<uint64_t>(segment) << 48) | segment_page;
auto& page = buffer_manager.fix_page(page_id, true);
ASSERT_TRUE(page.get_data());
std::memset(page.get_data(), 0, 1024);
buffer_manager.unfix_page(page, true);
}
}
// Let the buffer manager be destroyed here so that the caches are
// empty before running the actual test.
}
imlab::unique_ptr_aligned<char[]> loaded_pages(static_cast<char*>(imlab::aligned_malloc(32, 1024 * 10)), &imlab::aligned_free_wrapper);
imlab::BufferManager buffer_manager(1024, 10, std::move(loaded_pages));
std::atomic<size_t> aborts = 0;
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager, &aborts] {
std::mt19937_64 engine{i};
// 5% of queries are scans.
std::bernoulli_distribution scan_distr{0.05};
// Number of pages accessed by a point query is geometrically
// distributed.
std::geometric_distribution<size_t> num_pages_distr{0.5};
// 60% of point queries are reads.
std::bernoulli_distribution reads_distr{0.6};
// Out of 20 accesses, 12 are from segment 0, 5 from segment 1,
// 2 from segment 2, and 1 from segment 3.
std::discrete_distribution<uint16_t> segment_distr{12.0, 5.0, 2.0, 1.0};
// Page accesses for point queries are uniformly distributed in
// [0, 100].
std::uniform_int_distribution<uint64_t> page_distr{0, 100};
std::vector<uint64_t> scan_sums(4);
for (size_t j = 0; j < 100; ++j) {
uint16_t segment = segment_distr(engine);
uint64_t segment_shift = static_cast<uint64_t>(segment) << 48;
if (scan_distr(engine)) {
// scan
uint64_t scan_sum = 0;
for (uint64_t segment_page = 0; segment_page <= 100; ++segment_page) {
uint64_t page_id = segment_shift | segment_page;
imlab::BufferFrame* page;
while (true) {
try {
page = &buffer_manager.fix_page(page_id, false);
break;
} catch (const imlab::buffer_full_error&) {
// Don't abort scan when the buffer is full, retry
// the current page.
}
}
ASSERT_TRUE(page->get_data());
uint64_t value = *reinterpret_cast<uint64_t*>(page->get_data());
scan_sum += value;
buffer_manager.unfix_page(*page, false);
}
EXPECT_GE(scan_sum, scan_sums[segment]);
scan_sums[segment] = scan_sum;
} else {
// point query
auto num_pages = num_pages_distr(engine) + 1;
// For point queries all accesses but the last are always
// reads. Only the last is potentially a write. Also,
// all pages but the last are held for the entire duration
// of the query.
std::vector<imlab::BufferFrame*> pages;
auto unfix_pages = [&] {
for (auto it = pages.rbegin(); it != pages.rend(); ++it) {
auto& page = **it;
buffer_manager.unfix_page(page, false);
}
pages.clear();
};
for (size_t page_number = 0; page_number < num_pages - 1; ++page_number) {
uint64_t segment_page = page_distr(engine);
uint64_t page_id = segment_shift | segment_page;
imlab::BufferFrame* page;
try {
page = &buffer_manager.fix_page(page_id, false);
} catch (const imlab::buffer_full_error&) {
// Abort query when buffer is full.
++aborts;
goto abort;
}
pages.push_back(page);
}
// Unfix all pages before accessing the last one
// (potentially exclusively) to avoid deadlocks.
unfix_pages();
{
uint64_t segment_page = page_distr(engine);
uint64_t page_id = segment_shift | segment_page;
if (reads_distr(engine)) {
// read
imlab::BufferFrame* page;
try {
page = &buffer_manager.fix_page(page_id, false);
} catch (const imlab::buffer_full_error&) {
++aborts;
goto abort;
}
buffer_manager.unfix_page(*page, false);
} else {
// write
imlab::BufferFrame* page;
try {
page = &buffer_manager.fix_page(page_id, true);
} catch (const imlab::buffer_full_error&) {
++aborts;
goto abort;
}
ASSERT_TRUE(page->get_data());
auto& value = *reinterpret_cast<uint64_t*>(page->get_data());
++value;
buffer_manager.unfix_page(*page, true);
}
}
abort:
unfix_pages();
}
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_LT(aborts.load(), 20);
}
#endif
// ---------------------------------------------------------------------------------------------------
} // namespace
// ---------------------------------------------------------------------------------------------------
|
/*
A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.
For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n" ("s ubstitutio n")
"sub4u4" ("sub stit u tion")
"12" ("substitution")
"su3i1u2on" ("su bst i t u ti on")
"substitution" (no substrings replaced)
The following are not valid abbreviations:
"s55n" ("s ubsti tutio n", the replaced substrings are adjacent)
"s010n" (has leading zeros)
"s0ubstitution" (replaces an empty substring)
Given a string word and an abbreviation abbr, return whether the string matches the given abbreviation.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: word = "internationalization", abbr = "i12iz4n"
Output: true
Explanation: The word "internationalization" can be abbreviated as "i12iz4n" ("i nternational iz atio n").
Example 2:
Input: word = "apple", abbr = "a2e"
Output: false
Explanation: The word "apple" cannot be abbreviated as "a2e".
Constraints:
1 <= word.length <= 20
word consists of only lowercase English letters.
1 <= abbr.length <= 10
abbr consists of lowercase English letters and digits.
All the integers in abbr will fit in a 32-bit integer.
*/
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int w_len = word.size(), a_len = abbr.size();
int s1 = 0, s2 = 0;
while( s1 < w_len && s2 < a_len )
{
if (abbr[s2] >= 'a' && abbr[s2] <= 'z' )
{
if ( word[s1++] != abbr[s2++] )
return false;
}
else if ( abbr[s2] == '0' )
{
return false;
}
else {
int len = 0;
while( s2 < a_len && (abbr[s2] >= '0' && abbr[s2] <= '9') )
{
len = len * 10 + (abbr[s2] - '0');
s2++;
}
s1 += len;
}
}
return s1 == w_len && s2 == a_len;
}
};
// Two pointers
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int i = 0, j = 0;
while(i < word.size() && j < abbr.size())
{
if ( isdigit(abbr[j]) )
{
if ( abbr[j] == '0' )
return false;
int len = 0;
while( j < abbr.size() && isdigit(abbr[j]) )
{
len = len * 10 + (abbr[j]-'0');
j++;
}
i += len;
}
else if ( word[i++] != abbr[j++] )
{
return false;
}
}
return i == word.size() && j == abbr.size();
}
};
int main()
{
Solution s;
string word = "internationalization", abbr = "i12iz4n";
s.validWordAbbreviation(word,abbr);
}
|
//========= Copyright Valve Corporation, All rights reserved. ============//
#include "stdafx.h"
#include "msgprotobuf.h"
#include "smartptr.h"
#include "rtime.h"
#include "gcsdk/gcreportprinter.h"
#include <winsock.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
namespace GCSDK
{
GCConVar cv_webapi_result_size_limit( "webapi_result_size_limit", "50000000" );
GCConVar cv_webapi_serialize_threads( "webapi_serialize_threads", "1", 0, "Switch for serializing webAPI responses on threads" );
static GCConVar webapi_account_tracking( "webapi_account_tracking", "1", "Controls whether or not account tracking stats are collected for web api usage" );
static GCConVar webapi_kill_switch( "webapi_kill_switch", "0", "When set to zero this will block no web api calls, when set to 1 this will block all web api except those sent by steam. To block steam, use the webapi_enable_steam_<priority> controls" );
static GCConVar webapi_kill_switch_error_response( "webapi_kill_switch_error_response", "1", "Determines if a response should be sent when the kill switch kills a web api request" );
static GCConVar webapi_rate_limit_calls_per_min( "webapi_rate_limit_calls_per_min", "600", "Determines how many messages can be sent from an account via the web api per minute. <0 disables this limiting" );
static GCConVar webapi_rate_limit_mb_per_min( "webapi_rate_limit_mb_per_min", "20", "Determines how many megabytes of data can be sent to an account via the web api per minute. <0 disables this limiting" );
static GCConVar webapi_elevated_rate_limit_calls_per_min( "webapi_elevated_rate_limit_calls_per_min", "-1", "Determines how many messages can be sent from an account via the web api per minute for elevated accounts. <0 disables this limiting" );
static GCConVar webapi_elevated_rate_limit_mb_per_min( "webapi_elevated_rate_limit_mb_per_min", "-1", "Determines how many megabytes of data can be sent to an account via the web api per minute for elevated accounts. <0 disables this limiting" );
static GCConVar webapi_ip_rate_limit( "webapi_ip_rate_limit", "1", "Controls whether or not we rate limit based upon IPs or just accounts" );
//-----------------------------------------------------------------------------
// CWebAPIAccountTracker
//
// Utility that tracks web api calls based upon accesses made by various users
//-----------------------------------------------------------------------------
class CWebAPIAccountTracker
{
public:
//called when a web api request is made to track the call. A return value of true indicates that it should be allowed,
//false indicates it should be blocked
bool TrackUser( AccountID_t nID, uint32 nIP );
//called once the size of the response is known and will track bandwidth and caller attributed to the provided function
void TrackFunction( AccountID_t nID, uint32 nIP, const char* pszFunction, uint32 nResponseSize );
//called to reset all permissions to default
void ResetAccountPermissions();
//called to associate a permission level with an account
void SetAccountPermission( AccountID_t nID, EWebAPIAccountLevel eLevel );
//completely resets accumulated stats
void ResetStats();
//resets just the profile stats
void ResetProfileStats();
//different caller report filters that can be used
enum EDumpCaller
{
eDumpCaller_All,
eDumpCaller_Blocked,
eDumpCaller_Status,
eDumpCaller_Calls,
};
//different reports that can be provided
void DumpTotalCallers( EDumpCaller eFilter, const char* pszFunctionFilter = NULL ) const;
void DumpTotalIPs( EDumpCaller eFilter, const char* pszFunctionFilter = NULL ) const;
void DumpCaller( AccountID_t nID ) const;
void DumpIP( uint32 nIP ) const;
void DumpFunctions() const;
void DumpProfile( bool bAllTime ) const;
void DumpSteamServers() const;
//given a steam server name, this will return the identifier of that server
uint32 GetSteamServerID( const char* pszServer );
//for steam level requests, we have a priority provided, and to track stats separately we break them up to different account IDs instead of just zero
static const uint32 k_nSteamIP_High = 2;
static const uint32 k_nSteamIP_Normal = 1;
static const uint32 k_nSteamIP_Low = 0;
private:
//called to get the starting time of this rate interval
RTime32 GetRateIntervalStart( AccountID_t nCaller ) const;
struct SCallerStats
{
SCallerStats() :
m_nBlockedCalls( 0 ),
m_eLevel( eWebAPIAccountLevel_RateLimited )
{
ResetRateInterval( 0 );
}
void ResetRateInterval( RTime32 nStart )
{
m_nRateIntervalStartTime = nStart;
m_nRateIntervalCalls = 0;
m_nRateIntervalBytes = 0;
}
//the most recent rate interval that we received a message from the user (used to expire old counts)
RTime32 m_nRateIntervalStartTime;
//how many messages have been sent within this rate interval (used for rate limiting)
uint32 m_nRateIntervalCalls;
//how many bytes have been sent for this account during this interval
uint32 m_nRateIntervalBytes;
//total number of blocked calls
uint32 m_nBlockedCalls;
//flags associated with this caller, used to block/whitelist, etc
EWebAPIAccountLevel m_eLevel;
};
struct SFunctionStats
{
//track the number of calls and bandwidth. The profile versions are separate and used for displaying profiles over a window
uint32 m_nTotalCalls;
uint32 m_nProfileCalls;
uint32 m_nMaxBytes;
uint32 m_nProfileMaxBytes;
uint64 m_nTotalBytes;
uint64 m_nProfileBytes;
//a map of who has called us, which consists of the caller account and IP as the key
struct SCaller
{
bool operator==( const SCaller& rhs ) const { return m_nAccountID == rhs.m_nAccountID && m_nIP == rhs.m_nIP; }
AccountID_t m_nAccountID;
uint32 m_nIP;
};
struct SCalls
{
uint32 m_nCalls;
uint64 m_nBytes;
};
CUtlHashMapLarge< SCaller, SCalls > m_Callers;
};
//a structure used to simplify reporting so a vector can just be built of these, and then provided to the report function which will handle sorting it and displaying
struct SReportRow
{
SReportRow( const char* pszFunction, uint32 nCalls, uint64 nSize ) :
m_pszFunction( pszFunction ),
m_nCalls( nCalls ),
m_nSize( nSize )
{}
const char* m_pszFunction;
uint32 m_nCalls;
uint64 m_nSize;
};
struct SSteamServer
{
CUtlString m_sName;
uint32 m_nID;
};
//called to find an existing user, or create one if not in the list already
SCallerStats* CreateAccountUser( AccountID_t nID, RTime32 nRateIntervalStart );
SCallerStats* CreateIPUser( uint32 nIP, RTime32 nRateIntervalStart );
//called to print a report of the provided report rows as either an ID list or a function list. This will re-sort the provided vector
static void PrintReport( const CUtlVector< SReportRow >& vec );
//how many seconds are in a rate interval
static const uint32 knRateIntervalTimeS = 60;
CUtlHashMapLarge< AccountID_t, SCallerStats > m_AccountCallers;
CUtlHashMapLarge< uint32, SCallerStats > m_IPCallers;
CUtlHashMapLarge< uintp, SFunctionStats* > m_Functions;
CUtlHashMapLarge< const char*, SSteamServer*, CaseSensitiveStrEquals, MurmurHash3ConstCharPtr > m_SteamServers;
CJobTime m_ProfileTime;
};
//our global profiler
static CWebAPIAccountTracker g_WebAPIAccountTracker;
void WebAPIAccount_ResetAllPermissions()
{
g_WebAPIAccountTracker.ResetAccountPermissions();
}
void WebAPIAccount_SetPermission( AccountID_t nID, EWebAPIAccountLevel eLevel )
{
g_WebAPIAccountTracker.SetAccountPermission( nID, eLevel );
}
bool WebAPIAccount_BTrackUserAndValidate( AccountID_t nID, uint32 unIP )
{
return g_WebAPIAccountTracker.TrackUser( nID, unIP );
}
RTime32 CWebAPIAccountTracker::GetRateIntervalStart( AccountID_t nCaller ) const
{
//we shift the time by the account ID so that all users don't wrap at the same time which can cause a temporary surge in web API requests
RTime32 curTime = CRTime::RTime32TimeCur() + ( nCaller % knRateIntervalTimeS );
return curTime - ( curTime % knRateIntervalTimeS );
}
CWebAPIAccountTracker::SCallerStats* CWebAPIAccountTracker::CreateAccountUser( AccountID_t nID, RTime32 nRateIntervalStart )
{
int nIndex = m_AccountCallers.Find( nID );
if( nIndex == m_AccountCallers.InvalidIndex() )
{
nIndex = m_AccountCallers.Insert( nID );
SCallerStats& caller = m_AccountCallers[ nIndex ];
caller.m_nRateIntervalStartTime = nRateIntervalStart;
//account ID is always unrestricted!
if( nID == 0 )
caller.m_eLevel = eWebAPIAccountLevel_Unlimited;
}
return &m_AccountCallers[ nIndex ];
}
CWebAPIAccountTracker::SCallerStats* CWebAPIAccountTracker::CreateIPUser( uint32 nIP, RTime32 nRateIntervalStart )
{
int nIndex = m_IPCallers.Find( nIP );
if( nIndex == m_IPCallers.InvalidIndex() )
{
nIndex = m_IPCallers.Insert( nIP );
SCallerStats& caller = m_IPCallers[ nIndex ];
caller.m_nRateIntervalStartTime = nRateIntervalStart;
}
return &m_IPCallers[ nIndex ];
}
uint32 CWebAPIAccountTracker::GetSteamServerID( const char* pszServer )
{
int nIndex = m_SteamServers.Find( pszServer );
if( nIndex == m_SteamServers.InvalidIndex() )
{
SSteamServer* pServer = new SSteamServer;
pServer->m_sName = pszServer;
pServer->m_nID = m_SteamServers.Count();
m_SteamServers.Insert( pServer->m_sName, pServer );
return pServer->m_nID;
}
return m_SteamServers[ nIndex ]->m_nID;
}
void CWebAPIAccountTracker::DumpSteamServers() const
{
CGCReportPrinter rp;
rp.AddStringColumn( "ID" );
rp.AddStringColumn( "Server" );
FOR_EACH_MAP_FAST( m_SteamServers, nServer )
{
const uint32 nID = m_SteamServers[ nServer ]->m_nID;
rp.StrValue( CFmtStr( "%u.%u.%u.%u", iptod( nID << 8 ) ) );
rp.StrValue( m_SteamServers[ nServer ]->m_sName );
rp.CommitRow();
}
rp.SortReport( "ID", false );
rp.PrintReport( SPEW_CONSOLE );
}
//determines what the resulting account level access should be based upon the access rights of the IP address and the account
static EWebAPIAccountLevel DetermineAccessLevel( EWebAPIAccountLevel eAccount, EWebAPIAccountLevel eIP )
{
//unrestricted users should always be allowed, regardless of the IP range that they are making requests from, same with unlimited IP addresses
if( ( eAccount == eWebAPIAccountLevel_Unlimited ) || ( eIP == eWebAPIAccountLevel_Unlimited ) )
return eWebAPIAccountLevel_Unlimited;
//otherwise, if either is blocked, then block
if( ( eAccount == eWebAPIAccountLevel_Blocked ) || ( eIP == eWebAPIAccountLevel_Blocked ) )
return eWebAPIAccountLevel_Blocked;
//now we are dealing with default case versus elevated. Elevated wins over default
if( ( eAccount == eWebAPIAccountLevel_Elevated ) || ( eIP == eWebAPIAccountLevel_Elevated ) )
return eWebAPIAccountLevel_Elevated;
//default
return eWebAPIAccountLevel_RateLimited;
}
bool CWebAPIAccountTracker::TrackUser( AccountID_t nID, uint32 nIP )
{
if( !webapi_account_tracking.GetBool() )
return true;
//first off update their aggregate caller stats
{
//what is our current time, and at what time did this rate interval start
const RTime32 rateIntervalStart = GetRateIntervalStart( nID );
//see if this account is completely blocked
SCallerStats* pAccountCaller = CreateAccountUser( nID, rateIntervalStart );
SCallerStats* pIPCaller = CreateIPUser( nIP, rateIntervalStart );
//determine what our policy should be based upon the access level of the IP and the user
EWebAPIAccountLevel eAccessLevel = DetermineAccessLevel( pAccountCaller->m_eLevel, pIPCaller->m_eLevel );
//if we are blocked, just bail now
if( eAccessLevel == eWebAPIAccountLevel_Blocked )
{
pAccountCaller->m_nBlockedCalls++;
pIPCaller->m_nBlockedCalls++;
return false;
}
//reset the rate interval tracking
if( pAccountCaller->m_nRateIntervalStartTime < rateIntervalStart )
pAccountCaller->ResetRateInterval( rateIntervalStart );
if( pIPCaller->m_nRateIntervalStartTime < rateIntervalStart )
pIPCaller->ResetRateInterval( rateIntervalStart );
//now handle rate limiting
if( ( eAccessLevel == eWebAPIAccountLevel_RateLimited ) || ( eAccessLevel == eWebAPIAccountLevel_Elevated ) )
{
//determine the rate we want to limit
int32 nCallsPerMin = ( eAccessLevel == eWebAPIAccountLevel_RateLimited ) ? webapi_rate_limit_calls_per_min.GetInt() : webapi_elevated_rate_limit_calls_per_min.GetInt();
int32 nBytesPerMin = ( ( eAccessLevel == eWebAPIAccountLevel_RateLimited ) ? webapi_rate_limit_mb_per_min.GetInt() : webapi_elevated_rate_limit_mb_per_min.GetInt() ) * 1024 * 1024;
//see if this account is rate limited
if( ( eAccessLevel == eWebAPIAccountLevel_RateLimited ) )
{
bool bAllow = true;
//see if we are being limited based upon call rate limiting (tracking based upon ip and account) Note that
//we don't return until we've dones stat tracking for both so the reports are accurate and capture it at both levels
if( ( nCallsPerMin >= 0 && pAccountCaller->m_nRateIntervalCalls >= ( uint32 )nCallsPerMin ) ||
( nBytesPerMin >= 0 && pAccountCaller->m_nRateIntervalBytes >= ( uint32 )nBytesPerMin ) )
{
pAccountCaller->m_nBlockedCalls++;
bAllow = false;
}
if( webapi_ip_rate_limit.GetBool() )
{
if( ( nCallsPerMin >= 0 && pIPCaller->m_nRateIntervalCalls >= ( uint32 )nCallsPerMin ) ||
( nBytesPerMin >= 0 && pIPCaller->m_nRateIntervalBytes >= ( uint32 )nBytesPerMin ) )
{
pIPCaller->m_nBlockedCalls++;
bAllow = false;
}
}
if( !bAllow )
return false;
}
}
}
return true;
}
void CWebAPIAccountTracker::TrackFunction( AccountID_t nID, uint32 nIP, const char* pszFunction, uint32 nResponseSize )
{
if( !webapi_account_tracking.GetBool() )
return;
//update the bytes for that user
{
int nCallerIndex = m_AccountCallers.Find( nID );
if( nCallerIndex != m_AccountCallers.InvalidIndex() )
{
SCallerStats& caller = m_AccountCallers[ nCallerIndex ];
caller.m_nRateIntervalBytes += nResponseSize;
caller.m_nRateIntervalCalls++;
}
}
//update the bytes for that user and for their IP
{
int nCallerIndex = m_IPCallers.Find( nIP );
if( nCallerIndex != m_IPCallers.InvalidIndex() )
{
SCallerStats& caller = m_IPCallers[ nCallerIndex ];
caller.m_nRateIntervalBytes += nResponseSize;
caller.m_nRateIntervalCalls++;
}
}
//now update the function specific stats
{
int nFunctionIndex = m_Functions.Find( ( uintp )pszFunction );
if( nFunctionIndex == m_Functions.InvalidIndex() )
{
SFunctionStats* pNewStats = new SFunctionStats;
pNewStats->m_nTotalCalls = 0;
pNewStats->m_nProfileCalls = 0;
pNewStats->m_nTotalBytes = 0;
pNewStats->m_nProfileBytes = 0;
pNewStats->m_nMaxBytes = 0;
pNewStats->m_nProfileMaxBytes = 0;
nFunctionIndex = m_Functions.Insert( ( uintp )pszFunction, pNewStats );
}
//update our stats
SFunctionStats& function = *m_Functions[ nFunctionIndex ];
function.m_nTotalCalls++;
function.m_nProfileCalls++;
function.m_nTotalBytes += nResponseSize;
function.m_nProfileBytes += nResponseSize;
function.m_nMaxBytes = MAX( function.m_nMaxBytes, nResponseSize );
function.m_nProfileMaxBytes = MAX( function.m_nProfileMaxBytes, nResponseSize );
//update caller stats
{
struct SFunctionStats::SCaller caller;
caller.m_nAccountID = nID;
caller.m_nIP = nIP;
int nCallerIndex = function.m_Callers.Find( caller );
if( nCallerIndex == function.m_Callers.InvalidIndex() )
{
nCallerIndex = function.m_Callers.Insert( caller );
function.m_Callers[ nCallerIndex ].m_nCalls = 1;
function.m_Callers[ nCallerIndex ].m_nBytes = nResponseSize;
}
else
{
function.m_Callers[ nCallerIndex ].m_nCalls++;
function.m_Callers[ nCallerIndex ].m_nBytes += nResponseSize;
}
}
}
}
void CWebAPIAccountTracker::SetAccountPermission( AccountID_t nID, EWebAPIAccountLevel eLevel )
{
SCallerStats* pCaller = CreateAccountUser( nID, GetRateIntervalStart( nID ) );
pCaller->m_eLevel = eLevel;
}
void CWebAPIAccountTracker::ResetAccountPermissions()
{
FOR_EACH_MAP_FAST( m_AccountCallers, nCaller )
{
m_AccountCallers[ nCaller ].m_eLevel = eWebAPIAccountLevel_RateLimited;
}
FOR_EACH_MAP_FAST( m_IPCallers, nCaller )
{
m_IPCallers[ nCaller ].m_eLevel = eWebAPIAccountLevel_RateLimited;
}
}
void CWebAPIAccountTracker::ResetStats()
{
FOR_EACH_MAP_FAST( m_AccountCallers, nCaller )
{
m_AccountCallers[ nCaller ].ResetRateInterval( GetRateIntervalStart( m_AccountCallers.Key( nCaller ) ) );
m_AccountCallers[ nCaller ].m_nBlockedCalls = 0;
}
FOR_EACH_MAP_FAST( m_IPCallers, nCaller )
{
m_IPCallers[ nCaller ].ResetRateInterval( GetRateIntervalStart( m_IPCallers.Key( nCaller ) ) );
m_IPCallers[ nCaller ].m_nBlockedCalls = 0;
}
m_Functions.PurgeAndDeleteElements();
}
void CWebAPIAccountTracker::ResetProfileStats()
{
FOR_EACH_MAP_FAST( m_Functions, nFunction )
{
m_Functions[ nFunction ]->m_nProfileCalls = 0;
m_Functions[ nFunction ]->m_nProfileBytes = 0;
m_Functions[ nFunction ]->m_nProfileMaxBytes = 0;
}
m_ProfileTime.SetToJobTime();
}
static const int k_cSteamIDRenderedMaxLen = 36;
//-----------------------------------------------------------------------------
// Purpose: Renders the steam ID to a buffer with an admin console link. NOTE: for convenience of
// calling code, this code returns a pointer to a static buffer and is NOT thread-safe.
// Output: buffer with rendered Steam ID
//-----------------------------------------------------------------------------
static const char * CSteamID_RenderLink( const CSteamID & steamID )
{
// longest length of returned string is k_cBufLen
// <link cmd="steamid64 %llu"></link> => 30 + 20 == 50
// 50 + k_cSteamIDRenderedMaxLen + 1
const int k_cBufLen = 50 + k_cSteamIDRenderedMaxLen + 1;
const int k_cBufs = 4; // # of static bufs to use (so people can compose output with multiple calls to RenderLink() )
static char rgchBuf[k_cBufs][k_cBufLen];
static int nBuf = 0;
char * pchBuf = rgchBuf[nBuf]; // get pointer to current static buf
nBuf++; // use next buffer for next call to this method
nBuf %= k_cBufs;
Q_snprintf( pchBuf, k_cBufLen, "<link cmd=\"steamid64 %llu\">%s</link>", steamID.ConvertToUint64(), steamID.Render() );
return pchBuf;
}
//-----------------------------------------------------------------------------
// Purpose: Renders the passed-in steam ID to a buffer with admin console link. NOTE: for convenience
// of calling code, this code returns a pointer to a static buffer and is NOT thread-safe.
// Input: 64-bit representation of Steam ID to render
// Output: buffer with rendered Steam ID link
//-----------------------------------------------------------------------------
static const char * CSteamID_RenderLink( uint64 ulSteamID )
{
CSteamID steamID( ulSteamID );
return CSteamID_RenderLink( steamID );
}
void CWebAPIAccountTracker::DumpCaller( AccountID_t nID ) const
{
const CSteamID steamID = GGCInterface()->ConstructSteamIDForClient( nID );
//cache the account name here so we don't yield while we have indices
CUtlString sPersona = GGCBase()->YieldingGetPersonaName( steamID, "[Unknown]" );
//dump high level user stats
int nCallerIndex = m_AccountCallers.Find( nID );
if( nCallerIndex == m_AccountCallers.InvalidIndex() )
{
EG_MSG( SPEW_CONSOLE, "User %u not found in any web api calls\n", nID );
return;
}
//a map of IP addresses that have been used by this account
CUtlHashMapLarge< uint32, SFunctionStats::SCalls > ipCalls;
//now each function they called
uint64 nTotalBytes = 0;
uint32 nTotalCalls = 0;
CUtlVector< SReportRow > vFuncs;
FOR_EACH_MAP_FAST( m_Functions, nFunc )
{
//add up how many calls they made to this function across all IPs
uint64 nFnBytes = 0;
uint32 nFnCalls = 0;
FOR_EACH_MAP_FAST( m_Functions[ nFunc ]->m_Callers, nCaller )
{
const CWebAPIAccountTracker::SFunctionStats::SCaller& caller = m_Functions[ nFunc ]->m_Callers.Key( nCaller );
if( caller.m_nAccountID == nID )
{
const CWebAPIAccountTracker::SFunctionStats::SCalls& calls = m_Functions[ nFunc ]->m_Callers[ nCaller ];
nFnBytes += calls.m_nBytes;
nFnCalls += calls.m_nCalls;
int nIPIndex = ipCalls.Find( caller.m_nIP );
if( nIPIndex == ipCalls.InvalidIndex() )
{
SFunctionStats::SCalls toAdd;
toAdd.m_nBytes = calls.m_nBytes;
toAdd.m_nCalls = calls.m_nCalls;
ipCalls.Insert( caller.m_nIP, toAdd );
}
else
{
ipCalls[ nIPIndex ].m_nBytes += calls.m_nBytes;
ipCalls[ nIPIndex ].m_nBytes += calls.m_nCalls;
}
}
}
if( nFnCalls > 0 )
{
vFuncs.AddToTail( SReportRow( ( const char* )m_Functions.Key( nFunc ), nFnCalls, nFnBytes ) );
}
nTotalBytes += nFnBytes;
nTotalCalls += nFnCalls;
}
const SCallerStats& caller = m_AccountCallers[ nCallerIndex ];
EG_MSG( SPEW_CONSOLE, "---------------------------------------------------\n" );
EG_MSG( SPEW_CONSOLE, "User %s: \"%s\"\n", CSteamID_RenderLink( steamID ), sPersona.String() );
double fTotalMB = nTotalBytes / ( 1024.0 * 1024.0 );
double fMBPerHour = fTotalMB / ( GGCBase()->GetGCUpTime() / 3600.0 );
double fCallsPerHour = nTotalCalls / ( GGCBase()->GetGCUpTime() / 3600.0 );
EG_MSG( SPEW_CONSOLE, "\tAccess: %u, Total Calls: %u, Blocked calls: %u, Total: %.2fMB, MB/h: %.2f, Calls/h: %.0f\n", caller.m_eLevel, nTotalCalls, caller.m_nBlockedCalls, fTotalMB, fMBPerHour, fCallsPerHour );
//don't let someone accidentally change Steam's access!
if( nID != 0 )
{
if( caller.m_eLevel == eWebAPIAccountLevel_RateLimited )
{
EG_MSG( SPEW_CONSOLE, "\t<link cmd=\"webapi_account_set_access %u %d\">[Block Account]</link>", nID, eWebAPIAccountLevel_Blocked );
EG_MSG( SPEW_CONSOLE, "\t<link cmd=\"webapi_account_set_access %u %d\">[Elevate Account]</link>\n", nID, eWebAPIAccountLevel_Elevated );
}
else if( caller.m_eLevel == eWebAPIAccountLevel_Blocked )
{
EG_MSG( SPEW_CONSOLE, "\t<link cmd=\"webapi_account_set_access %u %d\">[Unblock Account]</link>\n", nID, eWebAPIAccountLevel_RateLimited );
}
else if( caller.m_eLevel == eWebAPIAccountLevel_Elevated )
{
EG_MSG( SPEW_CONSOLE, "\t<link cmd=\"webapi_account_set_access %u %d\">[Demote Account]</link>\n", nID, eWebAPIAccountLevel_RateLimited );
}
}
//print a report of the IP addresses that they are calling from
{
CGCReportPrinter rp;
rp.AddStringColumn( "IP" );
rp.AddIntColumn( "Calls", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "MB", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
FOR_EACH_MAP_FAST( ipCalls, nIP )
{
rp.StrValue( CFmtStr( "%u.%u.%u.%u", iptod( ipCalls.Key( nIP ) ) ), CFmtStr( "webapi_account_dump_ip %u", ipCalls.Key( nIP ) ) );
rp.IntValue( ipCalls[ nIP ].m_nCalls );
rp.IntValue( ipCalls[ nIP ].m_nBytes );
rp.CommitRow();
}
rp.SortReport( "MB" );
rp.PrintReport( SPEW_CONSOLE );
}
//and print a report of all the functions that they've called
PrintReport( vFuncs );
}
void CWebAPIAccountTracker::DumpIP( uint32 nIP ) const
{
//dump high level user stats
int nCallerIndex = m_IPCallers.Find( nIP );
if( nCallerIndex == m_IPCallers.InvalidIndex() )
{
EG_MSG( SPEW_CONSOLE, "IP %u not found in any web api calls\n", nIP );
return;
}
//a map of IP addresses that have been used by this account
CUtlHashMapLarge< AccountID_t, SFunctionStats::SCalls > accountCalls;
//now each function they called
uint64 nTotalBytes = 0;
uint32 nTotalCalls = 0;
CUtlVector< SReportRow > vFuncs;
FOR_EACH_MAP_FAST( m_Functions, nFunc )
{
//add up how many calls they made to this function across all IPs
uint64 nFnBytes = 0;
uint32 nFnCalls = 0;
FOR_EACH_MAP_FAST( m_Functions[ nFunc ]->m_Callers, nCaller )
{
const CWebAPIAccountTracker::SFunctionStats::SCaller& caller = m_Functions[ nFunc ]->m_Callers.Key( nCaller );
if( caller.m_nIP == nIP )
{
const CWebAPIAccountTracker::SFunctionStats::SCalls& calls = m_Functions[ nFunc ]->m_Callers[ nCaller ];
nFnBytes += calls.m_nBytes;
nFnCalls += calls.m_nCalls;
int nAccountIndex = accountCalls.Find( caller.m_nAccountID );
if( nAccountIndex == accountCalls.InvalidIndex() )
{
SFunctionStats::SCalls toAdd;
toAdd.m_nBytes = calls.m_nBytes;
toAdd.m_nCalls = calls.m_nCalls;
accountCalls.Insert( caller.m_nAccountID, toAdd );
GGCBase()->PreloadPersonaName( GGCInterface()->ConstructSteamIDForClient( caller.m_nAccountID ) );
}
else
{
accountCalls[ nAccountIndex ].m_nBytes += calls.m_nBytes;
accountCalls[ nAccountIndex ].m_nBytes += calls.m_nCalls;
}
}
}
if( nFnCalls > 0 )
{
vFuncs.AddToTail( SReportRow( ( const char* )m_Functions.Key( nFunc ), nFnCalls, nFnBytes ) );
}
nTotalBytes += nFnBytes;
nTotalCalls += nFnCalls;
}
const SCallerStats& caller = m_IPCallers[ nCallerIndex ];
EG_MSG( SPEW_CONSOLE, "---------------------------------------------------\n" );
EG_MSG( SPEW_CONSOLE, "IP %u.%u.%u.%u\n", iptod( nIP ) );
double fTotalMB = nTotalBytes / ( 1024.0 * 1024.0 );
double fMBPerHour = fTotalMB / ( GGCBase()->GetGCUpTime() / 3600.0 );
double fCallsPerHour = nTotalCalls / ( GGCBase()->GetGCUpTime() / 3600.0 );
EG_MSG( SPEW_CONSOLE, "\tAccess: %u, Total Calls: %u, Blocked calls: %u, Total: %.2fMB, MB/h: %.2f, Calls/h: %.0f\n", caller.m_eLevel, nTotalCalls, caller.m_nBlockedCalls, fTotalMB, fMBPerHour, fCallsPerHour );
//print a report of the accounts that they are calling from
{
CGCReportPrinter rp;
rp.AddSteamIDColumn( "Account" );
rp.AddStringColumn( "Persona" );
rp.AddIntColumn( "Calls", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "MB", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
FOR_EACH_MAP_FAST( accountCalls, nAccount )
{
CSteamID steamID = GGCInterface()->ConstructSteamIDForClient( accountCalls.Key( nAccount ) );
rp.SteamIDValue( steamID, CFmtStr( "webapi_account_dump_caller %u", steamID.GetAccountID() ) );
rp.StrValue( GGCBase()->YieldingGetPersonaName( steamID, "[unknown]" ), CFmtStr( "webapi_account_dump_caller %u", steamID.GetAccountID() ) );
rp.IntValue( accountCalls[ nAccount ].m_nCalls );
rp.IntValue( accountCalls[ nAccount ].m_nBytes );
rp.CommitRow();
}
rp.SortReport( "MB" );
rp.PrintReport( SPEW_CONSOLE );
}
//and print a report of all the functions that they've called
PrintReport( vFuncs );
}
struct SCallerReportStats
{
uint32 m_nFunctions;
uint32 m_nCalls;
uint64 m_nBytes;
};
void CWebAPIAccountTracker::DumpTotalCallers( EDumpCaller eFilter, const char* pszFunctionFilter ) const
{
//accumulate stats for each unique caller
CUtlHashMapLarge< AccountID_t, SCallerReportStats > mapCallers;
FOR_EACH_MAP_FAST( m_Functions, nCurrFunction )
{
//handle filtering out functions we don't care about
const char* pszFunctionName = ( const char* )m_Functions.Key( nCurrFunction );
if( pszFunctionFilter && ( V_stristr( pszFunctionName, pszFunctionFilter ) == NULL ) )
continue;
const SFunctionStats& function = *m_Functions[ nCurrFunction ];
FOR_EACH_MAP_FAST( function.m_Callers, nCurrCaller )
{
const AccountID_t key = function.m_Callers.Key( nCurrCaller ).m_nAccountID;
//add this account
int nStatIndex = mapCallers.Find( key );
if( nStatIndex == mapCallers.InvalidIndex() )
{
SCallerReportStats stats;
stats.m_nFunctions = 0;
stats.m_nCalls = 0;
stats.m_nBytes = 0;
nStatIndex = mapCallers.Insert( key, stats );
GGCBase()->PreloadPersonaName( GGCInterface()->ConstructSteamIDForClient( key ) );
}
mapCallers[ nStatIndex ].m_nFunctions += 1;
mapCallers[ nStatIndex ].m_nCalls += function.m_Callers[ nCurrCaller ].m_nCalls;
mapCallers[ nStatIndex ].m_nBytes += function.m_Callers[ nCurrCaller ].m_nBytes;
}
}
CGCReportPrinter rp;
rp.AddStringColumn( "Account" );
rp.AddIntColumn( "Calls", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "MB", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
rp.AddIntColumn( "Blocked", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "Access", CGCReportPrinter::eSummary_None );
rp.AddIntColumn( "APIs", CGCReportPrinter::eSummary_None );
rp.AddIntColumn( "MB/h", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
rp.AddIntColumn( "Calls/h", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "KB/c", CGCReportPrinter::eSummary_None );
rp.AddStringColumn( "UserName" );
const double fUpTimeHrs = MAX( GGCBase()->GetGCUpTime() / 3600.0, 0.01 );
//now show the report
FOR_EACH_MAP_FAST( m_AccountCallers, nCurrCaller )
{
//apply filters to our results
if( ( eFilter == eDumpCaller_Blocked ) && ( m_AccountCallers[ nCurrCaller ].m_nBlockedCalls == 0 ) )
continue;
if( ( eFilter == eDumpCaller_Status ) && ( m_AccountCallers[ nCurrCaller ].m_eLevel == eWebAPIAccountLevel_RateLimited ) )
continue;
const AccountID_t accountID = m_AccountCallers.Key( nCurrCaller );
const SCallerReportStats* pStats = NULL;
int nCollectedStats = mapCallers.Find( accountID );
if( nCollectedStats != mapCallers.InvalidIndex() )
{
pStats = &mapCallers[ nCollectedStats ];
}
//filter out users that didn't make any calls if appropriate
if( ( eFilter == eDumpCaller_Calls ) && ( !pStats || ( pStats->m_nCalls == 0 ) ) )
continue;
const CSteamID steamID( GGCInterface()->ConstructSteamIDForClient( accountID ) );
rp.StrValue( steamID.Render() , CFmtStr( "webapi_account_dump_caller %u", accountID ) );
rp.IntValue( ( pStats ) ? pStats->m_nCalls : 0 );
rp.IntValue( ( pStats ) ? pStats->m_nBytes : 0 );
rp.IntValue( m_AccountCallers[ nCurrCaller ].m_nBlockedCalls );
rp.IntValue( m_AccountCallers[ nCurrCaller ].m_eLevel );
rp.IntValue( ( pStats ) ? pStats->m_nFunctions : 0 );
rp.IntValue( ( int64 )( ( ( pStats ) ? pStats->m_nBytes : 0 ) / fUpTimeHrs ) );
rp.IntValue( ( int64 )( ( ( pStats ) ? pStats->m_nCalls : 0 ) / fUpTimeHrs ) );
rp.IntValue( ( pStats && pStats->m_nCalls > 0 ) ? ( pStats->m_nBytes / pStats->m_nCalls ) / 1024 : 0 );
rp.StrValue( GGCBase()->YieldingGetPersonaName( steamID, "[unknown]" ) );
rp.CommitRow();
}
const char* pszSort = "MB/h";
if( eFilter == eDumpCaller_Blocked )
pszSort = "Blocked";
else if( eFilter == eDumpCaller_Status )
pszSort = "Access";
rp.SortReport( pszSort );
rp.PrintReport( SPEW_CONSOLE );
}
void CWebAPIAccountTracker::DumpTotalIPs( EDumpCaller eFilter, const char* pszFunctionFilter ) const
{
//accumulate stats for each unique caller
CUtlHashMapLarge< uint32, SCallerReportStats > mapIPs;
FOR_EACH_MAP_FAST( m_Functions, nCurrFunction )
{
//handle filtering out functions we don't care about
const char* pszFunctionName = ( const char* )m_Functions.Key( nCurrFunction );
if( pszFunctionFilter && ( V_stristr( pszFunctionName, pszFunctionFilter ) == NULL ) )
continue;
const SFunctionStats& function = *m_Functions[ nCurrFunction ];
FOR_EACH_MAP_FAST( function.m_Callers, nCurrCaller )
{
const uint32 key = function.m_Callers.Key( nCurrCaller ).m_nIP;
//add this account
int nStatIndex = mapIPs.Find( key );
if( nStatIndex == mapIPs.InvalidIndex() )
{
SCallerReportStats stats;
stats.m_nFunctions = 0;
stats.m_nCalls = 0;
stats.m_nBytes = 0;
nStatIndex = mapIPs.Insert( key, stats );
}
mapIPs[ nStatIndex ].m_nFunctions += 1;
mapIPs[ nStatIndex ].m_nCalls += function.m_Callers[ nCurrCaller ].m_nCalls;
mapIPs[ nStatIndex ].m_nBytes += function.m_Callers[ nCurrCaller ].m_nBytes;
}
}
CGCReportPrinter rp;
rp.AddStringColumn( "IP" );
rp.AddIntColumn( "Calls", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "MB", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
rp.AddIntColumn( "Blocked", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "Access", CGCReportPrinter::eSummary_None );
rp.AddIntColumn( "APIs", CGCReportPrinter::eSummary_None );
rp.AddIntColumn( "MB/h", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
rp.AddIntColumn( "Calls/h", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "KB/c", CGCReportPrinter::eSummary_None );
const double fUpTimeHrs = MAX( GGCBase()->GetGCUpTime() / 3600.0, 0.01 );
//now show the report
FOR_EACH_MAP_FAST( m_IPCallers, nCurrCaller )
{
//apply filters to our results
if( ( eFilter == eDumpCaller_Blocked ) && ( m_IPCallers[ nCurrCaller ].m_nBlockedCalls == 0 ) )
continue;
if( ( eFilter == eDumpCaller_Status ) && ( m_IPCallers[ nCurrCaller ].m_eLevel == eWebAPIAccountLevel_RateLimited ) )
continue;
const uint32 nIP = m_IPCallers.Key( nCurrCaller );
const SCallerReportStats* pStats = NULL;
int nCollectedStats = mapIPs.Find( nIP );
if( nCollectedStats != mapIPs.InvalidIndex() )
{
pStats = &mapIPs[ nCollectedStats ];
}
//filter out users that didn't make any calls if appropriate
if( ( eFilter == eDumpCaller_Calls ) && ( !pStats || ( pStats->m_nCalls == 0 ) ) )
continue;
rp.StrValue( CFmtStr( "%u.%u.%u.%u", iptod( nIP ) ), CFmtStr( "webapi_account_dump_ip %u", nIP ) );
rp.IntValue( ( pStats ) ? pStats->m_nCalls : 0 );
rp.IntValue( ( pStats ) ? pStats->m_nBytes : 0 );
rp.IntValue( m_IPCallers[ nCurrCaller ].m_nBlockedCalls );
rp.IntValue( m_IPCallers[ nCurrCaller ].m_eLevel );
rp.IntValue( ( pStats ) ? pStats->m_nFunctions : 0 );
rp.IntValue( ( int64 )( ( ( pStats ) ? pStats->m_nBytes : 0 ) / fUpTimeHrs ) );
rp.IntValue( ( int64 )( ( ( pStats ) ? pStats->m_nCalls : 0 ) / fUpTimeHrs ) );
rp.IntValue( ( pStats && pStats->m_nCalls > 0 ) ? ( pStats->m_nBytes / pStats->m_nCalls ) / 1024 : 0 );
rp.CommitRow();
}
const char* pszSort = "MB/h";
if( eFilter == eDumpCaller_Blocked )
pszSort = "Blocked";
else if( eFilter == eDumpCaller_Status )
pszSort = "Access";
rp.SortReport( pszSort );
rp.PrintReport( SPEW_CONSOLE );
}
void CWebAPIAccountTracker::DumpFunctions() const
{
CUtlVector< SReportRow > vFuncs;
vFuncs.EnsureCapacity( m_Functions.Count() );
FOR_EACH_MAP_FAST( m_Functions, i )
{
vFuncs.AddToTail( SReportRow( ( const char* )m_Functions.Key( i ), m_Functions[ i ]->m_nTotalCalls, m_Functions[ i ]->m_nTotalBytes ) );
}
PrintReport( vFuncs );
}
void CWebAPIAccountTracker::DumpProfile( bool bAllTime ) const
{
//accumulate totals so we can do percentage
uint32 nTotalCalls = 0;
uint64 nTotalBytes = 0;
FOR_EACH_MAP_FAST( m_Functions, nFunction )
{
if( bAllTime )
{
nTotalCalls += m_Functions[ nFunction ]->m_nTotalCalls;
nTotalBytes += m_Functions[ nFunction ]->m_nTotalBytes;
}
else
{
nTotalCalls += m_Functions[ nFunction ]->m_nProfileCalls;
nTotalBytes += m_Functions[ nFunction ]->m_nProfileBytes;
}
}
//determine how much time we are covering, and come up with a scale to normalize the values
uint64 nSampleMicroS = ( bAllTime ) ? ( uint64 )GGCBase()->GetGCUpTime() * 1000000 : m_ProfileTime.CServerMicroSecsPassed();
double fToPS = ( nSampleMicroS > 0 ) ? 1000000.0 / ( double )nSampleMicroS : 1.0;
EmitInfo( SPEW_CONSOLE, SPEW_ALWAYS, LOG_ALWAYS, "Web API Profile: Sampled %.2f seconds\n", nSampleMicroS / ( 1000.0 * 1000.0 ) );
CGCReportPrinter rp;
rp.AddStringColumn( "Web API Name" );
rp.AddIntColumn( "MB", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
rp.AddFloatColumn( "%", CGCReportPrinter::eSummary_Total, 1 );
rp.AddFloatColumn( "KBPS", CGCReportPrinter::eSummary_Total, 1 );
rp.AddIntColumn( "Calls", CGCReportPrinter::eSummary_Total );
rp.AddFloatColumn( "%", CGCReportPrinter::eSummary_Total, 1 );
rp.AddFloatColumn( "CallsPS", CGCReportPrinter::eSummary_Total, 1 );
rp.AddIntColumn( "MaxKB", CGCReportPrinter::eSummary_Max );
FOR_EACH_MAP_FAST( m_Functions, nFunction )
{
const SFunctionStats* pFunc = m_Functions[ nFunction ];
uint32 nCalls = ( bAllTime ) ? pFunc->m_nTotalCalls : pFunc->m_nProfileCalls;
uint32 nMax = ( bAllTime ) ? pFunc->m_nMaxBytes : pFunc->m_nProfileMaxBytes;
uint64 nBytes = ( bAllTime ) ? pFunc->m_nTotalBytes : pFunc->m_nProfileBytes;
rp.StrValue( ( const char* )m_Functions.Key( nFunction ) );
rp.IntValue( nBytes );
rp.FloatValue( ( 100.0 * nBytes ) / nTotalBytes );
rp.FloatValue( ( nBytes / 1024.0 ) * fToPS );
rp.IntValue( nCalls );
rp.FloatValue( ( 100.0 * nCalls ) / nTotalCalls );
rp.FloatValue( nCalls * fToPS );
rp.IntValue( nMax / 1024 );
rp.CommitRow();
}
rp.SortReport( "KBPS" );
rp.PrintReport( SPEW_CONSOLE );
}
void CWebAPIAccountTracker::PrintReport( const CUtlVector< SReportRow >& vec )
{
CGCReportPrinter rp;
//now print it out based upon the type
rp.AddStringColumn( "Function" );
rp.AddIntColumn( "Calls", CGCReportPrinter::eSummary_Total );
rp.AddIntColumn( "MB", CGCReportPrinter::eSummary_Total, CGCReportPrinter::eIntDisplay_Memory_MB );
rp.AddFloatColumn( "Calls/h", CGCReportPrinter::eSummary_Total, 0 );
rp.AddFloatColumn( "MB/h", CGCReportPrinter::eSummary_Total );
const double fUpTimeHrs = MAX( GGCBase()->GetGCUpTime() / 3600.0, 0.01 );
for( int i = 0; i < vec.Count(); i++ )
{
rp.StrValue( vec[ i ].m_pszFunction, CFmtStr( "webapi_account_dump_function_callers %s", vec[ i ].m_pszFunction ) );
rp.IntValue( vec[ i ].m_nCalls );
rp.IntValue( vec[ i ].m_nSize );
rp.FloatValue( vec[ i ].m_nCalls / fUpTimeHrs );
rp.FloatValue( ( vec[ i ].m_nSize / ( 1024.0 * 1024.0 ) ) / fUpTimeHrs );
rp.CommitRow();
}
rp.SortReport( "MB/h" );
rp.PrintReport( SPEW_CONSOLE );
}
GC_CON_COMMAND( webapi_account_dump_steam_servers, "Dumps the ID listings of the various steam servers encoded in the IP address of Steam requests" )
{
g_WebAPIAccountTracker.DumpSteamServers();
}
GC_CON_COMMAND( webapi_account_dump_callers, "Dumps the most frequent callers of web api's for the current run of the GC" )
{
g_WebAPIAccountTracker.DumpTotalCallers( CWebAPIAccountTracker::eDumpCaller_Calls );
}
GC_CON_COMMAND( webapi_account_dump_ips, "Dumps the most frequent ip callers of web api's for the current run of the GC" )
{
g_WebAPIAccountTracker.DumpTotalIPs( CWebAPIAccountTracker::eDumpCaller_Calls );
}
GC_CON_COMMAND( webapi_account_dump_blocked_callers, "Dumps the callers that have been blocked and how many calls have been blocked" )
{
g_WebAPIAccountTracker.DumpTotalCallers( CWebAPIAccountTracker::eDumpCaller_Blocked );
}
GC_CON_COMMAND( webapi_account_dump_caller_access, "Dumps the access rights of any caller that is not the default rate limiting" )
{
g_WebAPIAccountTracker.DumpTotalCallers( CWebAPIAccountTracker::eDumpCaller_Status );
}
GC_CON_COMMAND( webapi_account_dump_functions, "Dumps the most frequently called web api functions" )
{
g_WebAPIAccountTracker.DumpFunctions();
}
GC_CON_COMMAND_PARAMS( webapi_account_dump_function_callers, 1, "<function name> - Dumps the most frequent callers of functions that match the provided substring" )
{
g_WebAPIAccountTracker.DumpTotalCallers( CWebAPIAccountTracker::eDumpCaller_Calls, args[ 1 ] );
}
GC_CON_COMMAND_PARAMS( webapi_account_dump_caller, 1, "<caller account> - Dumps the functions that the provided account ID has been calling the most" )
{
g_WebAPIAccountTracker.DumpCaller( ( AccountID_t )V_atoui64( args[ 1 ] ) );
}
GC_CON_COMMAND_PARAMS( webapi_account_dump_ip, 1, "<ip> - Dumps the functions that the provided ip has been calling the most" )
{
g_WebAPIAccountTracker.DumpIP( ( AccountID_t )V_atoui64( args[ 1 ] ) );
}
GC_CON_COMMAND( webapi_account_reset_stats, "Forces a reset of all stats collected for web api account stats" )
{
g_WebAPIAccountTracker.ResetStats();
}
//utility class for dumping out the profile results after time has expired
static void DumpWebAPIProfile()
{
g_WebAPIAccountTracker.DumpProfile( false );
}
GC_CON_COMMAND_PARAMS( webapi_profile, 1, "<seconds to profile> Turns on web api profiling for N seconds and dumps the results" )
{
float fSeconds = MAX( 1.0f, atof( args[ 1 ] ) );
g_WebAPIAccountTracker.ResetProfileStats();
static CGlobalScheduledFunction s_DumpProfile;
s_DumpProfile.ScheduleMS( DumpWebAPIProfile, fSeconds * 1000.0f );
}
//console commands to control web API profiling
GC_CON_COMMAND( webapi_profile_reset, "Turns on web api profiling" )
{
g_WebAPIAccountTracker.ResetProfileStats();
}
GC_CON_COMMAND( webapi_profile_dump, "Displays stats collected while web api profiling was enabled" )
{
g_WebAPIAccountTracker.DumpProfile( false );
}
GC_CON_COMMAND( webapi_profile_dump_total, "Displays stats collected while web api profiling was enabled" )
{
g_WebAPIAccountTracker.DumpProfile( true );
}
//-----------------------------------------------------------------------------
// Purpose: Sends a message and waits for a response
// Input: steamIDTarget - The entity this message is going to
// msgOut - The message to send
// nTimeoutSec - Number of seconds to wait for a response
// pMsgIn - Pointer to the message that will contain the response
// eMsg - The type of message the response should be
// Returns: True is the response was received, false otherwise. The contents
// of pMsgIn will be valid only if the function returns true.
//-----------------------------------------------------------------------------
bool CGCJob::BYldSendMessageAndGetReply( CSteamID &steamIDTarget, CGCMsgBase &msgOut, uint nTimeoutSec, CGCMsgBase *pMsgIn, MsgType_t eMsg )
{
IMsgNetPacket *pNetPacket = NULL;
if ( !BYldSendMessageAndGetReply( steamIDTarget, msgOut, nTimeoutSec, &pNetPacket ) )
return false;
pMsgIn->SetPacket( pNetPacket );
if ( pMsgIn->Hdr().m_eMsg != eMsg )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Sends a message and waits for a response
// Input: steamIDTarget - The entity this message is going to
// msgOut - The message to send
// nTimeoutSec - Number of seconds to wait for a response
// ppNetPackets - Pointer to a IMsgNetPacket pointer which will contain
// the response
// Returns: True is the response was received, false otherwise. *ppNetPacket
// will point to a valid packet only if the function returns true.
//-----------------------------------------------------------------------------
bool CGCJob::BYldSendMessageAndGetReply( CSteamID &steamIDTarget, CGCMsgBase &msgOut, uint nTimeoutSec, IMsgNetPacket **ppNetPacket )
{
msgOut.ExpectingReply( GetJobID() );
if ( !m_pGC->BSendGCMsgToClient( steamIDTarget, msgOut ) )
return false;
SetJobTimeout( nTimeoutSec );
return BYieldingWaitForMsg( ppNetPacket );
}
//-----------------------------------------------------------------------------
// Purpose: BYldSendMessageAndGetReply, ProtoBuf edition
//-----------------------------------------------------------------------------
bool CGCJob::BYldSendMessageAndGetReply( CSteamID &steamIDTarget, CProtoBufMsgBase &msgOut, uint nTimeoutSec, CProtoBufMsgBase *pMsgIn, MsgType_t eMsg )
{
IMsgNetPacket *pNetPacket = NULL;
if ( !BYldSendMessageAndGetReply( steamIDTarget, msgOut, nTimeoutSec, &pNetPacket ) )
return false;
pMsgIn->InitFromPacket( pNetPacket );
if ( pMsgIn->GetEMsg() != eMsg )
return false;
return true;
}
bool CGCJob::BYldSendMessageAndGetReply( CSteamID &steamIDTarget, CProtoBufMsgBase &msgOut, uint nTimeoutSec, IMsgNetPacket **ppNetPacket )
{
msgOut.ExpectingReply( GetJobID() );
if ( !m_pGC->BSendGCMsgToClient( steamIDTarget, msgOut ) )
return false;
SetJobTimeout( nTimeoutSec );
return BYieldingWaitForMsg( ppNetPacket );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CGCWGJob::CGCWGJob( CGCBase *pGCBase )
: CGCJob( pGCBase ),
m_steamID( k_steamIDNil ),
m_pWebApiFunc( NULL )
{
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CGCWGJob::~CGCWGJob()
{
}
//-----------------------------------------------------------------------------
// Purpose: Receive a k_EMsgWGRequest and manage keyvalues serialization/deserialization
//-----------------------------------------------------------------------------
bool CGCWGJob::BYieldingRunGCJob( IMsgNetPacket * pNetPacket )
{
CGCMsg<MsgGCWGRequest_t> msg( pNetPacket );
CUtlString strRequestName;
KeyValuesAD pkvRequest( "request" );
KeyValuesAD pkvResponse( "response" );
m_steamID = CSteamID( msg.Body().m_ulSteamID );
msg.BReadStr( &strRequestName );
//deserialize KV
m_bufRequest.Clear();
m_bufRequest.Put( msg.PubReadCur(), msg.Body().m_cubKeyValues );
KVPacker packer;
if ( !packer.ReadAsBinary( pkvRequest, m_bufRequest ) )
{
AssertMsg( false, "Failed to deserialize key values from WG request" );
CGCWGJobMgr::SendErrorMessage( msg, "Failed to deserialize key values from WG request", k_EResultInvalidParam );
return false;
}
if( !BVerifyParams( msg, pkvRequest, m_pWebApiFunc ) )
return false;
bool bRet = BYieldingRunJobFromRequest( pkvRequest, pkvResponse );
// request failed, set success for wg
if ( pkvResponse->IsEmpty( "success" ) )
{
pkvResponse->SetInt( "success", bRet ? k_EResultOK : k_EResultFail );
}
// send response msg
CGCWGJobMgr::SendResponse( msg, pkvResponse, bRet );
return true;
}
bool CGCWGJob::BVerifyParams( const CGCMsg<MsgGCWGRequest_t> & msg, KeyValues *pkvRequest, const WebApiFunc_t * pWebApiFunc )
{
// we've found the function; now validate the call
for ( int i = 0; i < Q_ARRAYSIZE( pWebApiFunc->m_rgParams ); i++ )
{
if ( !pWebApiFunc->m_rgParams[i].m_pchParam )
break;
// just simple validation for now; make sure the key exists
if ( !pWebApiFunc->m_rgParams[i].m_bOptional && !pkvRequest->FindKey( pWebApiFunc->m_rgParams[i].m_pchParam ) )
{
CGCWGJobMgr::SendErrorMessage( msg,
CFmtStr( "Error: Missing parameter '%s' from web request '%s'\n", pWebApiFunc->m_rgParams[i].m_pchParam, pWebApiFunc->m_pchRequestName ),
k_EResultInvalidParam );
EmitWarning( SPEW_GC, 2, "Error: Missing parameter '%s' from web request '%s'\n", pWebApiFunc->m_rgParams[i].m_pchParam, pWebApiFunc->m_pchRequestName );
return false;
}
}
return true;
}
void CGCWGJob::SetErrorMessage( KeyValues *pkvErr, const char *pchErrorMsg, int32 nResult )
{
CGCWGJobMgr::SetErrorMessage( pkvErr, pchErrorMsg, nResult );
}
//-----------------------------------------------------------------------------
// CGCJobVerifySession - A job that asks steam if a given user is still connected
// and cleans up the session if the user is gone
//-----------------------------------------------------------------------------
bool CGCJobVerifySession::BYieldingRunGCJob()
{
if ( !m_pGC->BYieldingLockSteamID( m_steamID, __FILE__, __LINE__ ) )
return false;
m_pGC->YieldingRequestSession( m_steamID );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CWebAPIJob::CWebAPIJob( CGCBase *pGC, EWebAPIOutputFormat eDefaultOutputFormat )
: CGCJob( pGC ), m_eDefaultOutputFormat( eDefaultOutputFormat )
{
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CWebAPIJob::~CWebAPIJob()
{
}
//-----------------------------------------------------------------------------
// Called to handle converting a web api response to a serialized result and free the object as well on a background thread
class CEmitWebAPIData
{
public:
CEmitWebAPIData( CMsgHttpRequest* pRequest) : m_bResult( false ), m_Request( pRequest ) {}
//inputs
CHTTPRequest m_Request;
//outputs
CHTTPResponse m_Response;
std::string m_sSerializedResponse;
bool m_bResult;
};
//the worker thread function that is responsible for serializing the response from web api values to a text buffer, freeing the web api value tree, and serializing the message to a protobuf for
//direct sending. If this function fails (a false response value) the message will not be serialized
static void ThreadedEmitFormattedOutputWrapperAndFreeResponse( CWebAPIResponse *pResponse, CEmitWebAPIData* pEmitData, EWebAPIOutputFormat eDefaultFormat, size_t unMaxResultSize )
{
// parse the output type that we want the result to be in
EWebAPIOutputFormat eOutputFormat = eDefaultFormat;
const char *pszParamOutput = pEmitData->m_Request.GetGETParamString( "format", NULL );
if ( !pszParamOutput )
pszParamOutput = pEmitData->m_Request.GetPOSTParamString( "format", NULL );
if ( pszParamOutput )
{
if ( Q_stricmp( pszParamOutput, "xml" ) == 0 )
eOutputFormat = k_EWebAPIOutputFormat_XML;
else if ( Q_stricmp( pszParamOutput, "vdf" ) == 0 )
eOutputFormat = k_EWebAPIOutputFormat_VDF;
else if ( Q_stricmp( pszParamOutput, "json" ) == 0 )
eOutputFormat = k_EWebAPIOutputFormat_JSON;
}
pEmitData->m_bResult = pResponse->BEmitFormattedOutput( eOutputFormat, *( pEmitData->m_Response.GetBodyBuffer() ), unMaxResultSize );
delete pResponse;
//update the response code on the output (can probably be done elsewhere), but must be done before we pack the message below
switch( eOutputFormat )
{
case k_EWebAPIOutputFormat_JSON:
pEmitData->m_Response.SetResponseHeaderValue( "content-type", "application/json; charset=UTF-8" );
break;
case k_EWebAPIOutputFormat_XML:
pEmitData->m_Response.SetResponseHeaderValue( "content-type", "text/xml; charset=UTF-8" );
break;
case k_EWebAPIOutputFormat_VDF:
pEmitData->m_Response.SetResponseHeaderValue( "content-type", "text/vdf; charset=UTF-8" );
break;
default:
break;
}
//if successful, we can go ahead and convert this all the way into a completely serialized form for sending over the wire
if( pEmitData->m_bResult )
{
CMsgHttpResponse msgResponse;
pEmitData->m_Response.SerializeIntoProtoBuf( msgResponse );
msgResponse.SerializeToString( &pEmitData->m_sSerializedResponse );
}
}
//called to respond to a web api request with the specified response value
static void WebAPIRespondToRequest( const char* pszName, uint32 nSenderIP, const CHTTPResponse& response, const CProtoBufMsg< CMsgWebAPIRequest >& msg )
{
VPROF_BUDGET( "WebAPI - sending result", VPROF_BUDGETGROUP_STEAM );
CProtoBufMsg<CMsgHttpResponse> msgResponse( k_EGCMsgWebAPIJobRequestHttpResponse, msg );
response.SerializeIntoProtoBuf( msgResponse.Body() );
GGCBase()->BReplyToMessage( msgResponse, msg );
//track this message in the web API response
g_WebAPIAccountTracker.TrackFunction( msg.Body().api_key().account_id(), nSenderIP, pszName, msgResponse.Body().body().size() );
}
//responses to the web api message with an error code
static void WebAPIRespondWithError( const char* pszName, uint32 nSenderIP, const CProtoBufMsg< CMsgWebAPIRequest >& msg, EHTTPStatusCode statusCode )
{
CHTTPResponse response;
response.SetStatusCode( statusCode );
WebAPIRespondToRequest( pszName, nSenderIP, response, msg );
}
//parses an IP address out of the provided string. This will be the last IP address in the list
static uint32 ParseIPAddrFromForwardHeader( const char* pszHeader )
{
//find the last comma in the string, our IP address follows that
const char* pszStart = V_strrchr( pszHeader, ',' );
//if no match, then we just have the ip address, otherwise advance past the comma
if( !pszStart )
pszStart = pszHeader;
else
pszStart++;
//skip leading spaces
while( V_isspace( *pszStart ) )
pszStart++;
return ntohl( inet_addr( pszStart ) );
}
//-----------------------------------------------------------------------------
// Purpose: Receive a k_EMsgWebAPIJobRequest and manage serialization/deserialization to
// web request/response objects
//-----------------------------------------------------------------------------
bool CWebAPIJob::BYieldingRunJobFromMsg( IMsgNetPacket * pNetPacket )
{
VPROF_BUDGET( "WebAPI", VPROF_BUDGETGROUP_STEAM );
CProtoBufMsg<CMsgWebAPIRequest> msg( pNetPacket );
//make sure all the required parameters were present
bool bMsgParsedOK = msg.Body().has_api_key()
&& msg.Body().has_interface_name()
&& msg.Body().has_method_name()
&& msg.Body().has_request()
&& msg.Body().has_version();
if( !bMsgParsedOK )
{
WebAPIRespondWithError( GetName(), 0, msg, k_EHTTPStatusCode400BadRequest );
return true;
}
//determine the account that sent this request
const AccountID_t nSenderAccountID = msg.Body().api_key().account_id();
uint32 nSenderIP = 0;
//if this isn't a system request, try and identify the IP address of the sender so we can rate limit accordingly
if( nSenderAccountID != 0 )
{
const int nNumHeaders = msg.Body().request().headers_size();
for( int nHeader = 0; nHeader < nNumHeaders; nHeader++ )
{
if( strcmp( msg.Body().request().headers( nHeader ).name().c_str(), "X-Forwarded-For" ) != 0 )
continue;
//this is our IP address
nSenderIP = ParseIPAddrFromForwardHeader( msg.Body().request().headers( nHeader ).value().c_str() );
}
//see if we have the kill switch turned on
if( webapi_kill_switch.GetBool() )
{
if( webapi_kill_switch_error_response.GetBool() )
WebAPIRespondWithError( GetName(), nSenderIP, msg, k_EHTTPStatusCode503ServiceUnavailable );
return true;
}
}
else
{
// !FIXME! DOTAMERGE
// //determine the priority of this steam request
// uint32 nPriority;
// nSenderIP = GetSteamRequestIPAddress( msg.Body().request(), nPriority );
// //and allow for a kill switch based upon this priority
// if( ( ( nPriority == CWebAPIAccountTracker::k_nSteamIP_Low ) && !webapi_enable_steam_low.GetBool() ) ||
// ( ( nPriority == CWebAPIAccountTracker::k_nSteamIP_Normal ) && !webapi_enable_steam_normal.GetBool() ) ||
// ( ( nPriority == CWebAPIAccountTracker::k_nSteamIP_High ) && !webapi_enable_steam_high.GetBool() ) )
// {
// if( webapi_kill_switch_error_response.GetBool() )
// WebAPIRespondWithError( GetName(), 0, msg );
// return true;
// }
}
//track stats for this account, and handle rate limiting
if( !g_WebAPIAccountTracker.TrackUser( nSenderAccountID, nSenderIP ) )
{
if( webapi_kill_switch_error_response.GetBool() )
WebAPIRespondWithError( GetName(), nSenderIP, msg, k_EHTTPStatusCode429TooManyRequests );
return true;
}
//allocate the data that we'll use to fill out the request and send it to the background thread for work
CPlainAutoPtr< CEmitWebAPIData > pEmitData( new CEmitWebAPIData( const_cast< CMsgHttpRequest* >( &msg.Body().request() ) ) );
CHTTPRequest& request = pEmitData->m_Request;
CHTTPResponse& response = pEmitData->m_Response;
{
VPROF_BUDGET( "WebAPI - Prepare msg", VPROF_BUDGETGROUP_STEAM );
m_webAPIKey.DeserializeFromProtoBuf( msg.Body().api_key() );
}
CPlainAutoPtr< CWebAPIResponse > pwebAPIResponse( new CWebAPIResponse() );
{
VPROF_BUDGET( "WebAPI - Process msg", VPROF_BUDGETGROUP_STEAM );
if( !BYieldingRunJobFromAPIRequest( msg.Body().interface_name().c_str(), msg.Body().method_name().c_str(), msg.Body().version(), &request, &response, pwebAPIResponse.Get() ) )
{
//error executing our job
WebAPIRespondWithError( GetName(), nSenderIP, msg, k_EHTTPStatusCode500InternalServerError );
return false;
}
}
// !FIXME! DOTAMERGE
// //see if they want to re-route this request
// if( m_nRerouteRequest >= 0 )
// {
// if( ( uint32 )m_nRerouteRequest == m_pGC->GetGCDirIndex() )
// {
// AssertMsg( false, "Error: WebAPI %s attempting to re-route a web api message to itself (%d)", GetName(), m_nRerouteRequest );
// }
// else
// {
// //route to the other GC and discard this message
// CProtoBufMsg< CMsgGCMsgWebAPIJobRequestForwardResponse > msgRoute( k_EGCMsgWebAPIJobRequestForwardResponse );
// msgRoute.Body().set_dir_index( m_nRerouteRequest );
// m_pGC->BReplyToMessage( msgRoute, msg );
// }
// return true;
// }
VPROF_BUDGET( "WebAPI - Emitting result", VPROF_BUDGETGROUP_STEAM );
response.SetStatusCode( pwebAPIResponse->GetStatusCode() );
response.SetExpirationHeaderDeltaFromNow( pwebAPIResponse->GetExpirationSeconds() );
if( pwebAPIResponse->GetLastModified() )
response.SetHeaderTimeValue( "last-modified", pwebAPIResponse->GetLastModified() );
// if we aren't allowed to have a message body on this, simply send the result back now
if( !CHTTPUtil::BStatusCodeAllowsBody( pwebAPIResponse->GetStatusCode() ) )
{
AssertMsg( pwebAPIResponse->GetRootValue() == NULL, "Response HTTP status code %d doesn't allow a body, but one was present", pwebAPIResponse->GetStatusCode() );
//since we didn't have a body to serialize, we need to handle sending just the response
WebAPIRespondToRequest( GetName(), nSenderIP, response, msg );
return true;
}
//let the job convert the formatting and free our response for us (quite costly). Note that we detach the web API response since this job will free it
bool bThreadFuncSucceeded = BYieldingWaitForThreadFunc( CreateFunctor( ThreadedEmitFormattedOutputWrapperAndFreeResponse, pwebAPIResponse.Detach(), pEmitData.Get(), m_eDefaultOutputFormat, (size_t)cv_webapi_result_size_limit.GetInt() ) );
//if we called the function successfully and had a valid result, just send back the preserialized body
if( bThreadFuncSucceeded && pEmitData->m_bResult )
{
m_pGC->BReplyToMessageWithPreSerializedBody( k_EGCMsgWebAPIJobRequestHttpResponse, msg, ( const byte* )pEmitData->m_sSerializedResponse.c_str(), pEmitData->m_sSerializedResponse.size() );
g_WebAPIAccountTracker.TrackFunction( nSenderAccountID, nSenderIP, GetName(), pEmitData->m_sSerializedResponse.size() );
}
else
{
//we failed to generate a response, see if we ran out of space
if( response.GetBodyBuffer()->TellMaxPut() > cv_webapi_result_size_limit.GetInt() )
{
// !FIXME! DOTAMERGE
//CGCAlertInfo alert( "WebAPIResponseSize", "WebAPI request %s failed to emit because it exceeded %d characters", request.GetURL(), cv_webapi_result_size_limit.GetInt() );
//
//switch( request.GetEHTTPMethod() )
//{
//case k_EHTTPMethodGET:
// {
// const uint32 nNumParams = request.GetGETParamCount();
// for( uint32 nParam = 0; nParam < nNumParams; nParam++ )
// {
// alert.AddExtendedInfoLine( "%s=%s", request.GetGETParamName( nParam ), request.GetGETParamValue( nParam ) );
// }
// }
// break;
//case k_EHTTPMethodPOST:
// {
// const uint32 nNumParams = request.GetPOSTParamCount();
// for( uint32 nParam = 0; nParam < nNumParams; nParam++ )
// {
// alert.AddExtendedInfoLine( "%s=%s", request.GetPOSTParamName( nParam ), request.GetPOSTParamValue( nParam ) );
// }
// }
// break;
//}
//
//GGCBase()->PostAlert( alert );
GGCBase()->PostAlert( k_EAlertTypeInfo, false, CFmtStr( "WebAPI request %s failed to emit because it exceeded %d characters", request.GetURL(), cv_webapi_result_size_limit.GetInt() ) );
}
else
{
EG_WARNING( SPEW_GC, "WebAPI %s - request %s failed to emit for unknown reason\n", GetName(), request.GetURL() );
}
//make sure that they get an error code back
WebAPIRespondWithError( GetName(), nSenderIP, msg, k_EHTTPStatusCode500InternalServerError );
}
return true;
}
void CWebAPIJob::AddLocalizedString( CWebAPIValues *pOutDefn, const char *pchFieldName, const char *pchKeyName, ELanguage eLang, bool bReturnTokenIfNotFound )
{
// NULL keys we just skip
if( !pchKeyName )
return;
const char *pchValue;
if( eLang == k_Lang_None )
{
pchValue = pchKeyName;
}
else
{
pchValue = GGCBase()->LocalizeToken( pchKeyName, eLang, bReturnTokenIfNotFound );
}
if( pchValue )
{
pOutDefn->CreateChildObject( pchFieldName )->SetStringValue( pchValue );
}
}
//-----------------------------------------------------------------------------
// Purpose: A wrapper to call BEmitFormattedOutput and pass out a return value
// since functors don't make return values available.
//-----------------------------------------------------------------------------
/*static*/ void CWebAPIJob::ThreadedEmitFormattedOutputWrapper( CWebAPIResponse *pResponse, EWebAPIOutputFormat eFormat, CUtlBuffer *poutputBuffer, size_t unMaxResultSize, bool *pbResult )
{
*pbResult = pResponse->BEmitFormattedOutput( eFormat, *poutputBuffer, unMaxResultSize );
}
} // namespace GCSDK
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Jason Shipman
//
// 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.
#pragma once
#include <CpperoMQ/Common.hpp>
#include <algorithm>
#include <cstring>
namespace CpperoMQ
{
class Socket
{
friend class IncomingMessage;
friend class OutgoingMessage;
public:
Socket() = delete;
virtual ~Socket();
Socket(const Socket& other) = delete;
Socket& operator=(Socket& other) = delete;
auto bind(const char* address) -> void;
auto unbind(const char* address) -> void;
auto connect(const char* address) -> void;
auto disconnect(const char* address) -> void;
auto getBacklog() const -> int;
auto getHandshakeInterval() const -> int;
auto getImmediate() const -> bool;
auto getIoThreadAffinity() const -> uint64_t;
auto getIPv6() const -> bool;
auto getLastEndpoint(size_t length, char* buffer) const -> void;
auto getMaxReconnectInterval() const -> int;
auto getMulticastRate() const -> int;
auto getMulticastRecoveryInterval() const -> int;
auto getReconnectInterval() const -> int;
auto setBacklog(const int backlog) -> void;
auto setHandshakeInterval(const int milliseconds) -> void;
auto setImmediate(const bool immediate) -> void;
auto setIoThreadAffinity(const uint64_t affinity) -> void;
auto setIPv6(const bool ipv6) -> void;
auto setMaxReconnectInterval(const int milliseconds) -> void;
auto setMulticastRate(const int kbps) -> void;
auto setMulticastRecoveryInterval(const int milliseconds) -> void;
auto setReconnectInterval(const int milliseconds) -> void;
explicit operator void*();
protected:
Socket(void* context, int type);
Socket(Socket&& other);
Socket& operator=(Socket&& other);
template <typename T>
auto getSocketOption(const int option) const -> T;
auto getSocketOption( const int option
, void* value
, size_t* valueLength ) const -> void;
template <typename T>
auto setSocketOption(const int option, const T value) -> void;
auto setSocketOption( const int option
, const void* value
, const size_t valueLength ) -> void;
private:
void* mSocket;
};
inline
Socket::~Socket()
{
if (mSocket != nullptr)
{
int result = zmq_close(mSocket);
CPPEROMQ_ASSERT(result == 0);
mSocket = 0 ;
}
}
inline
auto Socket::bind(const char* address) -> void
{
if (0 != zmq_bind(mSocket, address))
{
throw Error();
}
}
inline
auto Socket::unbind(const char* address) -> void
{
if (0 != zmq_unbind(mSocket, address))
{
throw Error();
}
}
inline
auto Socket::connect(const char* address) -> void
{
if (0 != zmq_connect(mSocket, address))
{
throw Error();
}
}
inline
auto Socket::disconnect(const char* address) -> void
{
if (0 != zmq_disconnect(mSocket, address))
{
throw Error();
}
}
inline
Socket::Socket(void* context, int type)
: mSocket(nullptr)
{
CPPEROMQ_ASSERT(context != nullptr);
mSocket = zmq_socket(context, type);
if (mSocket == NULL)
{
throw Error();
}
}
inline
Socket::Socket(Socket&& other)
: mSocket(other.mSocket)
{
other.mSocket = nullptr;
}
inline
Socket& Socket::operator=(Socket&& other)
{
using std::swap;
swap(mSocket, other.mSocket);
return (*this);
}
inline
auto Socket::getBacklog() const -> int
{
return (getSocketOption<int>(ZMQ_BACKLOG));
}
inline
auto Socket::getHandshakeInterval() const -> int
{
return (getSocketOption<int>(ZMQ_HANDSHAKE_IVL));
}
inline
auto Socket::getImmediate() const -> bool
{
return (getSocketOption<bool>(ZMQ_IMMEDIATE));
}
inline
auto Socket::getIoThreadAffinity() const -> uint64_t
{
return (getSocketOption<uint64_t>(ZMQ_AFFINITY));
}
inline
auto Socket::getIPv6() const -> bool
{
return (getSocketOption<bool>(ZMQ_IPV6));
}
inline
auto Socket::getLastEndpoint(size_t length, char* buffer) const -> void
{
CPPEROMQ_ASSERT(buffer != nullptr);
memset(buffer, 0, length);
return (getSocketOption(ZMQ_LAST_ENDPOINT, buffer, &length));
}
inline
auto Socket::getMaxReconnectInterval() const -> int
{
return (getSocketOption<int>(ZMQ_RECONNECT_IVL_MAX));
}
inline
auto Socket::getMulticastRate() const -> int
{
return (getSocketOption<int>(ZMQ_RATE));
}
inline
auto Socket::getMulticastRecoveryInterval() const -> int
{
return (getSocketOption<int>(ZMQ_RECOVERY_IVL));
}
inline
auto Socket::getReconnectInterval() const -> int
{
return (getSocketOption<int>(ZMQ_RECONNECT_IVL));
}
inline
auto Socket::setBacklog(const int backlog) -> void
{
setSocketOption(ZMQ_BACKLOG, backlog);
}
inline
auto Socket::setHandshakeInterval(const int milliseconds) -> void
{
setSocketOption(ZMQ_HANDSHAKE_IVL, milliseconds);
}
inline
auto Socket::setImmediate(const bool immediate) -> void
{
setSocketOption(ZMQ_IMMEDIATE, (immediate) ? 1 : 0);
}
inline
auto Socket::setIoThreadAffinity(const uint64_t affinity) -> void
{
setSocketOption(ZMQ_AFFINITY, affinity);
}
inline
auto Socket::setIPv6(const bool ipv6) -> void
{
setSocketOption(ZMQ_IPV6, (ipv6) ? 1 : 0);
}
inline
auto Socket::setMulticastRate(const int kbps) -> void
{
setSocketOption(ZMQ_RATE, kbps);
}
inline
auto Socket::setMulticastRecoveryInterval(const int milliseconds) -> void
{
setSocketOption(ZMQ_RECOVERY_IVL, milliseconds);
}
inline
auto Socket::setMaxReconnectInterval(const int milliseconds) -> void
{
setSocketOption(ZMQ_RECONNECT_IVL_MAX, milliseconds);
}
inline
auto Socket::setReconnectInterval(const int milliseconds) -> void
{
setSocketOption(ZMQ_RECONNECT_IVL, milliseconds);
}
inline
Socket::operator void*()
{
return mSocket;
}
template <typename T>
inline
auto Socket::getSocketOption(const int option) const -> T
{
T value;
size_t valueLength = sizeof(T);
getSocketOption(option, &value, &valueLength);
return value;
}
inline
auto Socket::getSocketOption( const int option
, void* value
, size_t* valueLength ) const -> void
{
if (0 != zmq_getsockopt(mSocket, option, value, valueLength))
{
throw Error();
}
}
template <typename T>
inline
auto Socket::setSocketOption(const int option, const T value) -> void
{
setSocketOption(option, &value, sizeof(value));
}
inline
auto Socket::setSocketOption( const int option
, const void* value
, const size_t valueLength ) -> void
{
if (0 != zmq_setsockopt(mSocket, option, value, valueLength))
{
throw Error();
}
}
}
|
/*
Copyright 2005-2015 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks is free software;
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation. Threading Building Blocks is
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should have received a copy of
the GNU General Public License along with Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
#include "harness.h"
#if __TBB_FLOW_GRAPH_CPP11_FEATURES
#include "tbb/flow_graph.h"
#include <tuple>
#include <cmath>
#include <vector>
struct passthru_body {
int operator()( int i ) {
return i;
}
};
class src_body{
int start;
int finish;
int step;
public:
src_body(int f, int s) : start(1), finish(f), step(s) {}
bool operator()(int &a) {
a = start;
if (start <= finish) {
a = start;
start+=step;
return true;
}
else {
return false;
};
}
};
struct m_fxn_body{
void operator()(int, tbb::flow::multifunction_node<int, tbb::flow::tuple<int,int> >::output_ports_type ) {}
};
struct ct_body {
ct_body(){}
void operator()(tbb::flow::continue_msg){}
};
struct seq_body {
int operator()(int i){return i;}
};
template<int N, typename T1, typename T2>
struct compare {
static void compare_refs(T1 tuple1, T2 tuple2) {
ASSERT( &tbb::flow::get<N>(tuple1) == &tbb::flow::get<N>(tuple2), "ports not set correctly");
compare<N-1, T1, T2>::compare_refs(tuple1, tuple2);
}
};
template<typename T1, typename T2>
struct compare<1, T1, T2> {
static void compare_refs(T1 tuple1, T2 tuple2) {
ASSERT(&tbb::flow::get<0>(tuple1) == &tbb::flow::get<0>(tuple2), "port 0 not correctly set");
}
};
void add_all_nodes (){
tbb::flow::graph g;
typedef tbb::flow::tuple<tbb::flow::continue_msg, tbb::flow::tuple<int, int>, int, int, int, int,
int, int, int, int, int, int, int, int > InputTupleType;
typedef tbb::flow::tuple<tbb::flow::continue_msg, tbb::flow::tuple<int, int>, tbb::flow::tagged_msg<size_t, int, float>,
int, int, int, int, int, int, int, int, int, int, int, int > OutputTupleType;
typedef tbb::flow::tuple< > EmptyTupleType;
typedef tbb::flow::composite_node<InputTupleType, OutputTupleType > input_output_type;
typedef tbb::flow::composite_node<InputTupleType, EmptyTupleType > input_only_type;
typedef tbb::flow::composite_node<EmptyTupleType, OutputTupleType > output_only_type;
const size_t NUM_INPUTS = tbb::flow::tuple_size<InputTupleType>::value;
const size_t NUM_OUTPUTS = tbb::flow::tuple_size<OutputTupleType>::value;
//node types
tbb::flow::continue_node<tbb::flow::continue_msg> ct(g, ct_body());
tbb::flow::split_node< tbb::flow::tuple<int, int> > s(g);
tbb::flow::source_node<int> src(g, src_body(20,5), false);
tbb::flow::function_node<int, int> fxn(g, tbb::flow::unlimited, passthru_body());
tbb::flow::multifunction_node<int, tbb::flow::tuple<int, int> > m_fxn(g, tbb::flow::unlimited, m_fxn_body());
tbb::flow::broadcast_node<int> bc(g);
tbb::flow::limiter_node<int> lim(g, 2);
tbb::flow::indexer_node<int, float> ind(g);
tbb::flow::join_node< tbb::flow::tuple< int, int >, tbb::flow::queueing > j(g);
tbb::flow::queue_node<int> q(g);
tbb::flow::buffer_node<int> bf(g);
tbb::flow::priority_queue_node<int> pq(g);
tbb::flow::write_once_node<int> wo(g);
tbb::flow::overwrite_node<int> ovw(g);
tbb::flow::sequencer_node<int> seq(g, seq_body());
#if !(__GNUC__==4 && __GNUC_MINOR__==4 && !defined(__clang__))
// upcasting of a tuple of reference from derived to base fails on gcc4.4 (and all icc in this environment)
// if std::tie is used to create the tuple of references
auto input_tuple = std::tie(ct, s, m_fxn, fxn, bc, tbb::flow::input_port<0>(j), lim, q, tbb::flow::input_port<0>(ind),
pq, ovw, wo, bf, seq);
auto output_tuple = std::tie(ct,j, ind, fxn, src, bc, tbb::flow::output_port<0>(s), lim, tbb::flow::output_port<0>(m_fxn),
q, pq, ovw, wo, bf, seq );
#else
input_output_type::input_ports_type input_tuple(ct, s, m_fxn, fxn, bc, tbb::flow::input_port<0>(j), lim, q,
tbb::flow::input_port<0>(ind), pq, ovw, wo, bf, seq);
input_output_type::output_ports_type output_tuple(ct,j, ind, fxn, src, bc, tbb::flow::output_port<0>(s),
lim, tbb::flow::output_port<0>(m_fxn), q, pq, ovw, wo, bf, seq);
#endif
//composite_node with both input_ports and output_ports
input_output_type a_node(g);
a_node.set_external_ports(input_tuple, output_tuple);
a_node.add_visible_nodes(src, fxn, m_fxn, bc, lim, ind, s, ct, j, q, bf, pq, wo, ovw, seq);
a_node.add_nodes(src, fxn, m_fxn, bc, lim, ind, s, ct, j, q, bf, pq, wo, ovw, seq);
auto a_node_input_ports_ptr = a_node.input_ports();
compare<NUM_INPUTS-1, decltype(a_node_input_ports_ptr), decltype(input_tuple)>::compare_refs(a_node_input_ports_ptr, input_tuple);
ASSERT (NUM_INPUTS == tbb::flow::tuple_size<decltype(a_node_input_ports_ptr)>::value, "not all declared input ports were bound to nodes");
auto a_node_output_ports_ptr = a_node.output_ports();
compare<NUM_OUTPUTS-1, decltype(a_node_output_ports_ptr), decltype(output_tuple)>::compare_refs(a_node_output_ports_ptr, output_tuple);
ASSERT(NUM_OUTPUTS == tbb::flow::tuple_size<decltype(a_node_output_ports_ptr)>::value, "not all declared output ports were bound to nodes");
//composite_node with only input_ports
input_only_type b_node(g);
b_node.set_external_ports(input_tuple);
b_node.add_visible_nodes(src, fxn, m_fxn, bc, lim, ind, s, ct, j, q, bf, pq, wo, ovw, seq);
b_node.add_nodes(src, fxn, m_fxn, bc, lim, ind, s, ct, j, q, bf, pq, wo, ovw, seq);
auto b_node_input_ports_ptr = b_node.input_ports();
compare<NUM_INPUTS-1, decltype(b_node_input_ports_ptr), decltype(input_tuple)>::compare_refs(b_node_input_ports_ptr, input_tuple);
ASSERT (NUM_INPUTS == tbb::flow::tuple_size<decltype(b_node_input_ports_ptr)>::value, "not all declared input ports were bound to nodes");
//composite_node with only output_ports
output_only_type c_node(g);
c_node.set_external_ports(output_tuple);
c_node.add_visible_nodes(src, fxn, m_fxn, bc, lim, ind, s, ct, j, q, bf, pq, wo, ovw, seq);
c_node.add_nodes(src, fxn, m_fxn, bc, lim, ind, s, ct, j, q, bf, pq, wo, ovw, seq);
auto c_node_output_ports_ptr = c_node.output_ports();
compare<NUM_OUTPUTS-1, decltype(c_node_output_ports_ptr), decltype(output_tuple)>::compare_refs(c_node_output_ports_ptr, output_tuple);
ASSERT (NUM_OUTPUTS == tbb::flow::tuple_size<decltype(c_node_output_ports_ptr)>::value, "not all declared input ports were bound to nodes");
}
struct tiny_node : public tbb::flow::composite_node< tbb::flow::tuple< int >, tbb::flow::tuple< int > > {
tbb::flow::function_node< int, int > f1;
tbb::flow::function_node< int, int > f2;
typedef tbb::flow::composite_node< tbb::flow::tuple< int >, tbb::flow::tuple< int > > base_type;
public:
tiny_node(tbb::flow::graph &g, bool hidden = false) : base_type(g), f1(g, tbb::flow::unlimited, passthru_body() ), f2(g, tbb::flow::unlimited, passthru_body() ) {
tbb::flow::make_edge( f1, f2 );
tbb::flow::tuple<tbb::flow::function_node< int, int >& > input_tuple(f1);
tbb::flow::tuple<tbb::flow::function_node< int, int >& > output_tuple(f2);
base_type::set_external_ports( input_tuple, output_tuple );
if(hidden)
base_type::add_nodes(f1, f2);
else
base_type::add_visible_nodes(f1, f2);
}
};
int test_tiny(bool hidden = false) {
tbb::flow::graph g;
tbb::flow::function_node< int, int > f0( g, tbb::flow::unlimited, passthru_body() );
tiny_node t(g, hidden);
ASSERT(&tbb::flow::input_port<0>(t) == &t.f1, "f1 not bound to input port 0 in composite_node t");
ASSERT(&tbb::flow::output_port<0>(t) == &t.f2, "f2 not bound to output port 0 in composite_node t");
tiny_node t1(g, hidden);
ASSERT(&tbb::flow::get<0>(t1.input_ports()) == &t1.f1, "f1 not bound to input port 0 in composite_node t1");
ASSERT(&tbb::flow::get<0>(t1.output_ports()) == &t1.f2, "f2 not bound to output port 0 in composite_node t1");
tiny_node t2(g, hidden);
ASSERT(&tbb::flow::input_port<0>(t2) == &t2.f1, "f1 not bound to input port 0 in composite_node t2");
ASSERT(&tbb::flow::output_port<0>(t2) == &t2.f2, "f2 not bound to output port 0 in composite_node t2");
tbb::flow::function_node< int, int > f3( g, tbb::flow::unlimited, passthru_body() );
tbb::flow::make_edge( f0, t );
tbb::flow::make_edge( t, t1 );
tbb::flow::make_edge( t1, t2 );
tbb::flow::make_edge( t2 , f3 );
tbb::flow::queue_node<int> q(g);
tbb::flow::make_edge(f3, q);
f0.try_put(1);
g.wait_for_all();
int i, j =0;
q.try_get(i);
ASSERT( i == 1, "item did not go through graph");
q.try_get(j);
ASSERT( !j, "unexpected item in graph");
g.wait_for_all();
tbb::flow::remove_edge(f3, q);
tbb::flow::remove_edge(t2, f3);
tbb::flow::remove_edge(t1, t2);
tbb::flow::make_edge( t1 , f3 );
tbb::flow::make_edge(f3, q);
f0.try_put(2);
g.wait_for_all();
q.try_get(i);
ASSERT( i == 2, "item did not go through graph after removal of edge");
q.try_get(j);
ASSERT( !j, "unexpected item in graph after removal of edge");
return 0;
}
class adder_node : public tbb::flow::composite_node< tbb::flow::tuple< int, int >, tbb::flow::tuple< int > > {
public:
tbb::flow::join_node< tbb::flow::tuple< int, int >, tbb::flow::queueing > j;
tbb::flow::function_node< tbb::flow::tuple< int, int >, int > f;
private:
typedef tbb::flow::composite_node< tbb::flow::tuple< int, int >, tbb::flow::tuple< int > > base_type;
struct f_body {
int operator()( const tbb::flow::tuple< int, int > &t ) {
return tbb::flow::get<0>(t) + tbb::flow::get<1>(t);
}
};
public:
adder_node(tbb::flow::graph &g, bool hidden = false) : base_type(g), j(g), f(g, tbb::flow::unlimited, f_body() ) {
tbb::flow::make_edge( j, f );
base_type::set_external_ports(base_type::input_ports_type(tbb::flow::input_port<0>(j), tbb::flow::input_port<1>(j)), base_type::output_ports_type(f));
if (hidden)
base_type::add_nodes(j, f);
else
base_type::add_visible_nodes(j, f);
}
};
struct square_body { int operator()(int v) { return v*v; } };
struct cube_body { int operator()(int v) { return v*v*v; } };
int adder_sum(int i) {
return (int)(pow(3*pow(i,3) + pow(i, 2),2));
}
int test_adder(bool hidden = false) {
tbb::flow::graph g;
tbb::flow::function_node<int,int> s(g, tbb::flow::unlimited, square_body());
tbb::flow::function_node<int,int> c(g, tbb::flow::unlimited, cube_body());
tbb::flow::function_node<int,int> p(g, tbb::flow::unlimited, passthru_body());
adder_node a0(g, hidden);
ASSERT(&tbb::flow::input_port<0>(a0) == &tbb::flow::input_port<0>(a0.j), "input_port 0 of j not bound to input port 0 in composite_node a0");
ASSERT(&tbb::flow::input_port<1>(a0) == &tbb::flow::input_port<1>(a0.j), "input_port 1 of j not bound to input port 1 in composite_node a0");
ASSERT(&tbb::flow::output_port<0>(a0) == &a0.f, "f not bound to output port 0 in composite_node a0");
adder_node a1(g, hidden);
ASSERT(&tbb::flow::get<0>(a0.input_ports()) == &tbb::flow::input_port<0>(a0.j), "input_port 0 of j not bound to input port 0 in composite_node a1");
ASSERT(&tbb::flow::get<1>(a0.input_ports()) == &tbb::flow::input_port<1>(a0.j), "input_port1 of j not bound to input port 1 in composite_node a1");
ASSERT(&tbb::flow::get<0>(a0.output_ports()) == &a0.f, "f not bound to output port 0 in composite_node a1");
adder_node a2(g, hidden);
ASSERT(&tbb::flow::input_port<0>(a2) == &tbb::flow::input_port<0>(a2.j), "input_port 0 of j not bound to input port 0 in composite_node a2");
ASSERT(&tbb::flow::input_port<1>(a2) == &tbb::flow::input_port<1>(a2.j), "input_port 1 of j not bound to input port 1 in composite_node a2");
ASSERT(&tbb::flow::output_port<0>(a2) == &a2.f, "f not bound to output port 0 in composite_node a2");
adder_node a3(g, hidden);
ASSERT(&tbb::flow::get<0>(a3.input_ports()) == &tbb::flow::input_port<0>(a3.j), "input_port 0 of j not bound to input port 0 in composite_node a3");
ASSERT(&tbb::flow::get<1>(a3.input_ports()) == &tbb::flow::input_port<1>(a3.j), "input_port1 of j not bound to input port 1 in composite_node a3");
ASSERT(&tbb::flow::get<0>(a3.output_ports()) == &a3.f, "f not bound to output port 0 in composite_node a3");
tbb::flow::function_node<int,int> s2(g, tbb::flow::unlimited, square_body());
tbb::flow::queue_node<int> q(g);
tbb::flow::make_edge( s, tbb::flow::input_port<0>(a0) );
tbb::flow::make_edge( c, tbb::flow::input_port<1>(a0) );
tbb::flow::make_edge( c, tbb::flow::input_port<0>(a1) );
tbb::flow::make_edge( c, tbb::flow::input_port<1>(a1) );
tbb::flow::make_edge( tbb::flow::output_port<0>(a0), tbb::flow::input_port<0>(a2) );
tbb::flow::make_edge( tbb::flow::output_port<0>(a1), tbb::flow::input_port<1>(a2) );
tbb::flow::make_edge( tbb::flow::output_port<0>(a2), s2 );
tbb::flow::make_edge( s2, q );
int sum_total=0;
int result=0;
for ( int i = 1; i < 4; ++i ) {
s.try_put(i);
c.try_put(i);
sum_total += adder_sum(i);
g.wait_for_all();
}
int j;
for ( int i = 1; i < 4; ++i ) {
q.try_get(j);
result += j;
}
g.wait_for_all();
ASSERT(result == sum_total, "the sum from the graph does not match the calculated value");
tbb::flow::remove_edge(s2, q);
tbb::flow::remove_edge( a2, s2 );
tbb::flow::make_edge( a0, a3 );
tbb::flow::make_edge( a1, tbb::flow::input_port<1>(a3) );
tbb::flow::make_edge( a3, s2 );
tbb::flow::make_edge( s2, q );
sum_total=0;
result=0;
for ( int i = 10; i < 20; ++i ) {
s.try_put(i);
c.try_put(i);
sum_total += adder_sum(i);
g.wait_for_all();
}
for ( int i = 10; i < 20; ++i ) {
q.try_get(j);
result += j;
}
g.wait_for_all();
ASSERT(result == sum_total, "the new sum after the replacement of the nodes does not match the calculated value");
return 0;
}
/*
outer composite node (outer_node)
|-------------------------------------------------------------------|
| |
| |------------------| |------------------| |------------------| |
|---------------------| |--| inner composite | /| inner composite | /| inner composite | | |-------------------|
|broadcast node(input)|/| | node |/ | node |/ | node |-+-| queue node(output)|
|---------------------|\| |(inner_node1) |\ | (inner_node2) |\ | (inner_node3) | | |-------------------|
|--| | \| | \| | |
| |------------------| |------------------| |------------------| |
| |
|-------------------------------------------------------------------|
*/
int test_nested_adder(bool hidden=false) {
tbb::flow::graph g;
tbb::flow::composite_node<tbb::flow::tuple<int, int>, tbb::flow::tuple<int> > outer_node(g);
typedef tbb::flow::composite_node<tbb::flow::tuple<int, int>, tbb::flow::tuple<int> > base_type;
tbb::flow::broadcast_node<int> input(g);
tbb::flow::queue_node<int> output(g);
adder_node inner_node1(g, hidden);
adder_node inner_node2(g, hidden);
adder_node inner_node3(g, hidden);
outer_node.set_external_ports(base_type::input_ports_type(tbb::flow::input_port<0>(inner_node1), tbb::flow::input_port<1>(inner_node1)), base_type::output_ports_type(tbb::flow::output_port<0>(inner_node3)));
ASSERT(&tbb::flow::input_port<0>(outer_node) == &tbb::flow::input_port<0>(inner_node1), "input port 0 of inner_node1 not bound to input port 0 in outer_node");
ASSERT(&tbb::flow::input_port<1>(outer_node) == &tbb::flow::input_port<1>(inner_node1), "input port 1 of inner_node1 not bound to input port 1 in outer_node");
ASSERT(&tbb::flow::output_port<0>(outer_node) == &tbb::flow::output_port<0>(inner_node3), "output port 0 of inner_node3 not bound to output port 0 in outer_node");
tbb::flow::make_edge(input, tbb::flow::input_port<0>(outer_node)/*inner_node1*/);
tbb::flow::make_edge(input, tbb::flow::input_port<1>(outer_node)/*inner_node1*/);
tbb::flow::make_edge(inner_node1, tbb::flow::input_port<0>(inner_node2));
tbb::flow::make_edge(inner_node1, tbb::flow::input_port<1>(inner_node2));
tbb::flow::make_edge(inner_node2, tbb::flow::input_port<0>(inner_node3));
tbb::flow::make_edge(inner_node2, tbb::flow::input_port<1>(inner_node3));
tbb::flow::make_edge(outer_node/*inner_node3*/, output);
if(hidden)
outer_node.add_nodes(inner_node1, inner_node2, inner_node3);
else
outer_node.add_visible_nodes(inner_node1, inner_node2, inner_node3);
int out;
for (int i = 1; i < 200000; ++i) {
input.try_put(i);
g.wait_for_all();
output.try_get(out);
ASSERT(tbb::flow::output_port<0>(outer_node).try_get(out) == output.try_get(out), "output from outer_node does not match output from graph");
ASSERT(out == 8*i, "output from outer_node not correct");
}
g.wait_for_all();
return 0;
}
template< typename T >
class prefix_node : public tbb::flow::composite_node< tbb::flow::tuple< T, T, T, T, T >, tbb::flow::tuple< T, T, T, T, T > > {
typedef tbb::flow::tuple< T, T, T, T, T > my_tuple_t;
public:
tbb::flow::join_node< my_tuple_t, tbb::flow::queueing > j;
tbb::flow::split_node< my_tuple_t > s;
private:
tbb::flow::function_node< my_tuple_t, my_tuple_t > f;
typedef tbb::flow::composite_node< my_tuple_t, my_tuple_t > base_type;
struct f_body {
my_tuple_t operator()( const my_tuple_t &t ) {
return my_tuple_t( tbb::flow::get<0>(t),
tbb::flow::get<0>(t) + tbb::flow::get<1>(t),
tbb::flow::get<0>(t) + tbb::flow::get<1>(t) + tbb::flow::get<2>(t),
tbb::flow::get<0>(t) + tbb::flow::get<1>(t) + tbb::flow::get<2>(t) + tbb::flow::get<3>(t),
tbb::flow::get<0>(t) + tbb::flow::get<1>(t) + tbb::flow::get<2>(t) + tbb::flow::get<3>(t) + tbb::flow::get<4>(t) );
}
};
public:
prefix_node(tbb::flow::graph &g, bool hidden = false ) : base_type(g), j(g), s(g), f(g, tbb::flow::serial, f_body() ) {
tbb::flow::make_edge( j, f );
tbb::flow::make_edge( f, s );
typename base_type::input_ports_type input_tuple(tbb::flow::input_port<0>(j), tbb::flow::input_port<1>(j), tbb::flow::input_port<2>(j), tbb::flow::input_port<3>(j), tbb::flow::input_port<4>(j));
typename base_type::output_ports_type output_tuple(tbb::flow::output_port<0>(s), tbb::flow::output_port<1>(s), tbb::flow::output_port<2>(s), tbb::flow::output_port<3>(s), tbb::flow::output_port<4>(s));
base_type::set_external_ports(input_tuple, output_tuple);
if(hidden)
base_type::add_nodes(j,s,f);
else
base_type::add_visible_nodes(j,s,f);
}
};
int test_prefix(bool hidden = false) {
tbb::flow::graph g;
prefix_node<double> p(g, hidden);
ASSERT(&tbb::flow::get<0>(p.input_ports()) == &tbb::flow::input_port<0>(p.j), "input port 0 of j is not bound to input port 0 of composite node p");
ASSERT(&tbb::flow::input_port<1>(p.j) == &tbb::flow::input_port<1>(p.j), "input port 1 of j is not bound to input port 1 of composite node p");
ASSERT(&tbb::flow::get<2>(p.input_ports()) == &tbb::flow::input_port<2>(p.j), "input port 2 of j is not bound to input port 2 of composite node p");
ASSERT(&tbb::flow::input_port<3>(p.j) == &tbb::flow::input_port<3>(p.j), "input port 3 of j is not bound to input port 3 of composite node p");
ASSERT(&tbb::flow::get<4>(p.input_ports()) == &tbb::flow::input_port<4>(p.j), "input port 4 of j is not bound to input port 4 of composite node p");
ASSERT(&tbb::flow::get<0>(p.output_ports()) == &tbb::flow::output_port<0>(p.s), "output port 0 of s is not bound to output port 0 of composite node p");
ASSERT(&tbb::flow::output_port<1>(p.s) == &tbb::flow::output_port<1>(p.s), "output port 1 of s is not bound to output port 1 of composite node p");
ASSERT(&tbb::flow::get<2>(p.output_ports()) == &tbb::flow::output_port<2>(p.s), "output port 2 of s is not bound to output port 2 of composite node p");
ASSERT(&tbb::flow::output_port<3>(p.s) == &tbb::flow::output_port<3>(p.s), "output port 3 of s is not bound to output port 3 of composite node p");
ASSERT(&tbb::flow::get<4>(p.output_ports()) == &tbb::flow::output_port<4>(p.s), "output port 4 of s is not bound to output port 4 of composite node p");
std::vector< tbb::flow::queue_node<double> > v( 5, tbb::flow::queue_node<double>(g) );
tbb::flow::make_edge( tbb::flow::output_port<0>(p), v[0] );
tbb::flow::make_edge( tbb::flow::output_port<1>(p), v[1] );
tbb::flow::make_edge( tbb::flow::output_port<2>(p), v[2] );
tbb::flow::make_edge( tbb::flow::output_port<3>(p), v[3] );
tbb::flow::make_edge( tbb::flow::output_port<4>(p), v[4] );
for( double offset = 1; offset < 10000; offset *= 10 ) {
tbb::flow::input_port<0>(p).try_put( offset );
tbb::flow::input_port<1>(p).try_put( offset + 1 );
tbb::flow::input_port<2>(p).try_put( offset + 2 );
tbb::flow::input_port<3>(p).try_put( offset + 3 );
tbb::flow::input_port<4>(p).try_put( offset + 4 );
}
g.wait_for_all();
double x;
while ( v[0].try_get(x) ) {
g.wait_for_all();
for ( int i = 1; i < 5; ++i ) {
v[i].try_get(x);
g.wait_for_all();
}
}
return 0;
}
void input_only_output_only_composite(bool hidden) {
tbb::flow::graph g;
#if TBB_PREVIEW_FLOW_GRAPH_TRACE
tbb::flow::composite_node<tbb::flow::tuple<int>, tbb::flow::tuple<int> > input_output(g, "test_name");
#else
tbb::flow::composite_node<tbb::flow::tuple<int>, tbb::flow::tuple<int> > input_output(g);
#endif
typedef tbb::flow::composite_node<tbb::flow::tuple<int>, tbb::flow::tuple<> > input_only_composite;
typedef tbb::flow::composite_node<tbb::flow::tuple<>, tbb::flow::tuple<int> > output_only_composite;
typedef tbb::flow::source_node<int> src_type;
typedef tbb::flow::queue_node<int> q_type;
typedef tbb::flow::function_node<int, int> f_type;
int num = 0;
int finish=1000;
int step = 4;
input_only_composite a_in(g);
output_only_composite a_out(g);
src_type src(g, src_body(finish, step), false);
q_type que(g);
f_type f(g, 1, passthru_body());
tbb::flow::tuple<f_type& > input_tuple(f);
a_in.set_external_ports(input_tuple);
ASSERT(&tbb::flow::get<0>(a_in.input_ports()) == &f, "f not bound to input port 0 in composite_node a_in");
tbb::flow::tuple<src_type&> output_tuple(src);
a_out.set_external_ports(output_tuple);
ASSERT(&tbb::flow::get<0>(a_out.output_ports()) == &src, "src not bound to output port 0 in composite_node a_out");
if(hidden) {
a_in.add_nodes(f, que);
a_out.add_nodes(src);
} else {
a_in.add_visible_nodes(f, que);
a_out.add_visible_nodes(src);
}
tbb::flow::make_edge(a_out, a_in);
tbb::flow::make_edge(f, que);
src.activate();
g.wait_for_all();
for(int i = 1; i<finish/step; ++i) {
que.try_get(num);
ASSERT(num == 4*i - 3, "number does not match position in sequence");
}
g.wait_for_all();
}
#endif // __TBB_FLOW_GRAPH_CPP11_FEATURES
int TestMain() {
#if __TBB_FLOW_GRAPH_CPP11_FEATURES
add_all_nodes();
test_tiny(false);
test_tiny(true);
test_adder(false);
test_adder(true);
test_nested_adder(true);
test_nested_adder(false);
test_prefix(false);
test_prefix(true);
input_only_output_only_composite(true);
input_only_output_only_composite(false);
return Harness::Done;
#else
return Harness::Skipped;
#endif
}
|
#include <geodesuka/core/hid/mouse.h>
#include <geodesuka/core/math.h>
namespace geodesuka {
namespace core {
namespace hid {
mouse::mouse() {
Mode = MODE_NORMAL;
}
mouse::~mouse() {
}
math::boolean mouse::operator[](math::integer buttonID) {
if ((Action[buttonID] == BUTTON_PRESS) || (Action[buttonID] == BUTTON_REPEAT)) {
return true;
}
else {
return false;
}
}
}
}
}
|
/*************************************************************************/
/* gd_mono_class.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "gd_mono_class.h"
#include <mono/metadata/attrdefs.h>
#include <mono/metadata/debug-helpers.h>
#include "gd_mono_assembly.h"
#include "gd_mono_cache.h"
#include "gd_mono_marshal.h"
String GDMonoClass::get_full_name(MonoClass *p_mono_class) {
// mono_type_get_full_name is not exposed to embedders, but this seems to do the job
MonoReflectionType *type_obj = mono_type_get_object(mono_domain_get(), get_mono_type(p_mono_class));
MonoException *exc = NULL;
MonoString *str = GDMonoUtils::object_to_string((MonoObject *)type_obj, &exc);
UNHANDLED_EXCEPTION(exc);
return GDMonoMarshal::mono_string_to_godot(str);
}
MonoType *GDMonoClass::get_mono_type(MonoClass *p_mono_class) {
return mono_class_get_type(p_mono_class);
}
String GDMonoClass::get_full_name() const {
return get_full_name(mono_class);
}
String GDMonoClass::get_type_desc() const {
return GDMonoUtils::get_type_desc(get_mono_type());
}
MonoType *GDMonoClass::get_mono_type() const {
// Careful, you cannot compare two MonoType*.
// There is mono_metadata_type_equal, how is this different from comparing two MonoClass*?
return get_mono_type(mono_class);
}
uint32_t GDMonoClass::get_flags() const {
return mono_class_get_flags(mono_class);
}
bool GDMonoClass::is_static() const {
uint32_t static_class_flags = MONO_TYPE_ATTR_ABSTRACT | MONO_TYPE_ATTR_SEALED;
return (get_flags() & static_class_flags) == static_class_flags;
}
bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const {
return mono_class_is_assignable_from(mono_class, p_from->mono_class);
}
StringName GDMonoClass::get_namespace() const {
GDMonoClass *nesting_class = get_nesting_class();
if (!nesting_class)
return namespace_name;
return nesting_class->get_namespace();
}
String GDMonoClass::get_name_for_lookup() const {
GDMonoClass *nesting_class = get_nesting_class();
if (!nesting_class)
return class_name;
return nesting_class->get_name_for_lookup() + "/" + class_name;
}
GDMonoClass *GDMonoClass::get_parent_class() const {
MonoClass *parent_mono_class = mono_class_get_parent(mono_class);
return parent_mono_class ? GDMono::get_singleton()->get_class(parent_mono_class) : NULL;
}
GDMonoClass *GDMonoClass::get_nesting_class() const {
MonoClass *nesting_type = mono_class_get_nesting_type(mono_class);
return nesting_type ? GDMono::get_singleton()->get_class(nesting_type) : NULL;
}
#ifdef TOOLS_ENABLED
Vector<MonoClassField *> GDMonoClass::get_enum_fields() {
bool class_is_enum = mono_class_is_enum(mono_class);
ERR_FAIL_COND_V(!class_is_enum, Vector<MonoClassField *>());
Vector<MonoClassField *> enum_fields;
void *iter = NULL;
MonoClassField *raw_field = NULL;
while ((raw_field = mono_class_get_fields(get_mono_ptr(), &iter)) != NULL) {
uint32_t field_flags = mono_field_get_flags(raw_field);
// Enums have an instance field named value__ which holds the value of the enum.
// Enum constants are static, so we will use this to ignore the value__ field.
if (field_flags & MONO_FIELD_ATTR_PUBLIC && field_flags & MONO_FIELD_ATTR_STATIC) {
enum_fields.push_back(raw_field);
}
}
return enum_fields;
}
#endif
bool GDMonoClass::has_attribute(GDMonoClass *p_attr_class) {
#ifdef DEBUG_ENABLED
ERR_FAIL_NULL_V(p_attr_class, false);
#endif
if (!attrs_fetched)
fetch_attributes();
if (!attributes)
return false;
return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
}
MonoObject *GDMonoClass::get_attribute(GDMonoClass *p_attr_class) {
#ifdef DEBUG_ENABLED
ERR_FAIL_NULL_V(p_attr_class, NULL);
#endif
if (!attrs_fetched)
fetch_attributes();
if (!attributes)
return NULL;
return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
}
void GDMonoClass::fetch_attributes() {
ERR_FAIL_COND(attributes != NULL);
attributes = mono_custom_attrs_from_class(get_mono_ptr());
attrs_fetched = true;
}
void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base) {
CRASH_COND(!CACHED_CLASS(GodotObject)->is_assignable_from(this));
if (methods_fetched)
return;
void *iter = NULL;
MonoMethod *raw_method = NULL;
while ((raw_method = mono_class_get_methods(get_mono_ptr(), &iter)) != NULL) {
StringName name = String::utf8(mono_method_get_name(raw_method));
// get_method implicitly fetches methods and adds them to this->methods
GDMonoMethod *method = get_method(raw_method, name);
ERR_CONTINUE(!method);
if (method->get_name() != name) {
#ifdef DEBUG_ENABLED
String fullname = method->get_ret_type_full_name() + " " + name + "(" + method->get_signature_desc(true) + ")";
WARN_PRINT("Method '" + fullname + "' is hidden by Godot API method. Should be '" +
method->get_full_name_no_class() + "'. In class '" + namespace_name + "." + class_name + "'.");
#endif
continue;
}
#ifdef DEBUG_ENABLED
// For debug builds, we also fetched from native base classes as well before if this is not a native base class.
// This allows us to warn the user here if he is using snake_case by mistake.
if (p_native_base != this) {
GDMonoClass *native_top = p_native_base;
while (native_top) {
GDMonoMethod *m = native_top->get_method(name, method->get_parameters_count());
if (m && m->get_name() != name) {
// found
String fullname = m->get_ret_type_full_name() + " " + name + "(" + m->get_signature_desc(true) + ")";
WARN_PRINT("Method '" + fullname + "' should be '" + m->get_full_name_no_class() +
"'. In class '" + namespace_name + "." + class_name + "'.");
break;
}
if (native_top == CACHED_CLASS(GodotObject))
break;
native_top = native_top->get_parent_class();
}
}
#endif
uint32_t flags = mono_method_get_flags(method->mono_method, NULL);
if (!(flags & MONO_METHOD_ATTR_VIRTUAL))
continue;
// Virtual method of Godot Object derived type, let's try to find GodotMethod attribute
GDMonoClass *top = p_native_base;
while (top) {
GDMonoMethod *base_method = top->get_method(name, method->get_parameters_count());
if (base_method && base_method->has_attribute(CACHED_CLASS(GodotMethodAttribute))) {
// Found base method with GodotMethod attribute.
// We get the original API method name from this attribute.
// This name must point to the virtual method.
MonoObject *attr = base_method->get_attribute(CACHED_CLASS(GodotMethodAttribute));
StringName godot_method_name = CACHED_FIELD(GodotMethodAttribute, methodName)->get_string_value(attr);
#ifdef DEBUG_ENABLED
CRASH_COND(godot_method_name == StringName());
#endif
MethodKey key = MethodKey(godot_method_name, method->get_parameters_count());
GDMonoMethod **existing_method = methods.getptr(key);
if (existing_method)
memdelete(*existing_method); // Must delete old one
methods.set(key, method);
break;
}
if (top == CACHED_CLASS(GodotObject))
break;
top = top->get_parent_class();
}
}
methods_fetched = true;
}
GDMonoMethod *GDMonoClass::get_fetched_method_unknown_params(const StringName &p_name) {
ERR_FAIL_COND_V(!methods_fetched, NULL);
const MethodKey *k = NULL;
while ((k = methods.next(k))) {
if (k->name == p_name)
return methods.get(*k);
}
return NULL;
}
bool GDMonoClass::has_fetched_method_unknown_params(const StringName &p_name) {
return get_fetched_method_unknown_params(p_name) != NULL;
}
bool GDMonoClass::implements_interface(GDMonoClass *p_interface) {
return mono_class_implements_interface(mono_class, p_interface->get_mono_ptr());
}
bool GDMonoClass::has_public_parameterless_ctor() {
GDMonoMethod *ctor = get_method(".ctor", 0);
return ctor && ctor->get_visibility() == IMonoClassMember::PUBLIC;
}
GDMonoMethod *GDMonoClass::get_method(const StringName &p_name, int p_params_count) {
MethodKey key = MethodKey(p_name, p_params_count);
GDMonoMethod **match = methods.getptr(key);
if (match)
return *match;
if (methods_fetched)
return NULL;
MonoMethod *raw_method = mono_class_get_method_from_name(mono_class, String(p_name).utf8().get_data(), p_params_count);
if (raw_method) {
GDMonoMethod *method = memnew(GDMonoMethod(p_name, raw_method));
methods.set(key, method);
return method;
}
return NULL;
}
GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method) {
MonoMethodSignature *sig = mono_method_signature(p_raw_method);
int params_count = mono_signature_get_param_count(sig);
StringName method_name = String::utf8(mono_method_get_name(p_raw_method));
return get_method(p_raw_method, method_name, params_count);
}
GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name) {
MonoMethodSignature *sig = mono_method_signature(p_raw_method);
int params_count = mono_signature_get_param_count(sig);
return get_method(p_raw_method, p_name, params_count);
}
GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name, int p_params_count) {
ERR_FAIL_NULL_V(p_raw_method, NULL);
MethodKey key = MethodKey(p_name, p_params_count);
GDMonoMethod **match = methods.getptr(key);
if (match)
return *match;
GDMonoMethod *method = memnew(GDMonoMethod(p_name, p_raw_method));
methods.set(key, method);
return method;
}
GDMonoMethod *GDMonoClass::get_method_with_desc(const String &p_description, bool p_include_namespace) {
MonoMethodDesc *desc = mono_method_desc_new(p_description.utf8().get_data(), p_include_namespace);
MonoMethod *method = mono_method_desc_search_in_class(desc, mono_class);
mono_method_desc_free(desc);
if (!method)
return NULL;
ERR_FAIL_COND_V(mono_method_get_class(method) != mono_class, NULL);
return get_method(method);
}
GDMonoField *GDMonoClass::get_field(const StringName &p_name) {
Map<StringName, GDMonoField *>::Element *result = fields.find(p_name);
if (result)
return result->value();
if (fields_fetched)
return NULL;
MonoClassField *raw_field = mono_class_get_field_from_name(mono_class, String(p_name).utf8().get_data());
if (raw_field) {
GDMonoField *field = memnew(GDMonoField(raw_field, this));
fields.insert(p_name, field);
return field;
}
return NULL;
}
const Vector<GDMonoField *> &GDMonoClass::get_all_fields() {
if (fields_fetched)
return fields_list;
void *iter = NULL;
MonoClassField *raw_field = NULL;
while ((raw_field = mono_class_get_fields(mono_class, &iter)) != NULL) {
StringName name = String::utf8(mono_field_get_name(raw_field));
Map<StringName, GDMonoField *>::Element *match = fields.find(name);
if (match) {
fields_list.push_back(match->get());
} else {
GDMonoField *field = memnew(GDMonoField(raw_field, this));
fields.insert(name, field);
fields_list.push_back(field);
}
}
fields_fetched = true;
return fields_list;
}
GDMonoProperty *GDMonoClass::get_property(const StringName &p_name) {
Map<StringName, GDMonoProperty *>::Element *result = properties.find(p_name);
if (result)
return result->value();
if (properties_fetched)
return NULL;
MonoProperty *raw_property = mono_class_get_property_from_name(mono_class, String(p_name).utf8().get_data());
if (raw_property) {
GDMonoProperty *property = memnew(GDMonoProperty(raw_property, this));
properties.insert(p_name, property);
return property;
}
return NULL;
}
const Vector<GDMonoProperty *> &GDMonoClass::get_all_properties() {
if (properties_fetched)
return properties_list;
void *iter = NULL;
MonoProperty *raw_property = NULL;
while ((raw_property = mono_class_get_properties(mono_class, &iter)) != NULL) {
StringName name = String::utf8(mono_property_get_name(raw_property));
Map<StringName, GDMonoProperty *>::Element *match = properties.find(name);
if (match) {
properties_list.push_back(match->get());
} else {
GDMonoProperty *property = memnew(GDMonoProperty(raw_property, this));
properties.insert(name, property);
properties_list.push_back(property);
}
}
properties_fetched = true;
return properties_list;
}
const Vector<GDMonoClass *> &GDMonoClass::get_all_delegates() {
if (delegates_fetched)
return delegates_list;
void *iter = NULL;
MonoClass *raw_class = NULL;
while ((raw_class = mono_class_get_nested_types(mono_class, &iter)) != NULL) {
if (mono_class_is_delegate(raw_class)) {
StringName name = String::utf8(mono_class_get_name(raw_class));
Map<StringName, GDMonoClass *>::Element *match = delegates.find(name);
if (match) {
delegates_list.push_back(match->get());
} else {
GDMonoClass *delegate = memnew(GDMonoClass(String::utf8(mono_class_get_namespace(raw_class)), String::utf8(mono_class_get_name(raw_class)), raw_class, assembly));
delegates.insert(name, delegate);
delegates_list.push_back(delegate);
}
}
}
delegates_fetched = true;
return delegates_list;
}
const Vector<GDMonoMethod *> &GDMonoClass::get_all_methods() {
if (!method_list_fetched) {
void *iter = NULL;
MonoMethod *raw_method = NULL;
while ((raw_method = mono_class_get_methods(get_mono_ptr(), &iter)) != NULL) {
method_list.push_back(memnew(GDMonoMethod(String::utf8(mono_method_get_name(raw_method)), raw_method)));
}
method_list_fetched = true;
}
return method_list;
}
GDMonoClass::GDMonoClass(const StringName &p_namespace, const StringName &p_name, MonoClass *p_class, GDMonoAssembly *p_assembly) {
namespace_name = p_namespace;
class_name = p_name;
mono_class = p_class;
assembly = p_assembly;
attrs_fetched = false;
attributes = NULL;
methods_fetched = false;
method_list_fetched = false;
fields_fetched = false;
properties_fetched = false;
delegates_fetched = false;
}
GDMonoClass::~GDMonoClass() {
if (attributes) {
mono_custom_attrs_free(attributes);
}
for (Map<StringName, GDMonoField *>::Element *E = fields.front(); E; E = E->next()) {
memdelete(E->value());
}
for (Map<StringName, GDMonoProperty *>::Element *E = properties.front(); E; E = E->next()) {
memdelete(E->value());
}
{
// Ugly workaround...
// We may have duplicated values, because we redirect snake_case methods to PascalCasel (only Godot API methods).
// This way, we end with both the snake_case name and the PascalCasel name paired with the same method.
// Therefore, we must avoid deleting the same pointer twice.
int offset = 0;
Vector<GDMonoMethod *> deleted_methods;
deleted_methods.resize(methods.size());
const MethodKey *k = NULL;
while ((k = methods.next(k))) {
GDMonoMethod *method = methods.get(*k);
if (method) {
for (int i = 0; i < offset; i++) {
if (deleted_methods[i] == method) {
// Already deleted
goto already_deleted;
}
}
deleted_methods.write[offset] = method;
++offset;
memdelete(method);
}
already_deleted:;
}
methods.clear();
}
for (int i = 0; i < method_list.size(); ++i) {
memdelete(method_list[i]);
}
}
|
/******************************************************************************
* Copyright 2018 The Baidu Authors. 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 "CSocketConnector.h"
#include "CCarLifeLog.h"
using namespace std;
CSocketConnector::CSocketConnector(string serverIP, u32 port, string interfaceName)
{
if(serverIP.find(":",0)!=string::npos) {
CCarLifeLog::carLifeLogLnWithPrefix("iSockset=&socketv6");
iSocket=&socketv6;
}else{
CCarLifeLog::carLifeLogLnWithPrefix("iSockset=&socket");
iSocket=&socket;
}
setConnectStatus(false);
mdServerIP = serverIP;
mdServerPort = port;
networkCardInterfaceName=interfaceName;
}
CSocketConnector::~CSocketConnector()
{
}
bool CSocketConnector::getConnectStatus()
{
return isConnected;
}
bool CSocketConnector::connectToServer()
{
if ( ! iSocket->create() )
{
CCarLifeLog::carLifeLogLnWithPrefix("socket.create fail!");
return false;
}
if ( ! iSocket->connect ( mdServerIP, mdServerPort, networkCardInterfaceName ) )
{
CCarLifeLog::carLifeLogWithPrefix("mdServerIP: ");
CCarLifeLog::carLifeLog(mdServerIP);
CCarLifeLog::carLifeLog(" mdServerPort: ");
CCarLifeLog::carLifeLog(mdServerPort);
CCarLifeLog::carLifeLog("\n");
CCarLifeLog::carLifeLogLnWithPrefix("socket.connect fail!");
return false;
}
setConnectStatus(true);
return true;
}
|
#include "PbbamInternalConfig.h"
#include <pbbam/ZmwTypeMap.h>
namespace PacBio {
namespace BAM {
// clang-format off
std::map<char, ZmwType> ZmwTypeMap::ParseChar
{
{ 'C' , ZmwType::CONTROL },
{ 'M' , ZmwType::MALFORMED },
{ 'N' , ZmwType::NORMAL },
{ 'S' , ZmwType::SENTINEL }
};
// clang-format on
} // namespace BAM
} // namespace PacBio
|
#include <Hazel.h>
class Sandbox : public Hazel::Application
{
public:
Sandbox()
{
}
~Sandbox()
{
}
private:
};
Hazel::Application* Hazel::CreateApplication()
{
return new Sandbox();
}
|
#include "stream.h"
#include <library/unittest/registar.h>
#include <util/stream/zlib.h>
Y_UNIT_TEST_SUITE(THttpTestMedium) {
Y_UNIT_TEST(TestCodings2) {
TStringBuf data = "aaaaaaaaaaaaaaaaaaaaaaa";
for (auto codec : SupportedCodings()) {
if (codec == AsStringBuf("z-zlib-0")) {
continue;
}
if (codec == AsStringBuf("z-null")) {
continue;
}
TString s;
{
TStringOutput so(s);
THttpOutput ho(&so);
TBufferedOutput bo(&ho, 10000);
bo << "HTTP/1.1 200 Ok\r\n"
<< "Connection: close\r\n"
<< "Content-Encoding: " << codec << "\r\n\r\n";
for (size_t i = 0; i < 100; ++i) {
bo << data;
}
}
try {
UNIT_ASSERT(s.size() > 10);
UNIT_ASSERT(s.find(data) == TString::npos);
} catch (...) {
Cerr << codec << " " << s << Endl;
throw;
}
{
TStringInput si(s);
THttpInput hi(&si);
auto res = hi.ReadAll();
UNIT_ASSERT(res.find(data) == 0);
}
}
}
} // THttpTestMedium suite
|
/*
The MIT License (MIT)
Copyright (c) 2014 Anatoli Steinmark
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.
*/
#ifndef RPGSS_SCRIPT_GRAPHICS_MODULE_IMAGEWRAPPER_HPP_INCLUDED
#define RPGSS_SCRIPT_GRAPHICS_MODULE_IMAGEWRAPPER_HPP_INCLUDED
#include "../../graphics/Image.hpp"
#include "../lua_include.hpp"
namespace rpgss {
namespace script {
namespace graphics_module {
class ImageWrapper {
public:
static void Push(lua_State* L, graphics::Image* image);
static bool Is(lua_State* L, int index);
static graphics::Image* Get(lua_State* L, int index);
static graphics::Image* GetOpt(lua_State* L, int index);
explicit ImageWrapper(graphics::Image* ptr);
int get_width() const;
int get_height() const;
int __len(lua_State* L);
int getDimensions(lua_State* L);
int getBlendMode(lua_State* L);
int setBlendMode(lua_State* L);
int getClipRect(lua_State* L);
int setClipRect(lua_State* L);
int copyPixels(lua_State* L);
int copyRect(lua_State* L);
int resize(lua_State* L);
int setAlpha(lua_State* L);
int clear(lua_State* L);
int grey(lua_State* L);
int flip(lua_State* L);
int rotate(lua_State* L);
int getPixel(lua_State* L);
int setPixel(lua_State* L);
int drawPoint(lua_State* L);
int drawLine(lua_State* L);
int drawRectangle(lua_State* L);
int drawCircle(lua_State* L);
int drawTriangle(lua_State* L);
int draw(lua_State* L);
int drawq(lua_State* L);
int drawText(lua_State* L);
int drawWindow(lua_State* L);
private:
graphics::Image::Ptr This;
};
} // namespace graphics_module
} // namespace script
} // namespace rpgss
#endif // RPGSS_SCRIPT_GRAPHICS_MODULE_IMAGEWRAPPER_HPP_INCLUDED
|
//--------------------------------------------------------------------------------------
// File: NBodyGravityCS11.cpp
//
// Demonstrates how to use Compute Shader to do n-body gravity computation
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "DXUTgui.h"
#include "SDKmisc.h"
#include "DXUTcamera.h"
#include "DXUTsettingsdlg.h"
#include <commdlg.h>
#include "resource.h"
#include "WaitDlg.h"
#pragma warning( disable : 4100 )
using namespace DirectX;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
CModelViewerCamera g_Camera; // A model viewing camera
CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog
CDXUTDialog g_HUD; // dialog for standard controls
CDXUTDialog g_SampleUI; // dialog for sample specific controls
CDXUTTextHelper* g_pTxtHelper = nullptr;
ID3D11VertexShader* g_pRenderParticlesVS = nullptr;
ID3D11GeometryShader* g_pRenderParticlesGS = nullptr;
ID3D11PixelShader* g_pRenderParticlesPS = nullptr;
ID3D11SamplerState* g_pSampleStateLinear = nullptr;
ID3D11BlendState* g_pBlendingStateParticle = nullptr;
ID3D11DepthStencilState* g_pDepthStencilState = nullptr;
ID3D11ComputeShader* g_pCalcCS = nullptr;
ID3D11Buffer* g_pcbCS = nullptr;
ID3D11Buffer* g_pParticlePosVelo0 = nullptr;
ID3D11Buffer* g_pParticlePosVelo1 = nullptr;
ID3D11ShaderResourceView* g_pParticlePosVeloRV0 = nullptr;
ID3D11ShaderResourceView* g_pParticlePosVeloRV1 = nullptr;
ID3D11UnorderedAccessView* g_pParticlePosVeloUAV0 = nullptr;
ID3D11UnorderedAccessView* g_pParticlePosVeloUAV1 = nullptr;
ID3D11Buffer* g_pParticleBuffer = nullptr;
ID3D11InputLayout* g_pParticleVertexLayout = nullptr;
ID3D11Buffer* g_pcbGS = nullptr;
ID3D11ShaderResourceView* g_pParticleTexRV = nullptr;
const float g_fSpread = 400.0f;
struct PARTICLE_VERTEX
{
XMFLOAT4 Color;
};
#define MAX_PARTICLES 10000 // the number of particles in the n-body simulation
struct CB_GS
{
XMFLOAT4X4 m_WorldViewProj;
XMFLOAT4X4 m_InvView;
};
struct CB_CS
{
UINT param[4];
float paramf[4];
};
struct PARTICLE
{
XMFLOAT4 pos;
XMFLOAT4 velo;
};
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
#define IDC_TOGGLEFULLSCREEN 1
#define IDC_TOGGLEREF 3
#define IDC_CHANGEDEVICE 4
#define IDC_RESETPARTICLES 5
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext );
void CALLBACK OnD3D11DestroyDevice( void* pUserContext );
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
float fElapsedTime, void* pUserContext );
void InitApp();
void RenderText();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable );
DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice );
DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain );
DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender );
DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain );
DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice );
InitApp();
DXUTInit( true, true ); // Use this line instead to try to create a hardware device
DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen
DXUTCreateWindow( L"NBodyGravityCS11" );
DXUTCreateDevice( D3D_FEATURE_LEVEL_10_0, true, 800, 600 );
DXUTMainLoop(); // Enter into the DXUT render loop
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
g_D3DSettingsDlg.Init( &g_DialogResourceManager );
g_HUD.Init( &g_DialogResourceManager );
g_SampleUI.Init( &g_DialogResourceManager );
g_HUD.SetCallback( OnGUIEvent ); int iY = 10;
g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, iY, 170, 23 );
g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 0, iY += 26, 170, 23, VK_F3 );
g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 0, iY += 26, 170, 23, VK_F2 );
g_HUD.AddButton( IDC_RESETPARTICLES, L"Reset particles", 0, iY += 26, 170, 22, VK_F2 );
g_SampleUI.SetCallback( OnGUIEvent );
}
//--------------------------------------------------------------------------------------
HRESULT CreateParticleBuffer( ID3D11Device* pd3dDevice )
{
HRESULT hr = S_OK;
D3D11_BUFFER_DESC vbdesc =
{
MAX_PARTICLES * sizeof( PARTICLE_VERTEX ),
D3D11_USAGE_DEFAULT,
D3D11_BIND_VERTEX_BUFFER,
0,
0
};
D3D11_SUBRESOURCE_DATA vbInitData;
ZeroMemory( &vbInitData, sizeof( D3D11_SUBRESOURCE_DATA ) );
auto pVertices = new PARTICLE_VERTEX[ MAX_PARTICLES ];
if( !pVertices )
return E_OUTOFMEMORY;
for( UINT i = 0; i < MAX_PARTICLES; i++ )
{
pVertices[i].Color = XMFLOAT4( 1, 1, 0.2f, 1 );
}
vbInitData.pSysMem = pVertices;
V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, &vbInitData, &g_pParticleBuffer ) );
DXUT_SetDebugName( g_pParticleBuffer, "Particles" );
SAFE_DELETE_ARRAY( pVertices );
return hr;
}
//--------------------------------------------------------------------------------------
float RPercent()
{
float ret = ( float )( ( rand() % 10000 ) - 5000 );
return ret / 5000.0f;
}
//--------------------------------------------------------------------------------------
// This helper function loads a group of particles
//--------------------------------------------------------------------------------------
void LoadParticles( PARTICLE* pParticles,
XMFLOAT3 Center, XMFLOAT4 Velocity, float Spread, UINT NumParticles )
{
XMVECTOR vCenter = XMLoadFloat3( &Center );
for( UINT i = 0; i < NumParticles; i++ )
{
XMVECTOR vDelta = XMVectorReplicate( Spread );
while( XMVectorGetX( XMVector3LengthSq( vDelta ) ) > Spread * Spread )
{
vDelta = XMVectorSet( RPercent() * Spread, RPercent() * Spread, RPercent() * Spread, 0.f );
}
XMVECTOR vPos = XMVectorAdd( vCenter, vDelta );
XMStoreFloat3( reinterpret_cast<XMFLOAT3*>( &pParticles[i].pos ), vPos );
pParticles[i].pos.w = 10000.0f * 10000.0f;
pParticles[i].velo = Velocity;
}
}
//--------------------------------------------------------------------------------------
HRESULT CreateParticlePosVeloBuffers( ID3D11Device* pd3dDevice )
{
HRESULT hr = S_OK;
D3D11_BUFFER_DESC desc;
ZeroMemory( &desc, sizeof(desc) );
desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE;
desc.ByteWidth = MAX_PARTICLES * sizeof(PARTICLE);
desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
desc.StructureByteStride = sizeof(PARTICLE);
desc.Usage = D3D11_USAGE_DEFAULT;
// Initialize the data in the buffers
PARTICLE* pData1 = new PARTICLE[ MAX_PARTICLES ];
if( !pData1 )
return E_OUTOFMEMORY;
srand( (unsigned int)GetTickCount64() );
#if 1
// Disk Galaxy Formation
float fCenterSpread = g_fSpread * 0.50f;
LoadParticles( pData1,
XMFLOAT3( fCenterSpread, 0, 0 ), XMFLOAT4( 0, 0, -20, 1/10000.0f / 10000.0f ),
g_fSpread, MAX_PARTICLES / 2 );
LoadParticles( &pData1[MAX_PARTICLES / 2],
XMFLOAT3( -fCenterSpread, 0, 0 ), XMFLOAT4( 0, 0, 20, 1/10000.0f / 10000.0f ),
g_fSpread, MAX_PARTICLES / 2 );
#else
// Disk Galaxy Formation with impacting third cluster
LoadParticles( pData1,
XMFLOAT3(g_fSpread,0,0), XMFLOAT4(0,0,-8,1/10000.0f / 10000.0f),
g_fSpread, MAX_PARTICLES/3 );
LoadParticles( &pData1[MAX_PARTICLES/3],
XMFLOAT3(-g_fSpread,0,0), XMFLOAT4(0,0,8,1/10000.0f / 10000.0f),
g_fSpread, MAX_PARTICLES/2 );
LoadParticles( &pData1[2*(MAX_PARTICLES/3)],
XMFLOAT3(0,0,g_fSpread*15.0f), XMFLOAT4(0,0,-60,1/10000.0f / 10000.0f),
g_fSpread, MAX_PARTICLES - 2*(MAX_PARTICLES/3) );
#endif
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pData1;
V_RETURN( pd3dDevice->CreateBuffer( &desc, &InitData, &g_pParticlePosVelo0 ) );
V_RETURN( pd3dDevice->CreateBuffer( &desc, &InitData, &g_pParticlePosVelo1 ) );
DXUT_SetDebugName( g_pParticlePosVelo0, "PosVelo0" );
DXUT_SetDebugName( g_pParticlePosVelo1, "PosVelo1" );
SAFE_DELETE_ARRAY( pData1 );
D3D11_SHADER_RESOURCE_VIEW_DESC DescRV;
ZeroMemory( &DescRV, sizeof( DescRV ) );
DescRV.Format = DXGI_FORMAT_UNKNOWN;
DescRV.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
DescRV.Buffer.FirstElement = 0;
DescRV.Buffer.NumElements = desc.ByteWidth / desc.StructureByteStride;
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pParticlePosVelo0, &DescRV, &g_pParticlePosVeloRV0 ) );
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pParticlePosVelo1, &DescRV, &g_pParticlePosVeloRV1 ) );
DXUT_SetDebugName( g_pParticlePosVeloRV0, "PosVelo0 SRV" );
DXUT_SetDebugName( g_pParticlePosVeloRV1, "PosVelo1 SRV" );
D3D11_UNORDERED_ACCESS_VIEW_DESC DescUAV;
ZeroMemory( &DescUAV, sizeof(D3D11_UNORDERED_ACCESS_VIEW_DESC) );
DescUAV.Format = DXGI_FORMAT_UNKNOWN;
DescUAV.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
DescUAV.Buffer.FirstElement = 0;
DescUAV.Buffer.NumElements = desc.ByteWidth / desc.StructureByteStride;
V_RETURN( pd3dDevice->CreateUnorderedAccessView( g_pParticlePosVelo0, &DescUAV, &g_pParticlePosVeloUAV0 ) );
V_RETURN( pd3dDevice->CreateUnorderedAccessView( g_pParticlePosVelo1, &DescUAV, &g_pParticlePosVeloUAV1 ) );
DXUT_SetDebugName( g_pParticlePosVeloUAV0, "PosVelo0 UAV" );
DXUT_SetDebugName( g_pParticlePosVeloUAV1, "PosVelo1 UAV" );
return hr;
}
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
HRESULT hr;
auto pd3dImmediateContext = DXUTGetD3D11DeviceContext();
int dimx = int(ceil(MAX_PARTICLES/128.0f));
{
pd3dImmediateContext->CSSetShader( g_pCalcCS, nullptr, 0 );
// For CS input
ID3D11ShaderResourceView* aRViews[ 1 ] = { g_pParticlePosVeloRV0 };
pd3dImmediateContext->CSSetShaderResources( 0, 1, aRViews );
// For CS output
ID3D11UnorderedAccessView* aUAViews[ 1 ] = { g_pParticlePosVeloUAV1 };
pd3dImmediateContext->CSSetUnorderedAccessViews( 0, 1, aUAViews, (UINT*)(&aUAViews) );
// For CS constant buffer
D3D11_MAPPED_SUBRESOURCE MappedResource;
V( pd3dImmediateContext->Map( g_pcbCS, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
auto pcbCS = reinterpret_cast<CB_CS*>( MappedResource.pData );
pcbCS->param[0] = MAX_PARTICLES;
pcbCS->param[1] = dimx;
pcbCS->paramf[0] = 0.1f;
pcbCS->paramf[1] = 1;
pd3dImmediateContext->Unmap( g_pcbCS, 0 );
ID3D11Buffer* ppCB[1] = { g_pcbCS };
pd3dImmediateContext->CSSetConstantBuffers( 0, 1, ppCB );
// Run the CS
pd3dImmediateContext->Dispatch( dimx, 1, 1 );
// Unbind resources for CS
ID3D11UnorderedAccessView* ppUAViewNULL[1] = { nullptr };
pd3dImmediateContext->CSSetUnorderedAccessViews( 0, 1, ppUAViewNULL, (UINT*)(&aUAViews) );
ID3D11ShaderResourceView* ppSRVNULL[1] = { nullptr };
pd3dImmediateContext->CSSetShaderResources( 0, 1, ppSRVNULL );
//pd3dImmediateContext->CSSetShader( nullptr, nullptr, 0 );
std::swap( g_pParticlePosVelo0, g_pParticlePosVelo1 );
std::swap( g_pParticlePosVeloRV0, g_pParticlePosVeloRV1 );
std::swap( g_pParticlePosVeloUAV0, g_pParticlePosVeloUAV1 );
}
// Update the camera's position based on user input
g_Camera.FrameMove( fElapsedTime );
}
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext )
{
// Pass messages to dialog resource manager calls so GUI state is updated correctly
*pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass messages to settings dialog if its active
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
return 0;
}
// Give the dialogs a chance to handle the message first
*pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
*pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass all windows messages to camera so it can respond to user input
g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
return 0;
}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
switch( nControlID )
{
case IDC_TOGGLEFULLSCREEN:
DXUTToggleFullScreen(); break;
case IDC_TOGGLEREF:
DXUTToggleREF(); break;
case IDC_CHANGEDEVICE:
g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break;
case IDC_RESETPARTICLES:
{
SAFE_RELEASE(g_pParticlePosVelo0);
SAFE_RELEASE(g_pParticlePosVelo1);
SAFE_RELEASE(g_pParticlePosVeloRV0);
SAFE_RELEASE(g_pParticlePosVeloRV1);
SAFE_RELEASE(g_pParticlePosVeloUAV0);
SAFE_RELEASE(g_pParticlePosVeloUAV1);
CreateParticlePosVeloBuffers(DXUTGetD3D11Device());
break;
}
}
}
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
// reject any device which doesn't support CS4x
if ( DeviceInfo->ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x == FALSE )
return false;
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
HRESULT hr;
static bool bFirstOnCreateDevice = true;
// Warn the user that in order to support CS4x, a non-hardware device has been created, continue or quit?
if ( DXUTGetDeviceSettings().d3d11.DriverType != D3D_DRIVER_TYPE_HARDWARE && bFirstOnCreateDevice )
{
if ( MessageBox( 0, L"CS4x capability is missing. "\
L"In order to continue, a non-hardware device has been created, "\
L"it will be very slow, continue?", L"Warning", MB_ICONEXCLAMATION | MB_YESNO ) != IDYES )
return E_FAIL;
}
CWaitDlg CompilingShadersDlg;
CompilingShadersDlg.ShowDialog( L"Compiling Shaders..." );
bFirstOnCreateDevice = false;
D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS ho;
V_RETURN( pd3dDevice->CheckFeatureSupport( D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho) ) );
auto pd3dImmediateContext = DXUTGetD3D11DeviceContext();
V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );
ID3DBlob* pBlobRenderParticlesVS = nullptr;
ID3DBlob* pBlobRenderParticlesGS = nullptr;
ID3DBlob* pBlobRenderParticlesPS = nullptr;
ID3DBlob* pBlobCalcCS = nullptr;
// Create the shaders
V_RETURN( DXUTCompileFromFile( L"ParticleDraw.hlsl", nullptr, "VSParticleDraw", "vs_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobRenderParticlesVS ) );
V_RETURN( DXUTCompileFromFile( L"ParticleDraw.hlsl", nullptr, "GSParticleDraw", "gs_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobRenderParticlesGS ) );
V_RETURN( DXUTCompileFromFile( L"ParticleDraw.hlsl", nullptr, "PSParticleDraw", "ps_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobRenderParticlesPS ) );
V_RETURN( DXUTCompileFromFile( L"NBodyGravityCS11.hlsl", nullptr, "CSMain", "cs_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobCalcCS ) );
V_RETURN( pd3dDevice->CreateVertexShader( pBlobRenderParticlesVS->GetBufferPointer(), pBlobRenderParticlesVS->GetBufferSize(), nullptr, &g_pRenderParticlesVS ) );
DXUT_SetDebugName( g_pRenderParticlesVS, "VSParticleDraw" );
V_RETURN( pd3dDevice->CreateGeometryShader( pBlobRenderParticlesGS->GetBufferPointer(), pBlobRenderParticlesGS->GetBufferSize(), nullptr, &g_pRenderParticlesGS ) );
DXUT_SetDebugName( g_pRenderParticlesGS, "GSParticleDraw" );
V_RETURN( pd3dDevice->CreatePixelShader( pBlobRenderParticlesPS->GetBufferPointer(), pBlobRenderParticlesPS->GetBufferSize(), nullptr, &g_pRenderParticlesPS ) );
DXUT_SetDebugName( g_pRenderParticlesPS, "PSParticleDraw" );
V_RETURN( pd3dDevice->CreateComputeShader( pBlobCalcCS->GetBufferPointer(), pBlobCalcCS->GetBufferSize(), nullptr, &g_pCalcCS ) );
DXUT_SetDebugName( g_pCalcCS, "CSMain" );
// Create our vertex input layout
const D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
V_RETURN( pd3dDevice->CreateInputLayout( layout, sizeof( layout ) / sizeof( layout[0] ),
pBlobRenderParticlesVS->GetBufferPointer(), pBlobRenderParticlesVS->GetBufferSize(), &g_pParticleVertexLayout ) );
DXUT_SetDebugName( g_pParticleVertexLayout, "Particles" );
SAFE_RELEASE( pBlobRenderParticlesVS );
SAFE_RELEASE( pBlobRenderParticlesGS );
SAFE_RELEASE( pBlobRenderParticlesPS );
SAFE_RELEASE( pBlobCalcCS );
V_RETURN( CreateParticleBuffer( pd3dDevice ) );
V_RETURN( CreateParticlePosVeloBuffers( pd3dDevice ) );
// Setup constant buffer
D3D11_BUFFER_DESC Desc;
Desc.Usage = D3D11_USAGE_DYNAMIC;
Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
Desc.MiscFlags = 0;
Desc.ByteWidth = sizeof( CB_GS );
V_RETURN( pd3dDevice->CreateBuffer( &Desc, nullptr, &g_pcbGS ) );
DXUT_SetDebugName( g_pcbGS, "CB_GS" );
Desc.ByteWidth = sizeof( CB_CS );
V_RETURN( pd3dDevice->CreateBuffer( &Desc, nullptr, &g_pcbCS ) );
DXUT_SetDebugName( g_pcbCS, "CB_CS" );
// Load the Particle Texture
V_RETURN( DXUTCreateShaderResourceViewFromFile( pd3dDevice, L"misc\\Particle.dds", &g_pParticleTexRV ) );
D3D11_SAMPLER_DESC SamplerDesc;
ZeroMemory( &SamplerDesc, sizeof(SamplerDesc) );
SamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
V_RETURN( pd3dDevice->CreateSamplerState( &SamplerDesc, &g_pSampleStateLinear ) );
DXUT_SetDebugName( g_pSampleStateLinear, "Linear" );
D3D11_BLEND_DESC BlendStateDesc;
ZeroMemory( &BlendStateDesc, sizeof(BlendStateDesc) );
BlendStateDesc.RenderTarget[0].BlendEnable = TRUE;
BlendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
BlendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
BlendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;
BlendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
BlendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
BlendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
BlendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F;
V_RETURN( pd3dDevice->CreateBlendState( &BlendStateDesc, &g_pBlendingStateParticle ) );
DXUT_SetDebugName( g_pBlendingStateParticle, "Blending" );
D3D11_DEPTH_STENCIL_DESC DepthStencilDesc;
ZeroMemory( &DepthStencilDesc, sizeof(DepthStencilDesc) );
DepthStencilDesc.DepthEnable = FALSE;
DepthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
pd3dDevice->CreateDepthStencilState( &DepthStencilDesc, &g_pDepthStencilState );
DXUT_SetDebugName( g_pDepthStencilState, "DepthOff" );
// Setup the camera's view parameters
XMVECTOR vecEye = XMVectorSet( -g_fSpread * 2, g_fSpread * 4, -g_fSpread * 3, 0.f );
g_Camera.SetViewParams( vecEye, g_XMZero );
CompilingShadersDlg.DestroyDialog();
return S_OK;
}
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
// Setup the camera's projection parameters
float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
g_Camera.SetProjParams( XM_PI / 4, fAspectRatio, 10.0f, 500000.0f );
g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
g_Camera.SetButtonMasks( 0, MOUSE_WHEEL, MOUSE_LEFT_BUTTON | MOUSE_MIDDLE_BUTTON | MOUSE_RIGHT_BUTTON );
g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
g_HUD.SetSize( 170, 170 );
g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
g_SampleUI.SetSize( 170, 300 );
return hr;
}
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext )
{
g_DialogResourceManager.OnD3D11ReleasingSwapChain();
}
//--------------------------------------------------------------------------------------
void RenderText()
{
g_pTxtHelper->Begin();
g_pTxtHelper->SetInsertionPos( 2, 0 );
g_pTxtHelper->SetForegroundColor( Colors::Yellow );
g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );
g_pTxtHelper->End();
}
//--------------------------------------------------------------------------------------
bool RenderParticles( ID3D11DeviceContext* pd3dImmediateContext, CXMMATRIX mView, CXMMATRIX mProj )
{
ID3D11BlendState *pBlendState0 = nullptr;
ID3D11DepthStencilState *pDepthStencilState0 = nullptr;
UINT SampleMask0, StencilRef0;
XMFLOAT4 BlendFactor0;
pd3dImmediateContext->OMGetBlendState( &pBlendState0, &BlendFactor0.x, &SampleMask0 );
pd3dImmediateContext->OMGetDepthStencilState( &pDepthStencilState0, &StencilRef0 );
pd3dImmediateContext->VSSetShader( g_pRenderParticlesVS, nullptr, 0 );
pd3dImmediateContext->GSSetShader( g_pRenderParticlesGS, nullptr, 0 );
pd3dImmediateContext->PSSetShader( g_pRenderParticlesPS, nullptr, 0 );
pd3dImmediateContext->IASetInputLayout( g_pParticleVertexLayout );
// Set IA parameters
ID3D11Buffer* pBuffers[1] = { g_pParticleBuffer };
UINT stride[1] = { sizeof( PARTICLE_VERTEX ) };
UINT offset[1] = { 0 };
pd3dImmediateContext->IASetVertexBuffers( 0, 1, pBuffers, stride, offset );
pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_POINTLIST );
ID3D11ShaderResourceView* aRViews[ 1 ] = { g_pParticlePosVeloRV0 };
pd3dImmediateContext->VSSetShaderResources( 0, 1, aRViews );
D3D11_MAPPED_SUBRESOURCE MappedResource;
pd3dImmediateContext->Map( g_pcbGS, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource);
auto pCBGS = reinterpret_cast<CB_GS*>( MappedResource.pData );
XMStoreFloat4x4( &pCBGS->m_WorldViewProj, XMMatrixMultiply( mView, mProj ) );
XMStoreFloat4x4( &pCBGS->m_InvView, XMMatrixInverse( nullptr, mView ) );
pd3dImmediateContext->Unmap( g_pcbGS, 0 );
pd3dImmediateContext->GSSetConstantBuffers( 0, 1, &g_pcbGS );
pd3dImmediateContext->PSSetShaderResources( 0, 1, &g_pParticleTexRV );
pd3dImmediateContext->PSSetSamplers( 0, 1, &g_pSampleStateLinear );
float bf[] = { 0.f, 0.f, 0.f, 0.f };
pd3dImmediateContext->OMSetBlendState( g_pBlendingStateParticle, bf, 0xFFFFFFFF );
pd3dImmediateContext->OMSetDepthStencilState( g_pDepthStencilState, 0 );
pd3dImmediateContext->Draw( MAX_PARTICLES, 0 );
ID3D11ShaderResourceView* ppSRVNULL[1] = { nullptr };
pd3dImmediateContext->VSSetShaderResources( 0, 1, ppSRVNULL );
pd3dImmediateContext->PSSetShaderResources( 0, 1, ppSRVNULL );
/*ID3D11Buffer* ppBufNULL[1] = { nullptr };
pd3dImmediateContext->GSSetConstantBuffers( 0, 1, ppBufNULL );*/
pd3dImmediateContext->GSSetShader( nullptr, nullptr, 0 );
pd3dImmediateContext->OMSetBlendState( pBlendState0, &BlendFactor0.x, SampleMask0 ); SAFE_RELEASE(pBlendState0);
pd3dImmediateContext->OMSetDepthStencilState( pDepthStencilState0, StencilRef0 ); SAFE_RELEASE(pDepthStencilState0);
return true;
}
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
float fElapsedTime, void* pUserContext )
{
// If the settings dialog is being shown, then render it instead of rendering the app's scene
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.OnRender( fElapsedTime );
return;
}
ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView();
pd3dImmediateContext->ClearRenderTargetView( pRTV, Colors::Black );
ID3D11DepthStencilView* pDSV = DXUTGetD3D11DepthStencilView();
pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 );
// Get the projection & view matrix from the camera class
XMMATRIX mProj = g_Camera.GetProjMatrix();
XMMATRIX mView = g_Camera.GetViewMatrix();
// Render the particles
RenderParticles( pd3dImmediateContext, mView, mProj );
DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
g_HUD.OnRender( fElapsedTime );
g_SampleUI.OnRender( fElapsedTime );
RenderText();
DXUT_EndPerfEvent();
// The following could be used to output fps stats into debug output window,
// which is useful because you can then turn off all UI rendering as they cloud performance
/*static DWORD dwTimefirst = GetTickCount();
if ( GetTickCount() - dwTimefirst > 5000 )
{
OutputDebugString( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
OutputDebugString( L"\n" );
dwTimefirst = GetTickCount();
}*/
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11DestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D11DestroyDevice();
g_D3DSettingsDlg.OnD3D11DestroyDevice();
DXUTGetGlobalResourceCache().OnDestroyDevice();
SAFE_DELETE( g_pTxtHelper );
SAFE_RELEASE( g_pParticleBuffer );
SAFE_RELEASE( g_pParticleVertexLayout );
SAFE_RELEASE( g_pParticlePosVelo0 );
SAFE_RELEASE( g_pParticlePosVelo1 );
SAFE_RELEASE( g_pParticlePosVeloRV0 );
SAFE_RELEASE( g_pParticlePosVeloRV1 );
SAFE_RELEASE( g_pParticlePosVeloUAV0 );
SAFE_RELEASE( g_pParticlePosVeloUAV1 );
SAFE_RELEASE( g_pcbGS );
SAFE_RELEASE( g_pcbCS );
SAFE_RELEASE( g_pParticleTexRV );
SAFE_RELEASE( g_pRenderParticlesVS );
SAFE_RELEASE( g_pRenderParticlesGS );
SAFE_RELEASE( g_pRenderParticlesPS );
SAFE_RELEASE( g_pCalcCS );
SAFE_RELEASE( g_pSampleStateLinear );
SAFE_RELEASE( g_pBlendingStateParticle );
SAFE_RELEASE( g_pDepthStencilState );
}
|
#include "pch.h"
#include "SharedAdaptiveCard.h"
#include "ParseUtil.h"
#include "ShowCardAction.h"
#include "ParseContext.h"
using namespace AdaptiveSharedNamespace;
ShowCardAction::ShowCardAction() : BaseActionElement(ActionType::ShowCard)
{
PopulateKnownPropertiesSet();
}
Json::Value ShowCardAction::SerializeToJsonValue() const
{
Json::Value root = BaseActionElement::SerializeToJsonValue();
root[AdaptiveCardSchemaKeyToString(AdaptiveCardSchemaKey::Card)] = GetCard()->SerializeToJsonValue();
return root;
}
std::shared_ptr<AdaptiveCard> ShowCardAction::GetCard() const
{
return m_card;
}
void ShowCardAction::SetCard(const std::shared_ptr<AdaptiveCard> card)
{
m_card = card;
}
void ShowCardAction::SetLanguage(const std::string& value)
{
// If the card inside doesn't specify language, propagate
if (m_card->GetLanguage().empty())
{
m_card->SetLanguage(value);
}
}
std::shared_ptr<BaseActionElement> ShowCardActionParser::Deserialize(ParseContext& context, const Json::Value& json)
{
std::shared_ptr<ShowCardAction> showCardAction = BaseActionElement::Deserialize<ShowCardAction>(json);
std::string propertyName = AdaptiveCardSchemaKeyToString(AdaptiveCardSchemaKey::Card);
auto parseResult = AdaptiveCard::Deserialize(json.get(propertyName, Json::Value()), "", context);
auto showCardWarnings = parseResult->GetWarnings();
auto warningsEnd = context.warnings.insert(context.warnings.end(), showCardWarnings.begin(), showCardWarnings.end());
showCardAction->SetCard(parseResult->GetAdaptiveCard());
return showCardAction;
}
std::shared_ptr<BaseActionElement>
ShowCardActionParser::DeserializeFromString(ParseContext& context, const std::string& jsonString)
{
return ShowCardActionParser::Deserialize(context, ParseUtil::GetJsonValueFromString(jsonString));
}
void ShowCardAction::PopulateKnownPropertiesSet()
{
m_knownProperties.insert({AdaptiveCardSchemaKeyToString(AdaptiveCardSchemaKey::Card)});
}
void ShowCardAction::GetResourceInformation(std::vector<RemoteResourceInformation>& resourceInfo)
{
auto card = GetCard();
auto showCardResources = card->GetResourceInformation();
auto resourceInfoEnd = resourceInfo.insert(resourceInfo.end(), showCardResources.begin(), showCardResources.end());
return;
}
|
/*
*
* Copyright 2018 gRPC 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/pollset_custom.h"
#include <stddef.h>
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/iomgr_custom.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/timer.h"
static grpc_custom_poller_vtable* poller_vtable;
struct grpc_pollset {
gpr_mu mu;
};
static size_t pollset_size() { return sizeof(grpc_pollset); }
static void pollset_global_init() { poller_vtable->init(); }
static void pollset_global_shutdown() { poller_vtable->shutdown(); }
static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
gpr_mu_init(&pollset->mu);
*mu = &pollset->mu;
}
static void pollset_shutdown(grpc_pollset* /*pollset*/, grpc_closure* closure) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
}
static void pollset_destroy(grpc_pollset* pollset) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
gpr_mu_destroy(&pollset->mu);
}
static grpc_error_handle pollset_work(grpc_pollset* pollset,
grpc_pollset_worker** /*worker_hdl*/,
grpc_millis deadline) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
gpr_mu_unlock(&pollset->mu);
grpc_millis now = grpc_core::ExecCtx::Get()->Now();
grpc_millis timeout = 0;
if (deadline > now) {
timeout = deadline - now;
}
// We yield here because the poll() call might yield
// control back to the application
grpc_core::ExecCtx* curr = grpc_core::ExecCtx::Get();
grpc_core::ExecCtx::Set(nullptr);
grpc_error_handle err = poller_vtable->poll(static_cast<size_t>(timeout));
grpc_core::ExecCtx::Set(curr);
grpc_core::ExecCtx::Get()->InvalidateNow();
if (grpc_core::ExecCtx::Get()->HasWork()) {
grpc_core::ExecCtx::Get()->Flush();
}
gpr_mu_lock(&pollset->mu);
return err;
}
static grpc_error_handle pollset_kick(
grpc_pollset* /*pollset*/, grpc_pollset_worker* /*specific_worker*/) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
poller_vtable->kick();
return GRPC_ERROR_NONE;
}
grpc_pollset_vtable custom_pollset_vtable = {
pollset_global_init, pollset_global_shutdown,
pollset_init, pollset_shutdown,
pollset_destroy, pollset_work,
pollset_kick, pollset_size};
void grpc_custom_pollset_init(grpc_custom_poller_vtable* vtable) {
poller_vtable = vtable;
grpc_set_pollset_vtable(&custom_pollset_vtable);
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
namespace AZ
{
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateIdentity()
{
Matrix3x3 result;
result.SetRow(0, 1.0f, 0.0f, 0.0f);
result.SetRow(1, 0.0f, 1.0f, 0.0f);
result.SetRow(2, 0.0f, 0.0f, 1.0f);
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateZero()
{
return Matrix3x3::CreateFromValue(0.0f);
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateFromValue(const VectorFloat& value)
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, value);
}
}
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateRotationX(const VectorFloat& angle)
{
Matrix3x3 result;
float c = cosf(angle);
float s = sinf(angle);
result.SetRow(0, 1.0f, 0.0f, 0.0f);
result.SetRow(1, 0.0f, c, -s);
result.SetRow(2, 0.0f, s, c);
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateRotationY(const VectorFloat& angle)
{
Matrix3x3 result;
float c = cosf(angle);
float s = sinf(angle);
result.SetRow(0, c, 0.0f, s);
result.SetRow(1, 0.0f, 1.0f, 0.0f);
result.SetRow(2, -s, 0.0f, c);
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateRotationZ(const VectorFloat& angle)
{
Matrix3x3 result;
float c = cosf(angle);
float s = sinf(angle);
result.SetRow(0, c, -s, 0.0f);
result.SetRow(1, s, c, 0.0f);
result.SetRow(2, 0.0f, 0.0f, 1.0f);
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateFromTransform(const Transform& t)
{
Matrix3x3 result;
result.SetRow(0, t.GetRowAsVector3(0));
result.SetRow(1, t.GetRowAsVector3(1));
result.SetRow(2, t.GetRowAsVector3(2));
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateFromMatrix4x4(const Matrix4x4& m)
{
Matrix3x3 result;
result.SetRow(0, m.GetRowAsVector3(0));
result.SetRow(1, m.GetRowAsVector3(1));
result.SetRow(2, m.GetRowAsVector3(2));
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateFromQuaternion(const Quaternion& q)
{
Matrix3x3 result;
result.SetRotationPartFromQuaternion(q);
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateDiagonal(const Vector3& diagonal)
{
Matrix3x3 result;
result.SetRow(0, diagonal.GetX(), 0.0f, 0.0f);
result.SetRow(1, 0.0f, diagonal.GetY(), 0.0f);
result.SetRow(2, 0.0f, 0.0f, diagonal.GetZ());
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::CreateCrossProduct(const Vector3& p)
{
Matrix3x3 result;
result.SetRow(0, 0.0f, -p.GetZ(), p.GetY());
result.SetRow(1, p.GetZ(), 0.0f, -p.GetX());
result.SetRow(2, -p.GetY(), p.GetX(), 0.0f);
return result;
}
AZ_MATH_FORCE_INLINE VectorFloat Matrix3x3::GetElement(int row, int col) const
{
AZ_Assert((row >= 0) && (row < 3), "Invalid index for component access!\n");
AZ_Assert((col >= 0) && (col < 3), "Invalid index for component access!\n");
return m_values[col][row];
}
AZ_MATH_FORCE_INLINE void Matrix3x3::SetElement(int row, int col, const VectorFloat& value)
{
AZ_Assert((row >= 0) && (row < 3), "Invalid index for component access!\n");
AZ_Assert((col >= 0) && (col < 3), "Invalid index for component access!\n");
m_values[col][row] = value;
}
AZ_MATH_FORCE_INLINE const Vector3 Matrix3x3::GetRow(int row) const
{
AZ_Assert((row >= 0) && (row < 3), "Invalid index for component access!\n");
return Vector3(m_values[0][row], m_values[1][row], m_values[2][row]);
}
AZ_MATH_FORCE_INLINE void Matrix3x3::SetRow(int row, const Vector3& v)
{
AZ_Assert((row >= 0) && (row < 3), "Invalid index for component access!\n");
m_values[0][row] = v.GetX();
m_values[1][row] = v.GetY();
m_values[2][row] = v.GetZ();
}
AZ_MATH_FORCE_INLINE const Vector3 Matrix3x3::GetColumn(int col) const
{
AZ_Assert((col >= 0) && (col < 3), "Invalid index for component access!\n");
return Vector3::CreateFromFloat3(&m_values[col][0]);
}
AZ_MATH_FORCE_INLINE void Matrix3x3::SetColumn(int col, const Vector3& v)
{
AZ_Assert((col >= 0) && (col < 3), "Invalid index for component access!\n");
m_values[col][0] = v.GetX();
m_values[col][1] = v.GetY();
m_values[col][2] = v.GetZ();
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::operator*(const Matrix3x3& rhs) const
{
Matrix3x3 out;
for (int row = 0; row < 3; ++row)
{
for (int col = 0; col < 3; col++)
{
out.m_values[col][row] = 0.0f;
for (int k = 0; k < 3; ++k)
{
out.m_values[col][row] += m_values[k][row] * rhs.m_values[col][k];
}
}
}
return out;
}
AZ_MATH_FORCE_INLINE const Vector3 Matrix3x3::operator*(const Vector3& rhs) const
{
return Vector3(m_values[0][0] * rhs(0) + m_values[1][0] * rhs(1) + m_values[2][0] * rhs(2),
m_values[0][1] * rhs(0) + m_values[1][1] * rhs(1) + m_values[2][1] * rhs(2),
m_values[0][2] * rhs(0) + m_values[1][2] * rhs(1) + m_values[2][2] * rhs(2));
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::operator+(const Matrix3x3& rhs) const
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, GetElement(i, j) + rhs.GetElement(i, j));
}
}
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::operator-(const Matrix3x3& rhs) const
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, GetElement(i, j) - rhs.GetElement(i, j));
}
}
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::operator*(const VectorFloat& multiplier) const
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, GetElement(i, j) * multiplier);
}
}
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::operator/(const VectorFloat& divisor) const
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, GetElement(i, j) / divisor);
}
}
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::operator-() const
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, -GetElement(i, j));
}
}
return result;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::GetTranspose() const
{
Matrix3x3 ret;
for (int row = 0; row < 3; ++row)
{
for (int col = 0; col < 3; ++col)
{
ret.m_values[col][row] = m_values[row][col];
}
}
return ret;
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::TransposedMultiply(const Matrix3x3& m) const
{
// \ref bullet btMatrix3x3::transposeTimes - practically this is this.Inverse * m;
Matrix3x3 ret;
Vector3 mc0 = m.GetColumn(0);
Vector3 mc1 = m.GetColumn(1);
Vector3 mc2 = m.GetColumn(2);
Vector3 cc0 = GetColumn(0);
Vector3 cc1 = GetColumn(1);
Vector3 cc2 = GetColumn(2);
ret.SetRow(0, cc0.Dot(mc0), cc0.Dot(mc1), cc0.Dot(mc2));
ret.SetRow(1, cc1.Dot(mc0), cc1.Dot(mc1), cc1.Dot(mc2));
ret.SetRow(2, cc2.Dot(mc0), cc2.Dot(mc1), cc2.Dot(mc2));
return ret;
}
AZ_MATH_FORCE_INLINE bool Matrix3x3::IsClose(const Matrix3x3& rhs, const VectorFloat& tolerance) const
{
for (int row = 0; row < 3; ++row)
{
for (int col = 0; col < 3; ++col)
{
if (fabsf(rhs(row, col) - GetElement(row, col)) > tolerance)
{
return false;
}
}
}
return true;
}
AZ_MATH_FORCE_INLINE bool Matrix3x3::operator==(const Matrix3x3& rhs) const
{
for (int row = 0; row < 3; ++row)
{
for (int col = 0; col < 3; ++col)
{
if ((float)rhs.GetElement(row, col) != (float)GetElement(row, col))
{
return false;
}
}
}
return true;
}
AZ_MATH_FORCE_INLINE const Vector3 Matrix3x3::GetDiagonal() const
{
return Vector3(GetElement(0, 0), GetElement(1, 1), GetElement(2, 2));
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::GetInverseFull() const
{
Matrix3x3 out = GetAdjugate();
//calculate the determinant
float det = m_values[0][0] * out.m_values[0][0] + m_values[0][1] * out.m_values[1][0] + m_values[0][2] * out.m_values[2][0];
//divide cofactors by determinant
float f = (det == 0.0f) ? 10000000.0f : 1.0f / det;
out.m_values[0][0] *= f;
out.m_values[1][0] *= f;
out.m_values[2][0] *= f;
out.m_values[0][1] *= f;
out.m_values[1][1] *= f;
out.m_values[2][1] *= f;
out.m_values[0][2] *= f;
out.m_values[1][2] *= f;
out.m_values[2][2] *= f;
return out;
}
AZ_MATH_FORCE_INLINE VectorFloat Matrix3x3::GetDeterminant() const
{
return m_values[0][0] * (m_values[1][1] * m_values[2][2] - m_values[2][1] * m_values[1][2])
+ m_values[0][1] * (m_values[1][2] * m_values[2][0] - m_values[2][2] * m_values[1][0])
+ m_values[0][2] * (m_values[1][0] * m_values[2][1] - m_values[2][0] * m_values[1][1]);
}
AZ_MATH_FORCE_INLINE const Matrix3x3 Matrix3x3::GetAdjugate() const
{
Matrix3x3 out;
out.m_values[0][0] = (m_values[1][1] * m_values[2][2] - m_values[2][1] * m_values[1][2]);
out.m_values[0][1] = (m_values[2][1] * m_values[0][2] - m_values[0][1] * m_values[2][2]);
out.m_values[0][2] = (m_values[0][1] * m_values[1][2] - m_values[1][1] * m_values[0][2]);
out.m_values[1][0] = (m_values[1][2] * m_values[2][0] - m_values[2][2] * m_values[1][0]);
out.m_values[1][1] = (m_values[2][2] * m_values[0][0] - m_values[0][2] * m_values[2][0]);
out.m_values[1][2] = (m_values[0][2] * m_values[1][0] - m_values[1][2] * m_values[0][0]);
out.m_values[2][0] = (m_values[1][0] * m_values[2][1] - m_values[2][0] * m_values[1][1]);
out.m_values[2][1] = (m_values[2][0] * m_values[0][1] - m_values[0][0] * m_values[2][1]);
out.m_values[2][2] = (m_values[0][0] * m_values[1][1] - m_values[1][0] * m_values[0][1]);
return out;
}
AZ_MATH_FORCE_INLINE const Vector3 operator*(const Vector3& lhs, const Matrix3x3& rhs)
{
return Vector3(lhs(0) * rhs(0, 0) + lhs(1) * rhs(1, 0) + lhs(2) * rhs(2, 0),
lhs(0) * rhs(0, 1) + lhs(1) * rhs(1, 1) + lhs(2) * rhs(2, 1),
lhs(0) * rhs(0, 2) + lhs(1) * rhs(1, 2) + lhs(2) * rhs(2, 2));
}
AZ_MATH_FORCE_INLINE const Matrix3x3 operator*(const VectorFloat& lhs, const Matrix3x3& rhs)
{
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
result.SetElement(i, j, lhs * rhs(i, j));
}
}
return result;
}
}
|
#include <tesseract_common/macros.h>
TESSERACT_COMMON_IGNORE_WARNINGS_PUSH
#include <gtest/gtest.h>
#include <Eigen/Geometry>
TESSERACT_COMMON_IGNORE_WARNINGS_POP
#include <tesseract_urdf/cylinder.h>
#include <tesseract_geometry/impl/cylinder.h>
#include "tesseract_urdf_common_unit.h"
TEST(TesseractURDFUnit, parse_cylinder) // NOLINT
{
{
std::string str = R"(<cylinder radius="1" length="2" extra="0 0 0"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_TRUE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
EXPECT_NEAR(geom->getRadius(), 1, 1e-8);
EXPECT_NEAR(geom->getLength(), 2, 1e-8);
}
{ // https://github.com/ros-industrial-consortium/tesseract_ros/issues/67
std::string str = R"(<cylinder radius="0.25" length="0.5" extra="0 0 0"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_TRUE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
EXPECT_NEAR(geom->getRadius(), 0.25, 1e-8);
EXPECT_NEAR(geom->getLength(), 0.5, 1e-8);
}
{
std::string str = R"(<cylinder radius="-1" length="2" extra="0 0 0"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
{
std::string str = R"(<cylinder radius="1" length="-2" extra="0 0 0"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
{
std::string str = R"(<cylinder radius="a" length="2"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
{
std::string str = R"(<cylinder radius="1" length="a"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
// TODO: I would expect this to fail but tinyxml2 still parses it so need to create an issue.
// {
// std::string str = R"(<cylinder radius="1 2" length="2 3"/>)";
// tesseract_geometry::Cylinder::Ptr geom;
// auto status = runTest<tesseract_geometry::Cylinder::Ptr>(geom, str, "cylinder", 2);
// EXPECT_FALSE(*status);
// EXPECT_FALSE(status->message().empty());
// }
{
std::string str = R"(<cylinder radius="1"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
{
std::string str = R"(<cylinder length="2"/>)";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
{
std::string str = "<cylinder />";
tesseract_geometry::Cylinder::Ptr geom;
EXPECT_FALSE(runTest<tesseract_geometry::Cylinder::Ptr>(geom, &tesseract_urdf::parseCylinder, str, "cylinder", 2));
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "ProtoNN.h"
using namespace EdgeML;
using namespace EdgeML::ProtoNN;
int main()
{
ProtoNNModel::ProtoNNHyperParams hyperParam;
hyperParam.problem_type = ProblemFormat::multiclass;
hyperParam.initialization_type = InitializationFormat::overall_kmeans;
hyperParam.dataformat_type = DataFormat::interface_ingest_format;
hyperParam.normalization_type = NormalizationFormat::none;
hyperParam.seed = 41;
hyperParam.batch_size = 100;
hyperParam.iters = 5;
hyperParam.epochs = 2;
hyperParam.D = 2;
hyperParam.d = 2;
hyperParam.m = 4;
hyperParam.k = 0;
hyperParam.l = 3;
hyperParam.gammaNumerator = 1.0;
hyperParam.lambda_W = 1.0;
hyperParam.lambda_Z = 1.0;
hyperParam.lambda_B = 1.0;
hyperParam.finalizeHyperParams();
// trivial data set
{
auto trainer = new ProtoNNTrainer(DataIngestType::InterfaceIngest, hyperParam);
FP_TYPE trainPts[2*16] = {-1.1, -1.1,
-0.9, -1.1,
-1.1, -0.9,
-0.9, -0.9,
1.1, 1.1,
0.9, 1.1,
1.1, 0.9,
0.9, 0.9,
-1.1, 1.1,
-0.9, 1.1,
-1.1, 0.9,
-0.9, 0.9,
1.1, -1.1,
0.9, -1.1,
1.1, -0.9,
0.9, -0.9};
labelCount_t labels[3] = {0,1,2};
for (int i=0; i<4; ++i)
trainer->feedDenseData (trainPts + 2*i, labels, 1);
for (int i=4; i<8; ++i)
trainer->feedDenseData (trainPts + 2*i, labels, 1);
for (int i=8; i<12; ++i)
trainer->feedDenseData (trainPts + 2*i, labels+1, 1);
for (int i=12; i<16; ++i)
trainer->feedDenseData (trainPts + 2*i, labels+2, 1);
trainer->finalizeData();
trainer->train();
auto modelBytes = trainer->getModelSize();
auto model = new char[modelBytes];
trainer->exportModel(modelBytes, model);
auto predictor = new ProtoNNPredictor(modelBytes, model);
FP_TYPE scoreArray[3] = {0.0, 0.0, 0.0};
FP_TYPE testPts[2*4] = {-1.0, -1.0,
1.0, 1.0,
-1.0, 1.0,
1.0, -1.0};
for (int t=0; t<4; ++t) {
predictor->scoreDenseDataPoint(scoreArray, testPts + 2*t);
for(int i=0;i<3;++i) std::cout<<scoreArray[i]<<" ";std::cout<<std::endl;
}
delete[] model;
delete trainer, predictor;
}
// Slightly less trivial example
{
auto trainer = new ProtoNNTrainer(DataIngestType::InterfaceIngest, hyperParam);
FP_TYPE trainPts[2*17] = {-1.1, -1.1,
-0.9, -1.1,
-1.1, -0.9,
-0.9, -0.9,
1.1, 1.1,
0.9, 1.1,
1.1, 0.9,
0.9, 0.9,
-1.1, 1.1,
-0.9, 1.1,
-1.1, 0.9,
-0.9, 0.9,
1.1, -1.1,
0.9, -1.1,
1.1, -0.9,
0.9, -0.9,
0.0, 0.0}; // Outlier
labelCount_t labels[3] = {0,1,2};
for (int i=0; i<3; ++i)
trainer->feedDenseData (trainPts + 2*i, labels, 1);
trainer->feedDenseData (trainPts + 6, labels + 1, 1);
for (int i=4; i<7; ++i)
trainer->feedDenseData (trainPts + 2*i, labels, 1);
trainer->feedDenseData (trainPts + 14, labels + 2, 1);
for (int i=8; i<11; ++i)
trainer->feedDenseData (trainPts + 2*i, labels+1, 1);
trainer->feedDenseData (trainPts + 22, labels + 2, 1);
for (int i=12; i<15; ++i)
trainer->feedDenseData (trainPts + 2*i, labels+2, 1);
trainer->feedDenseData (trainPts + 30, labels + 1, 1);
trainer->feedDenseData (trainPts + 32, labels+2, 1);
trainer->finalizeData();
trainer->train();
auto modelBytes = trainer->getModelSize();
auto model = new char[modelBytes];
trainer->exportModel(modelBytes, model);
auto predictor = new ProtoNNPredictor(modelBytes, model);
FP_TYPE scoreArray[3] = {0.0, 0.0, 0.0};
FP_TYPE testPts[2*5] = {-1.0, -1.0,
1.0, 1.0,
-1.0, 1.0,
1.0, -1.0,
0.5, 0.5};
for (int t=0; t<5; ++t) {
predictor->scoreDenseDataPoint(scoreArray, testPts + 2*t);
for(int i=0;i<3;++i) std::cout<<scoreArray[i]<<" ";std::cout<<std::endl;
}
delete[] model;
delete trainer, predictor;
}
// Slightly less trivial example for sparse data
{
auto trainer = new ProtoNNTrainer(DataIngestType::InterfaceIngest, hyperParam);
featureCount_t indices[2] = {0, 1};
int numIndices = 2;
FP_TYPE trainPts[2*17] = {-1.1, -1.1,
-0.9, -1.1,
-1.1, -0.9,
-0.9, -0.9,
1.1, 1.1,
0.9, 1.1,
1.1, 0.9,
0.9, 0.9,
-1.1, 1.1,
-0.9, 1.1,
-1.1, 0.9,
-0.9, 0.9,
1.1, -1.1,
0.9, -1.1,
1.1, -0.9,
0.9, -0.9,
0.0, 0.0}; // Outlier
labelCount_t labels[3] = {0,1,2};
for (int i=0; i<3; ++i)
trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels, 1);
trainer->feedSparseData (trainPts + 6, indices, numIndices, labels + 1, 1);
for (int i=4; i<7; ++i)
trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels, 1);
trainer->feedSparseData (trainPts + 14, indices, numIndices, labels + 2, 1);
for (int i=8; i<11; ++i)
trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels+1, 1);
trainer->feedSparseData (trainPts + 22, indices, numIndices, labels + 2, 1);
for (int i=12; i<15; ++i)
trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels+2, 1);
trainer->feedSparseData (trainPts + 30, indices, numIndices, labels + 1, 1);
trainer->feedSparseData (trainPts + 32, indices, numIndices, labels+2, 1);
trainer->finalizeData();
trainer->train();
auto modelBytes = trainer->getModelSize();
auto model = new char[modelBytes];
trainer->exportModel(modelBytes, model);
auto predictor = new ProtoNNPredictor(modelBytes, model);
FP_TYPE scoreArray[3] = {0.0, 0.0, 0.0};
FP_TYPE testPts[2*5] = {-1.0, -1.0,
1.0, 1.0,
-1.0, 1.0,
1.0, -1.0,
0.5, 0.5};
for (int t=0; t<5; ++t) {
//predictor->scoreDenseDataPoint(scoreArray, testPts + 2*t);
// both dense and sparse scoring work
predictor -> scoreSparseDataPoint(scoreArray, testPts + 2*t, indices, 2);
for(int i=0;i<3;++i) std::cout<<scoreArray[i]<<" ";std::cout<<std::endl;
}
delete[] model;
delete trainer, predictor;
}
}
|
//
// Created by Jeromy Black on 12/19/20.
//
#include "Animation.h"
#include "glad.h"
#include "GLFW/glfw3.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include "glm/glm.hpp"
using namespace std;
int Animation::FindKey()
{
int i = 0;
for (; i < keys.size() - 1; i++)
{
if (timeFromStart < (float) keys[i + 1]->startTime)
return i;
}
if (i == keys.size() - 1)
return i;
return 0 ;
}
vec3 Animation::GetPosition(const Entity& entity, float time)
{
// if (keys.size() == 1)
// return keys[0]->position;
// int startFrame = FindKey();
// int endFrame = startFrame >= (keys.size() - 1) ? 0 : startFrame + 1;
// float DeltaTime = 0;
// float Factor = 0;
// if (endFrame == 0)
// {
// DeltaTime = keys[0]->frameTime ;
// Factor = (timeFromStart - keys[startFrame]->startTime) / DeltaTime;
// }
// else
// {
// DeltaTime = keys[endFrame]->startTime - keys[startFrame]->startTime;
// Factor = (timeFromStart - keys[startFrame]->startTime) / DeltaTime;
// }
//// vec3 r = lerp(keys[startFrame]->position, keys[endFrame]->position, Factor);
//
// return r;
}
vec3 Animation::GetRotationMatrix(const Entity& entity, float time)
{
// if (keys.size() == 1)
// return keys[0]->rotation;
// int startFrame = FindKey();
// int endFrame = startFrame >= (keys.size() - 1) ? 0 : startFrame + 1;
// float DeltaTime = 0;
// float Factor = 0;
// if (endFrame == 0)
// {
// DeltaTime = keys[0]->frameTime ;
// Factor = (timeFromStart - keys[startFrame]->startTime) / DeltaTime;
// }
// else
// {
// DeltaTime = keys[endFrame]->startTime - keys[startFrame]->startTime;
// Factor = (timeFromStart - keys[startFrame]->startTime) / DeltaTime;
// }
// vec3 r = lerp(keys[startFrame]->rotation, keys[endFrame]->rotation, Factor);
// return r;
}
vec3 Animation::GetScale(const Entity& entity, float time)
{
// if (keys.size() == 1)
// return keys[0]->rotation;
// int startFrame = FindKey();
// int endFrame = startFrame >= (keys.size() - 1) ? 0 : startFrame + 1;
// float DeltaTime = 0;
// float Factor = 0;
// if (endFrame == 0)
// {
// DeltaTime = keys[0]->frameTime ;
// Factor = (timeFromStart - keys[startFrame]->startTime) / DeltaTime;
// }
// else
// {
// DeltaTime = keys[endFrame]->startTime - keys[startFrame]->startTime;
// Factor = (timeFromStart - keys[startFrame]->startTime) / DeltaTime;
// }
// vec3 r = lerp(keys[startFrame]->scale, keys[endFrame]->scale, Factor);
// return r;
}
mat4 Animation::GetAnimationMatrix(const Entity& entity, float time)
{
// timeFromStart += time;
//
// if (timeFromStart >= duration)
// timeFromStart = 0;
// std::cout << timeFromStart << std::endl;
// std::cout << "Duration" << duration << std::endl;
// int key = FindKey();
//
// mat4 result = mat4(1.0f);
// result = translate(result, GetPosition(entity, time));
// result = translate(result, entity.positionOffset);
// result = rotate(result, GetRotationMatrix(entity, time));
// result = translate(result, -1 * entity.positionOffset);
// result = scale(result, GetScale(entity, time));
// return result;
}
void Animation::AddAnimationKey(AnimationKey *key)
{
key->startTime = duration;
keys.emplace_back(key);
duration += key->frameTime;
}
Animation::Animation()
{
}
//Animation::Animation(const std::vector<AnimationKey> &keys) : keys(keys)
//{
//
//}
|
__device__
void builtin_function()
{}
// Should be __host__ __device__
void device_function()
{}
// Should be __host__
void uncalled_function()
{ device_function(); }
// Should be __device__,
// since __device__ builtin is called
void uncalled_builtin_call()
{
builtin_function();
}
template<class Func>
__global__ void kernel(Func f)
{
f();
}
template<class Func>
void submit(Func f)
{ f(); }
template<class T>
void templated_launch()
{
submit([](){
kernel([](){
device_function();
builtin_function();
});
});
}
template<class T>
void uncalled_templated_launch()
{
submit([](){
kernel([](){
device_function();
builtin_function();
});
});
}
int main()
{
templated_launch<int>();
templated_launch<float>();
}
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Semi-trailing arm suspension constructed with data from file.
//
// =============================================================================
#include <cstdio>
#include "chrono_vehicle/wheeled_vehicle/suspension/SemiTrailingArm.h"
#include "chrono_thirdparty/rapidjson/filereadstream.h"
using namespace rapidjson;
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
// This utility function returns a ChVector from the specified JSON array
// -----------------------------------------------------------------------------
static ChVector<> loadVector(const Value& a) {
assert(a.IsArray());
assert(a.Size() == 3);
return ChVector<>(a[0u].GetDouble(), a[1u].GetDouble(), a[2u].GetDouble());
}
// -----------------------------------------------------------------------------
// Construct a trailing arm suspension using data from the specified JSON file.
// -----------------------------------------------------------------------------
SemiTrailingArm::SemiTrailingArm(const std::string& filename)
: ChSemiTrailingArm(""), m_springForceCB(NULL), m_shockForceCB(NULL) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
Create(d);
GetLog() << "Loaded JSON: " << filename.c_str() << "\n";
}
SemiTrailingArm::SemiTrailingArm(const rapidjson::Document& d)
: ChSemiTrailingArm(""), m_springForceCB(NULL), m_shockForceCB(NULL) {
Create(d);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
SemiTrailingArm::~SemiTrailingArm() {
delete m_springForceCB;
delete m_shockForceCB;
}
// -----------------------------------------------------------------------------
// Worker function for creating a SemiTrailingArm suspension using data in the
// specified RapidJSON document.
// -----------------------------------------------------------------------------
void SemiTrailingArm::Create(const rapidjson::Document& d) {
// Read top-level data
assert(d.HasMember("Type"));
assert(d.HasMember("Template"));
assert(d.HasMember("Name"));
SetName(d["Name"].GetString());
// Read Spindle data
assert(d.HasMember("Spindle"));
assert(d["Spindle"].IsObject());
m_spindleMass = d["Spindle"]["Mass"].GetDouble();
m_points[SPINDLE] = loadVector(d["Spindle"]["COM"]);
m_spindleInertia = loadVector(d["Spindle"]["Inertia"]);
m_spindleRadius = d["Spindle"]["Radius"].GetDouble();
m_spindleWidth = d["Spindle"]["Width"].GetDouble();
// Read trailing arm data
assert(d.HasMember("Trailing Arm"));
assert(d["Trailing Arm"].IsObject());
m_armMass = d["Trailing Arm"]["Mass"].GetDouble();
m_points[TA_CM] = loadVector(d["Trailing Arm"]["COM"]);
m_armInertia = loadVector(d["Trailing Arm"]["Inertia"]);
m_armRadius = d["Trailing Arm"]["Radius"].GetDouble();
m_points[TA_O] = loadVector(d["Trailing Arm"]["Location Chassis Outer"]);
m_points[TA_I] = loadVector(d["Trailing Arm"]["Location Chassis Inner"]);
m_points[TA_S] = loadVector(d["Trailing Arm"]["Location Spindle"]);
// Read spring data and create force callback
assert(d.HasMember("Spring"));
assert(d["Spring"].IsObject());
m_points[SPRING_C] = loadVector(d["Spring"]["Location Chassis"]);
m_points[SPRING_A] = loadVector(d["Spring"]["Location Arm"]);
m_springRestLength = d["Spring"]["Free Length"].GetDouble();
if (d["Spring"].HasMember("Spring Coefficient")) {
m_springForceCB = new LinearSpringForce(d["Spring"]["Spring Coefficient"].GetDouble());
} else if (d["Spring"].HasMember("Curve Data")) {
int num_points = d["Spring"]["Curve Data"].Size();
MapSpringForce* springForceCB = new MapSpringForce();
for (int i = 0; i < num_points; i++) {
springForceCB->add_point(d["Spring"]["Curve Data"][i][0u].GetDouble(),
d["Spring"]["Curve Data"][i][1u].GetDouble());
}
m_springForceCB = springForceCB;
}
// Read shock data and create force callback
assert(d.HasMember("Shock"));
assert(d["Shock"].IsObject());
m_points[SHOCK_C] = loadVector(d["Shock"]["Location Chassis"]);
m_points[SHOCK_A] = loadVector(d["Shock"]["Location Arm"]);
if (d["Shock"].HasMember("Damping Coefficient")) {
m_shockForceCB = new LinearDamperForce(d["Shock"]["Damping Coefficient"].GetDouble());
} else if (d["Shock"].HasMember("Curve Data")) {
int num_points = d["Shock"]["Curve Data"].Size();
MapDamperForce* shockForceCB = new MapDamperForce();
for (int i = 0; i < num_points; i++) {
shockForceCB->add_point(d["Shock"]["Curve Data"][i][0u].GetDouble(),
d["Shock"]["Curve Data"][i][1u].GetDouble());
}
m_shockForceCB = shockForceCB;
}
// Read axle inertia
assert(d.HasMember("Axle"));
assert(d["Axle"].IsObject());
m_axleInertia = d["Axle"]["Inertia"].GetDouble();
}
} // end namespace vehicle
} // end namespace chrono
|
#include <DebugHelper.hpp>
#include "GamePacket.hpp"
#include <MessageTranslation\FlatbufferTranslator.hpp>
#include "..\CallbackProcessor\SharedMemoryDefinitions.hpp"
#include "..\CallbackProcessor\CallbackProcessor.hpp"
#include <BoostUtilities\BoostUtilities.hpp>
#include <BoostUtilities\BoostConstants.hpp>
namespace GameFunctions
{
BoostUtilities::SharedMemReader* pFlatFieldMem = nullptr;
BoostUtilities::SharedMemReader* pFlatTickMem = nullptr;
BoostUtilities::SharedMemReader* pPhysicsTickMem = nullptr;
ByteBuffer MakeEmptyBuffer()
{
ByteBuffer empty;
empty.ptr = new char[1]; // Arbitrary valid pointer to an array. We'll be calling delete[] on this later.
empty.size = 0;
return empty;
}
void Initialize_GamePacket()
{
pFlatFieldMem = new BoostUtilities::SharedMemReader(BoostConstants::FieldInfoFlatName);
pFlatTickMem = new BoostUtilities::SharedMemReader(BoostConstants::GameDataFlatName);
pPhysicsTickMem = new BoostUtilities::SharedMemReader(BoostConstants::PhysicsTickFlatName);
}
//////////////
// FIELD INFO
//////////////
extern "C" ByteBuffer RLBOT_CORE_API UpdateFieldInfoFlatbuffer()
{
if (!pFlatFieldMem)
{
return MakeEmptyBuffer();
}
return pFlatFieldMem->fetchData();
}
// Ctypes
extern "C" RLBotCoreStatus RLBOT_CORE_API UpdateFieldInfo(FieldInfo* pFieldInfo)
{
ByteBuffer fieldInfo = UpdateFieldInfoFlatbuffer();
FlatbufferTranslator::translateToFieldInfoStruct(fieldInfo, pFieldInfo);
delete[] fieldInfo.ptr;
return RLBotCoreStatus::Success;
}
//////////////
// GAME PACKET
//////////////
extern "C" ByteBuffer RLBOT_CORE_API UpdateLiveDataPacketFlatbuffer()
{
if (!pFlatTickMem)
{
return MakeEmptyBuffer();
}
return pFlatTickMem->fetchData();
}
// Ctypes
extern "C" RLBotCoreStatus RLBOT_CORE_API UpdateLiveDataPacket(LiveDataPacket* pLiveData)
{
ByteBuffer flatbuffer = UpdateLiveDataPacketFlatbuffer();
FlatbufferTranslator::translateToStruct(flatbuffer, pLiveData);
delete[] flatbuffer.ptr;
return RLBotCoreStatus::Success;
}
///////////////
// PHYSICS TICK
///////////////
extern "C" ByteBuffer RLBOT_CORE_API UpdateRigidBodyTickFlatbuffer()
{
if (!pPhysicsTickMem)
{
return MakeEmptyBuffer();
}
return pPhysicsTickMem->fetchData();
}
extern "C" RLBotCoreStatus RLBOT_CORE_API UpdateRigidBodyTick(RigidBodyTick* rigidBodyTick)
{
ByteBuffer flatbuffer = UpdateRigidBodyTickFlatbuffer();
FlatbufferTranslator::translateToRigidBodyStruct(flatbuffer, rigidBodyTick);
delete[] flatbuffer.ptr;
return RLBotCoreStatus::Success;
}
}
|
/*
* Scene_House_Out.cpp
* enigma
*
* Created by Rockford on 22/03/11.
* Copyright 2011 Casual Games France. All rights reserved.
*
*/
#include "MyGame.h"
#include "EScene.h"
#include "Scene_House_Out.h"
#include "ESceneDirector.h"
#include "EMiniJeuPentagram.h"
#include "MusicBank.h"
/* Constructeur */
Scene_House_Out::Scene_House_Out(ESceneDirector *lpSceneDirector) : EScene(lpSceneDirector)
{
_lpBgGraphic = KPTK::createKGraphic ();
_nYesForTutorial = -1;
_bTutorial = false;
_bTutorialAsked = false;
EMiniJeuPentagram::Preload();
}
/* Destructeur */
Scene_House_Out::~Scene_House_Out()
{
delete _lpBgGraphic;
}
void Scene_House_Out::Init()
{
_lpSceneDirector->ChangeMusic(DIRECTOR_MUSIC_NONE, true);
_lpSceneDirector->ShowIHM(true);
// Glit sur la portière
if (TaskResolved("car_box_map") && TaskResolved("car_box_key")) {
GetObjectImageByName("out_car_zone")->EnableGlitch(false);
}
if (!TaskResolved("task_out_firstvisit")) {
ResolveTask("task_out_firstvisit");
AddObjective("house","getmap");
AddHint("house","getmap","how");
_lpSceneDirector->getSequencer()->Callback(NULL, "tutoask");
_lpSceneDirector->getDiaryPtr()->beginCreatePage();
_lpSceneDirector->getDiaryPtr()->addImageToPage("diary_out.png");
_lpSceneDirector->getDiaryPtr()->addStringToPage("DIARY_OUT", FONT_DIARY_1, 0, 0);
_lpSceneDirector->getDiaryPtr()->endCreatePage();
}
if (TaskResolved("out_house_zeps")) {
GetObjectImageByName("out_house_zeps")->EnableGlitch(false);
}
if (getAdditionalName() == "gotohouse") {
AddObjective("house","enterhouse");
AddHint("house","enterhouse","how");
if (TestGlobal("__tutorial__")) {
_lpSceneDirector->getSequencer()->Tutobox(NULL, KStr("HOUSE_OUT_TUTO_ENTERHOUSE"), 273, 204, 180, 200);
}
}
_lpSceneDirector->getSequencer()->PreloadVideo("videos/zeppelins.ogv");
}
void Scene_House_Out::Check()
{
EScene::Check();
#ifdef SCENE_SHORTCUT
if (KInput::isPressed(K_VK_F5))
{
_lpSceneDirector->GoToScene("menu");
}
#endif
}
void Scene_House_Out::Logic()
{
EScene::Logic();
// Le joueur a répondu à la boite Yes/No demandant si il voulait un tuto
if (_nYesForTutorial != -1) {
// Activation du tutorial
if (_nYesForTutorial == 1) {
_bTutorial = true;
// Démarre le tutorial
_lpSceneDirector->getSequencer()->Tutobox(NULL, KStr("HOUSE_OUT_TUTO_CAR"), 776, 367, -45, 200);
SetGlobal("__tutorial__","1");
}
else {
SetGlobal("__tutorial__","0");
}
_nYesForTutorial = -1;
}
}
void Scene_House_Out::Draw()
{
EScene::Draw();
}
void Scene_House_Out::Close()
{
}
bool Scene_House_Out::ObjectClicked(const char *szObjectName, float x, float y)
{
if ( strcmp(szObjectName, "out_car_zone") == 0)
{
_lpSceneDirector->getSequencer()->PlaySound(NULL, "cardoor");
_lpSceneDirector->getSequencer()->GoToScene(NULL, "house_out_car", "", false);
return true;
}
if ( strcmp(szObjectName, "out_house_zeps") == 0)
{
ResolveTask("task_out_zeps");
GetObjectImageByName("out_house_zeps")->EnableGlitch(false);
_lpSceneDirector->getSequencer()->GotoVideo(szObjectName, "videos/zeppelins.ogv", "zeppelins");
_lpSceneDirector->getSequencer()->Talk("zeps", CHARACTER_POSX, CHARACTER_POSY, KStr("HOUSE_OUT_ASHLEY_ZEPS"), "", true);
if (!TaskResolved("task_out_zeps_page")) {
ResolveTask("task_out_zeps_page");
_lpSceneDirector->getDiaryPtr()->beginCreatePage();
_lpSceneDirector->getDiaryPtr()->addImageToPage("diary_zeps.png");
_lpSceneDirector->getDiaryPtr()->addStringToPage("DIARY_ZEPPELINS", FONT_DIARY_1, 0, 0);
_lpSceneDirector->getDiaryPtr()->endCreatePage();
}
return true;
}
if ( strcmp(szObjectName, "out_house_zone") == 0)
{
if (ObjectiveResolved("house","getmap")) {
_lpSceneDirector->getSequencer()->GoToScene(NULL, "parvis", "", false);
}
else {
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("HOUSE_OUT_ASHLEY_NEEDMAP"), "", true);
if (TestGlobal("__tutorial__")) {
_lpSceneDirector->getSequencer()->Tutobox(NULL, KStr("HOUSE_OUT_TUTO_CAR"), 913, 504, -45, 200);
}
}
return true;
}
if (strcmp(szObjectName, "house_out_isaac_quiet") == 0) {
ESoundBank::getSound("isaac_bark")->playSample();
if (!ObjectiveResolved("house","getmap")) {
_lpSceneDirector->getSequencer()->Talk(szObjectName, CHARACTER_POSX, CHARACTER_POSY, KStr("HOUSE_OUT_ASHLEY_ISAAC1"), "", true);
}
else {
_lpSceneDirector->getSequencer()->Talk(szObjectName, CHARACTER_POSX, CHARACTER_POSY, KStr("HOUSE_OUT_ASHLEY_ISAAC2"), "", true);
}
}
return false;
}
bool Scene_House_Out::ObjectOver(char *szObjectName, float x, float y)
{
return false;
}
bool Scene_House_Out::ItemUsed(const char *szItemName, const char *szObjectName)
{
return false;
}
void Scene_House_Out::MiniGameDone(const char *szGameName, bool bIsRevolved)
{
if (bIsRevolved) {
return;
}
if (!bIsRevolved) {
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("HOUSE_ASHLEY_GASP"), "", true, false);
return;
}
}
void Scene_House_Out::Callback(const char *szParam)
{
if (strcmp(szParam, "tutoask") == 0) {
if (!TaskResolved("__reply_tutorial__")) {
ResolveTask("__reply_tutorial__");
_lpSceneDirector->OpenDialogboxYN(KStr("HOUSE_OUT_TUTOASK"), &_nYesForTutorial);
}
}
}
|
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file testJacobianFactor.cpp
* @brief Unit tests for Linear Factor
* @author Christian Potthast
* @author Frank Dellaert
**/
#include <gtsam/base/TestableAssertions.h>
#include <CppUnitLite/TestHarness.h>
#include <gtsam/linear/JacobianFactor.h>
#include <gtsam/linear/GaussianFactorGraph.h>
#include <gtsam/linear/GaussianConditional.h>
#include <gtsam/linear/VectorValues.h>
#include <boost/assign/std/vector.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/adaptor/map.hpp>
using namespace std;
using namespace gtsam;
using namespace boost::assign;
namespace {
namespace simple {
// Terms we'll use
const vector<pair<Key, Matrix> > terms = list_of<pair<Key,Matrix> >
(make_pair(5, Matrix3::Identity()))
(make_pair(10, 2*Matrix3::Identity()))
(make_pair(15, 3*Matrix3::Identity()));
// RHS and sigmas
const Vector b = (Vector(3) << 1., 2., 3.);
const SharedDiagonal noise = noiseModel::Diagonal::Sigmas((Vector(3) << 0.5, 0.5, 0.5));
}
}
/* ************************************************************************* */
TEST(JacobianFactor, constructors_and_accessors)
{
using namespace simple;
// Test for using different numbers of terms
{
// b vector only constructor
JacobianFactor expected(
boost::make_iterator_range(terms.begin(), terms.begin()), b);
JacobianFactor actual(b);
EXPECT(assert_equal(expected, actual));
EXPECT(assert_equal(b, expected.getb()));
EXPECT(assert_equal(b, actual.getb()));
EXPECT(!expected.get_model());
EXPECT(!actual.get_model());
}
{
// One term constructor
JacobianFactor expected(
boost::make_iterator_range(terms.begin(), terms.begin() + 1), b, noise);
JacobianFactor actual(terms[0].first, terms[0].second, b, noise);
EXPECT(assert_equal(expected, actual));
LONGS_EQUAL((long)terms[0].first, (long)actual.keys().back());
EXPECT(assert_equal(terms[0].second, actual.getA(actual.end() - 1)));
EXPECT(assert_equal(b, expected.getb()));
EXPECT(assert_equal(b, actual.getb()));
EXPECT(noise == expected.get_model());
EXPECT(noise == actual.get_model());
}
{
// Two term constructor
JacobianFactor expected(
boost::make_iterator_range(terms.begin(), terms.begin() + 2), b, noise);
JacobianFactor actual(terms[0].first, terms[0].second,
terms[1].first, terms[1].second, b, noise);
EXPECT(assert_equal(expected, actual));
LONGS_EQUAL((long)terms[1].first, (long)actual.keys().back());
EXPECT(assert_equal(terms[1].second, actual.getA(actual.end() - 1)));
EXPECT(assert_equal(b, expected.getb()));
EXPECT(assert_equal(b, actual.getb()));
EXPECT(noise == expected.get_model());
EXPECT(noise == actual.get_model());
}
{
// Three term constructor
JacobianFactor expected(
boost::make_iterator_range(terms.begin(), terms.begin() + 3), b, noise);
JacobianFactor actual(terms[0].first, terms[0].second,
terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, noise);
EXPECT(assert_equal(expected, actual));
LONGS_EQUAL((long)terms[2].first, (long)actual.keys().back());
EXPECT(assert_equal(terms[2].second, actual.getA(actual.end() - 1)));
EXPECT(assert_equal(b, expected.getb()));
EXPECT(assert_equal(b, actual.getb()));
EXPECT(noise == expected.get_model());
EXPECT(noise == actual.get_model());
}
{
// Test three-term constructor with std::map
JacobianFactor expected(
boost::make_iterator_range(terms.begin(), terms.begin() + 3), b, noise);
map<Key,Matrix> mapTerms;
// note order of insertion plays no role: order will be determined by keys
mapTerms.insert(terms[2]);
mapTerms.insert(terms[1]);
mapTerms.insert(terms[0]);
JacobianFactor actual(mapTerms, b, noise);
EXPECT(assert_equal(expected, actual));
LONGS_EQUAL((long)terms[2].first, (long)actual.keys().back());
EXPECT(assert_equal(terms[2].second, actual.getA(actual.end() - 1)));
EXPECT(assert_equal(b, expected.getb()));
EXPECT(assert_equal(b, actual.getb()));
EXPECT(noise == expected.get_model());
EXPECT(noise == actual.get_model());
}
{
// VerticalBlockMatrix constructor
JacobianFactor expected(
boost::make_iterator_range(terms.begin(), terms.begin() + 3), b, noise);
VerticalBlockMatrix blockMatrix(list_of(3)(3)(3)(1), 3);
blockMatrix(0) = terms[0].second;
blockMatrix(1) = terms[1].second;
blockMatrix(2) = terms[2].second;
blockMatrix(3) = b;
JacobianFactor actual(terms | boost::adaptors::map_keys, blockMatrix, noise);
EXPECT(assert_equal(expected, actual));
LONGS_EQUAL((long)terms[2].first, (long)actual.keys().back());
EXPECT(assert_equal(terms[2].second, actual.getA(actual.end() - 1)));
EXPECT(assert_equal(b, expected.getb()));
EXPECT(assert_equal(b, actual.getb()));
EXPECT(noise == expected.get_model());
EXPECT(noise == actual.get_model());
}
}
/* ************************************************************************* */
TEST(JabobianFactor, Hessian_conversion) {
HessianFactor hessian(0, (Matrix(4,4) <<
1.57, 2.695, -1.1, -2.35,
2.695, 11.3125, -0.65, -10.225,
-1.1, -0.65, 1, 0.5,
-2.35, -10.225, 0.5, 9.25),
(Vector(4) << -7.885, -28.5175, 2.75, 25.675),
73.1725);
JacobianFactor expected(0, (Matrix(2,4) <<
1.2530, 2.1508, -0.8779, -1.8755,
0, 2.5858, 0.4789, -2.3943),
(Vector(2) << -6.2929, -5.7941));
EXPECT(assert_equal(expected, JacobianFactor(hessian), 1e-3));
}
/* ************************************************************************* */
TEST( JacobianFactor, construct_from_graph)
{
GaussianFactorGraph factors;
double sigma1 = 0.1;
Matrix A11 = Matrix::Identity(2,2);
Vector b1(2); b1 << 2, -1;
factors.add(JacobianFactor(10, A11, b1, noiseModel::Isotropic::Sigma(2, sigma1)));
double sigma2 = 0.5;
Matrix A21 = -2 * Matrix::Identity(2,2);
Matrix A22 = 3 * Matrix::Identity(2,2);
Vector b2(2); b2 << 4, -5;
factors.add(JacobianFactor(10, A21, 8, A22, b2, noiseModel::Isotropic::Sigma(2, sigma2)));
double sigma3 = 1.0;
Matrix A32 = -4 * Matrix::Identity(2,2);
Matrix A33 = 5 * Matrix::Identity(2,2);
Vector b3(2); b3 << 3, -6;
factors.add(JacobianFactor(8, A32, 12, A33, b3, noiseModel::Isotropic::Sigma(2, sigma3)));
Matrix A1(6,2); A1 << A11, A21, Matrix::Zero(2,2);
Matrix A2(6,2); A2 << Matrix::Zero(2,2), A22, A32;
Matrix A3(6,2); A3 << Matrix::Zero(4,2), A33;
Vector b(6); b << b1, b2, b3;
Vector sigmas(6); sigmas << sigma1, sigma1, sigma2, sigma2, sigma3, sigma3;
JacobianFactor expected(10, A1, 8, A2, 12, A3, b, noiseModel::Diagonal::Sigmas(sigmas));
// The ordering here specifies the order in which the variables will appear in the combined factor
JacobianFactor actual(factors, Ordering(list_of(10)(8)(12)));
EXPECT(assert_equal(expected, actual));
}
/* ************************************************************************* */
TEST(JacobianFactor, error)
{
JacobianFactor factor(simple::terms, simple::b, simple::noise);
VectorValues values;
values.insert(5, Vector::Constant(3, 1.0));
values.insert(10, Vector::Constant(3, 0.5));
values.insert(15, Vector::Constant(3, 1.0/3.0));
Vector expected_unwhitened(3); expected_unwhitened << 2.0, 1.0, 0.0;
Vector actual_unwhitened = factor.unweighted_error(values);
EXPECT(assert_equal(expected_unwhitened, actual_unwhitened));
Vector expected_whitened(3); expected_whitened << 4.0, 2.0, 0.0;
Vector actual_whitened = factor.error_vector(values);
EXPECT(assert_equal(expected_whitened, actual_whitened));
double expected_error = 0.5 * expected_whitened.squaredNorm();
double actual_error = factor.error(values);
DOUBLES_EQUAL(expected_error, actual_error, 1e-10);
}
/* ************************************************************************* */
TEST(JacobianFactor, matrices_NULL)
{
// Make sure everything works with NULL noise model
JacobianFactor factor(simple::terms, simple::b);
Matrix jacobianExpected(3, 9);
jacobianExpected << simple::terms[0].second, simple::terms[1].second, simple::terms[2].second;
Vector rhsExpected = simple::b;
Matrix augmentedJacobianExpected(3, 10);
augmentedJacobianExpected << jacobianExpected, rhsExpected;
Matrix augmentedHessianExpected =
augmentedJacobianExpected.transpose() * augmentedJacobianExpected;
// Hessian
EXPECT(assert_equal(Matrix(augmentedHessianExpected.topLeftCorner(9,9)), factor.information()));
EXPECT(assert_equal(augmentedHessianExpected, factor.augmentedInformation()));
// Whitened Jacobian
EXPECT(assert_equal(jacobianExpected, factor.jacobian().first));
EXPECT(assert_equal(rhsExpected, factor.jacobian().second));
EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobian()));
// Unwhitened Jacobian
EXPECT(assert_equal(jacobianExpected, factor.jacobianUnweighted().first));
EXPECT(assert_equal(rhsExpected, factor.jacobianUnweighted().second));
EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobianUnweighted()));
// hessianDiagonal
VectorValues expectDiagonal;
expectDiagonal.insert(5, ones(3));
expectDiagonal.insert(10, 4*ones(3));
expectDiagonal.insert(15, 9*ones(3));
EXPECT(assert_equal(expectDiagonal, factor.hessianDiagonal()));
// hessianBlockDiagonal
map<Key,Matrix> actualBD = factor.hessianBlockDiagonal();
LONGS_EQUAL(3,actualBD.size());
EXPECT(assert_equal(1*eye(3),actualBD[5]));
EXPECT(assert_equal(4*eye(3),actualBD[10]));
EXPECT(assert_equal(9*eye(3),actualBD[15]));
}
/* ************************************************************************* */
TEST(JacobianFactor, matrices)
{
// And now witgh a non-unit noise model
JacobianFactor factor(simple::terms, simple::b, simple::noise);
Matrix jacobianExpected(3, 9);
jacobianExpected << simple::terms[0].second, simple::terms[1].second, simple::terms[2].second;
Vector rhsExpected = simple::b;
Matrix augmentedJacobianExpected(3, 10);
augmentedJacobianExpected << jacobianExpected, rhsExpected;
Matrix augmentedHessianExpected =
augmentedJacobianExpected.transpose() * simple::noise->R().transpose()
* simple::noise->R() * augmentedJacobianExpected;
// Hessian
EXPECT(assert_equal(Matrix(augmentedHessianExpected.topLeftCorner(9,9)), factor.information()));
EXPECT(assert_equal(augmentedHessianExpected, factor.augmentedInformation()));
// Whitened Jacobian
EXPECT(assert_equal(simple::noise->R() * jacobianExpected, factor.jacobian().first));
EXPECT(assert_equal(simple::noise->R() * rhsExpected, factor.jacobian().second));
EXPECT(assert_equal(simple::noise->R() * augmentedJacobianExpected, factor.augmentedJacobian()));
// Unwhitened Jacobian
EXPECT(assert_equal(jacobianExpected, factor.jacobianUnweighted().first));
EXPECT(assert_equal(rhsExpected, factor.jacobianUnweighted().second));
EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobianUnweighted()));
// hessianDiagonal
VectorValues expectDiagonal;
// below we divide by the variance 0.5^2
expectDiagonal.insert(5, (Vector(3) << 1, 1, 1)/0.25);
expectDiagonal.insert(10, (Vector(3) << 4, 4, 4)/0.25);
expectDiagonal.insert(15, (Vector(3) << 9, 9, 9)/0.25);
EXPECT(assert_equal(expectDiagonal, factor.hessianDiagonal()));
// hessianBlockDiagonal
map<Key,Matrix> actualBD = factor.hessianBlockDiagonal();
LONGS_EQUAL(3,actualBD.size());
EXPECT(assert_equal(4*eye(3),actualBD[5]));
EXPECT(assert_equal(16*eye(3),actualBD[10]));
EXPECT(assert_equal(36*eye(3),actualBD[15]));
}
/* ************************************************************************* */
TEST(JacobianFactor, operators )
{
SharedDiagonal sigma0_1 = noiseModel::Isotropic::Sigma(2,0.1);
Matrix I = eye(2);
Vector b = (Vector(2) << 0.2,-0.1);
JacobianFactor lf(1, -I, 2, I, b, sigma0_1);
VectorValues c;
c.insert(1, (Vector(2) << 10.,20.));
c.insert(2, (Vector(2) << 30.,60.));
// test A*x
Vector expectedE = (Vector(2) << 200.,400.);
Vector actualE = lf * c;
EXPECT(assert_equal(expectedE, actualE));
// test A^e
VectorValues expectedX;
expectedX.insert(1, (Vector(2) << -2000.,-4000.));
expectedX.insert(2, (Vector(2) << 2000., 4000.));
VectorValues actualX = VectorValues::Zero(expectedX);
lf.transposeMultiplyAdd(1.0, actualE, actualX);
EXPECT(assert_equal(expectedX, actualX));
// test gradient at zero
Matrix A; Vector b2; boost::tie(A,b2) = lf.jacobian();
VectorValues expectedG;
expectedG.insert(1, (Vector(2) << 20,-10));
expectedG.insert(2, (Vector(2) << -20, 10));
FastVector<Key> keys; keys += 1,2;
EXPECT(assert_equal(-A.transpose()*b2, expectedG.vector(keys)));
VectorValues actualG = lf.gradientAtZero();
EXPECT(assert_equal(expectedG, actualG));
}
/* ************************************************************************* */
TEST(JacobianFactor, default_error )
{
JacobianFactor f;
double actual = f.error(VectorValues());
DOUBLES_EQUAL(0.0, actual, 1e-15);
}
//* ************************************************************************* */
TEST(JacobianFactor, empty )
{
// create an empty factor
JacobianFactor f;
EXPECT(f.empty());
}
/* ************************************************************************* */
TEST(JacobianFactor, eliminate)
{
Matrix A01 = (Matrix(3, 3) <<
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0);
Vector b0 = (Vector(3) << 1.5, 1.5, 1.5);
Vector s0 = (Vector(3) << 1.6, 1.6, 1.6);
Matrix A10 = (Matrix(3, 3) <<
2.0, 0.0, 0.0,
0.0, 2.0, 0.0,
0.0, 0.0, 2.0);
Matrix A11 = (Matrix(3, 3) <<
-2.0, 0.0, 0.0,
0.0, -2.0, 0.0,
0.0, 0.0, -2.0);
Vector b1 = (Vector(3) << 2.5, 2.5, 2.5);
Vector s1 = (Vector(3) << 2.6, 2.6, 2.6);
Matrix A21 = (Matrix(3, 3) <<
3.0, 0.0, 0.0,
0.0, 3.0, 0.0,
0.0, 0.0, 3.0);
Vector b2 = (Vector(3) << 3.5, 3.5, 3.5);
Vector s2 = (Vector(3) << 3.6, 3.6, 3.6);
GaussianFactorGraph gfg;
gfg.add(1, A01, b0, noiseModel::Diagonal::Sigmas(s0, true));
gfg.add(0, A10, 1, A11, b1, noiseModel::Diagonal::Sigmas(s1, true));
gfg.add(1, A21, b2, noiseModel::Diagonal::Sigmas(s2, true));
Matrix zero3x3 = zeros(3,3);
Matrix A0 = gtsam::stack(3, &A10, &zero3x3, &zero3x3);
Matrix A1 = gtsam::stack(3, &A11, &A01, &A21);
Vector b = gtsam::concatVectors(3, &b1, &b0, &b2);
Vector sigmas = gtsam::concatVectors(3, &s1, &s0, &s2);
JacobianFactor combinedFactor(0, A0, 1, A1, b, noiseModel::Diagonal::Sigmas(sigmas, true));
GaussianFactorGraph::EliminationResult expected = combinedFactor.eliminate(list_of(0));
JacobianFactor::shared_ptr expectedJacobian = boost::dynamic_pointer_cast<
JacobianFactor>(expected.second);
GaussianFactorGraph::EliminationResult actual = EliminateQR(gfg, list_of(0));
JacobianFactor::shared_ptr actualJacobian = boost::dynamic_pointer_cast<
JacobianFactor>(actual.second);
EXPECT(assert_equal(*expected.first, *actual.first));
EXPECT(assert_equal(*expectedJacobian, *actualJacobian));
}
/* ************************************************************************* */
TEST(JacobianFactor, eliminate2 )
{
// sigmas
double sigma1 = 0.2;
double sigma2 = 0.1;
Vector sigmas = (Vector(4) << sigma1, sigma1, sigma2, sigma2);
// the combined linear factor
Matrix Ax2 = (Matrix(4, 2) <<
// x2
-1., 0.,
+0.,-1.,
1., 0.,
+0.,1.
);
Matrix Al1x1 = (Matrix(4, 4) <<
// l1 x1
1., 0., 0.00, 0., // f4
0., 1., 0.00, 0., // f4
0., 0., -1., 0., // f2
0., 0., 0.00,-1. // f2
);
// the RHS
Vector b2(4);
b2(0) = -0.2;
b2(1) = 0.3;
b2(2) = 0.2;
b2(3) = -0.1;
vector<pair<Key, Matrix> > meas;
meas.push_back(make_pair(2, Ax2));
meas.push_back(make_pair(11, Al1x1));
JacobianFactor combined(meas, b2, noiseModel::Diagonal::Sigmas(sigmas));
// eliminate the combined factor
pair<GaussianConditional::shared_ptr, JacobianFactor::shared_ptr>
actual = combined.eliminate(Ordering(list_of(2)));
// create expected Conditional Gaussian
double oldSigma = 0.0894427; // from when R was made unit
Matrix R11 = (Matrix(2, 2) <<
1.00, 0.00,
0.00, 1.00
)/oldSigma;
Matrix S12 = (Matrix(2, 4) <<
-0.20, 0.00,-0.80, 0.00,
+0.00,-0.20,+0.00,-0.80
)/oldSigma;
Vector d = (Vector(2) << 0.2,-0.14)/oldSigma;
GaussianConditional expectedCG(2, d, R11, 11, S12);
EXPECT(assert_equal(expectedCG, *actual.first, 1e-4));
// the expected linear factor
double sigma = 0.2236;
Matrix Bl1x1 = (Matrix(2, 4) <<
// l1 x1
1.00, 0.00, -1.00, 0.00,
0.00, 1.00, +0.00, -1.00
)/sigma;
Vector b1 = (Vector(2) << 0.0, 0.894427);
JacobianFactor expectedLF(11, Bl1x1, b1);
EXPECT(assert_equal(expectedLF, *actual.second,1e-3));
}
/* ************************************************************************* */
TEST(JacobianFactor, EliminateQR)
{
// Augmented Ab test case for whole factor graph
Matrix Ab = (Matrix(14, 11) <<
4., 0., 1., 4., 1., 0., 3., 6., 8., 8., 1.,
9., 2., 0., 1., 6., 3., 9., 6., 6., 9., 4.,
5., 3., 7., 9., 5., 5., 9., 1., 3., 7., 0.,
5., 6., 5., 7., 9., 4., 0., 1., 1., 3., 5.,
0., 0., 4., 5., 6., 6., 7., 9., 4., 5., 4.,
0., 0., 9., 4., 8., 6., 2., 1., 4., 1., 6.,
0., 0., 6., 0., 4., 2., 4., 0., 1., 9., 6.,
0., 0., 6., 6., 4., 4., 5., 5., 5., 8., 6.,
0., 0., 0., 0., 8., 0., 9., 8., 2., 8., 0.,
0., 0., 0., 0., 0., 9., 4., 6., 3., 2., 0.,
0., 0., 0., 0., 1., 1., 9., 1., 5., 5., 3.,
0., 0., 0., 0., 1., 1., 3., 3., 2., 0., 5.,
0., 0., 0., 0., 0., 0., 0., 0., 2., 4., 6.,
0., 0., 0., 0., 0., 0., 0., 0., 6., 3., 4.);
// Create factor graph
const SharedDiagonal sig_4D = noiseModel::Isotropic::Sigma(4, 0.5);
const SharedDiagonal sig_2D = noiseModel::Isotropic::Sigma(2, 0.5);
GaussianFactorGraph factors = list_of
(JacobianFactor(list_of(3)(5)(7)(9)(11), VerticalBlockMatrix(list_of(2)(2)(2)(2)(2)(1), Ab.block(0, 0, 4, 11)), sig_4D))
(JacobianFactor(list_of(5)(7)(9)(11), VerticalBlockMatrix(list_of(2)(2)(2)(2)(1), Ab.block(4, 2, 4, 9)), sig_4D))
(JacobianFactor(list_of(7)(9)(11), VerticalBlockMatrix(list_of(2)(2)(2)(1), Ab.block(8, 4, 4, 7)), sig_4D))
(JacobianFactor(list_of(11), VerticalBlockMatrix(list_of(2)(1), Ab.block(12, 8, 2, 3)), sig_2D));
// extract the dense matrix for the graph
Matrix actualDense = factors.augmentedJacobian();
EXPECT(assert_equal(2.0 * Ab, actualDense));
// Expected augmented matrix, both GaussianConditional (first 6 rows) and remaining factor (next 4 rows)
Matrix R = 2.0 * (Matrix(11, 11) <<
-12.1244, -5.1962, -5.2786, -8.6603, -10.5573, -5.9385, -11.3820, -7.2581, -8.7427, -13.4440, -5.3611,
0., 4.6904, 5.0254, 5.5432, 5.5737, 3.0153, -3.0153, -3.5635, -3.9290, -2.7412, 2.1625,
0., 0., -13.8160, -8.7166, -10.2245, -8.8666, -8.7632, -5.2544, -6.9192, -10.5537, -9.3250,
0., 0., 0., 6.5033, -1.1453, 1.3179, 2.5768, 5.5503, 3.6524, 1.3491, -2.5676,
0., 0., 0., 0., -9.6242, -2.1148, -9.3509, -10.5846, -3.5366, -6.8561, -3.2277,
0., 0., 0., 0., 0., 9.7887, 4.3551, 5.7572, 2.7876, 0.1611, 1.1769,
0., 0., 0., 0., 0., 0., -11.1139, -0.6521, -2.1943, -7.5529, -0.9081,
0., 0., 0., 0., 0., 0., 0., -4.6479, -1.9367, -6.5170, -3.7685,
0., 0., 0., 0., 0., 0., 0., 0., 8.2503, 3.3757, 6.8476,
0., 0., 0., 0., 0., 0., 0., 0., 0., -5.7095, -0.0090,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -7.1635);
GaussianConditional expectedFragment(
list_of(3)(5)(7)(9)(11), 3, VerticalBlockMatrix(list_of(2)(2)(2)(2)(2)(1), R));
// Eliminate (3 frontal variables, 6 scalar columns) using QR !!!!
GaussianFactorGraph::EliminationResult actual = EliminateQR(factors, list_of(3)(5)(7));
const JacobianFactor &actualJF = dynamic_cast<const JacobianFactor&>(*actual.second);
EXPECT(assert_equal(expectedFragment, *actual.first, 0.001));
EXPECT(assert_equal(size_t(2), actualJF.keys().size()));
EXPECT(assert_equal(Key(9), actualJF.keys()[0]));
EXPECT(assert_equal(Key(11), actualJF.keys()[1]));
EXPECT(assert_equal(Matrix(R.block(6, 6, 4, 2)), actualJF.getA(actualJF.begin()), 0.001));
EXPECT(assert_equal(Matrix(R.block(6, 8, 4, 2)), actualJF.getA(actualJF.begin()+1), 0.001));
EXPECT(assert_equal(Vector(R.col(10).segment(6, 4)), actualJF.getb(), 0.001));
EXPECT(!actualJF.get_model());
}
/* ************************************************************************* */
TEST ( JacobianFactor, constraint_eliminate1 )
{
// construct a linear constraint
Vector v(2); v(0)=1.2; v(1)=3.4;
JacobianFactor lc(1, eye(2), v, noiseModel::Constrained::All(2));
// eliminate it
pair<GaussianConditional::shared_ptr, JacobianFactor::shared_ptr>
actual = lc.eliminate(list_of(1));
// verify linear factor
EXPECT(actual.second->size() == 0);
// verify conditional Gaussian
Vector sigmas = (Vector(2) << 0.0, 0.0);
GaussianConditional expCG(1, v, eye(2), noiseModel::Diagonal::Sigmas(sigmas));
EXPECT(assert_equal(expCG, *actual.first));
}
/* ************************************************************************* */
TEST ( JacobianFactor, constraint_eliminate2 )
{
// Construct a linear constraint
// RHS
Vector b(2); b(0)=3.0; b(1)=4.0;
// A1 - invertible
Matrix A1(2,2);
A1(0,0) = 1.0 ; A1(0,1) = 2.0;
A1(1,0) = 2.0 ; A1(1,1) = 1.0;
// A2 - not invertible
Matrix A2(2,2);
A2(0,0) = 1.0 ; A2(0,1) = 2.0;
A2(1,0) = 2.0 ; A2(1,1) = 4.0;
JacobianFactor lc(1, A1, 2, A2, b, noiseModel::Constrained::All(2));
// eliminate x and verify results
pair<GaussianConditional::shared_ptr, JacobianFactor::shared_ptr>
actual = lc.eliminate(list_of(1));
// LF should be empty
// It's tricky to create Eigen matrices that are only zero along one dimension
Matrix m(1,2);
Matrix Aempty = m.topRows(0);
Vector bempty = m.block(0,0,0,1);
JacobianFactor expectedLF(2, Aempty, bempty, noiseModel::Constrained::All(0));
EXPECT(assert_equal(expectedLF, *actual.second));
// verify CG
Matrix R = (Matrix(2, 2) <<
1.0, 2.0,
0.0, 1.0);
Matrix S = (Matrix(2, 2) <<
1.0, 2.0,
0.0, 0.0);
Vector d = (Vector(2) << 3.0, 0.6666);
Vector sigmas = (Vector(2) << 0.0, 0.0);
GaussianConditional expectedCG(1, d, R, 2, S, noiseModel::Diagonal::Sigmas(sigmas));
EXPECT(assert_equal(expectedCG, *actual.first, 1e-4));
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
|
// SPDX-License-Identifier: Apache-2.0
#define CATCH_CONFIG_RUNNER
#include <catch2/catch_all.hpp>
int main(int argc, char const* argv[])
{
int const result = Catch::Session().run(argc, argv);
// avoid closing extern console to close on VScode/windows
// system("pause");
return result;
}
|
#include"Problem_Test.h"
Problem_Test::Problem_Test()
{
printf("Optimization Problem Testing ...\n\n");
//printf("This is not an Optimization Algorithm\n");
//printf("Made to test Optimization Problems!\n");
}
Problem_Test::~Problem_Test()
{
}
double Problem_Test::optimize(Optimization_Problem* problem, int number_of_problems, double** solution)
{
}
double Problem_Test::optimizeDebug(Optimization_Problem* optimization_problem, int number_of_problems, double** solution)
{
}
void Problem_Test::testSolution(double* chromosome, Optimization_Problem* problem)
{
double best_fitness;
problem->objectiveFunction(chromosome, &best_fitness);
printf("Best Fitness %f\n",best_fitness);
}
/*void Problem_Test::testSolution(double* chromosome, Optimization_Problem* problem)
{
double best_fitness;
problem->objectiveFunction(chromosome, &best_fitness);
}
*/
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "interpreter.h"
#include "primitives/transaction.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "pubkey.h"
#include "script/script.h"
#include "uint256.h"
using namespace std;
typedef vector<unsigned char> valtype;
namespace {
inline bool set_success(ScriptError* ret)
{
if (ret)
*ret = SCRIPT_ERR_OK;
return true;
}
inline bool set_error(ScriptError* ret, const ScriptError serror)
{
if (ret)
*ret = serror;
return false;
}
} // anon namespace
bool CastToBool(const valtype& vch)
{
for (unsigned int i = 0; i < vch.size(); i++)
{
if (vch[i] != 0)
{
// Can be negative zero
if (i == vch.size()-1 && vch[i] == 0x80)
return false;
return true;
}
}
return false;
}
/**
* Script is a stack machine (like Forth) that evaluates a predicate
* returning a bool indicating valid or not. There are no loops.
*/
#define stacktop(i) (stack.at(stack.size()+(i)))
#define altstacktop(i) (altstack.at(altstack.size()+(i)))
static inline void popstack(vector<valtype>& stack)
{
if (stack.empty())
throw runtime_error("popstack(): stack empty");
stack.pop_back();
}
bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
if (vchPubKey.size() < 33) {
// Non-canonical public key: too short
return false;
}
if (vchPubKey[0] == 0x04) {
if (vchPubKey.size() != 65) {
// Non-canonical public key: invalid length for uncompressed key
return false;
}
} else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
if (vchPubKey.size() != 33) {
// Non-canonical public key: invalid length for compressed key
return false;
}
} else {
// Non-canonical public key: neither compressed nor uncompressed
return false;
}
return true;
}
/**
* A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
* Where R and S are not negative (their first byte has its highest bit not set), and not
* excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
* in which case a single 0 byte is necessary and even required).
*
* See https://massgridtalk.org/index.php?topic=8392.msg127623#msg127623
*
* This function is consensus-critical since BIP66.
*/
bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
// * total-length: 1-byte length descriptor of everything that follows,
// excluding the sighash byte.
// * R-length: 1-byte length descriptor of the R value that follows.
// * R: arbitrary-length big-endian encoded R value. It must use the shortest
// possible encoding for a positive integers (which means no null bytes at
// the start, except a single one when the next byte has its highest bit set).
// * S-length: 1-byte length descriptor of the S value that follows.
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
// * sighash: 1-byte value indicating what data is hashed (not part of the DER
// signature)
// Minimum and maximum size constraints.
if (sig.size() < 9) return false;
if (sig.size() > 73) return false;
// A signature is of type 0x30 (compound).
if (sig[0] != 0x30) return false;
// Make sure the length covers the entire signature.
if (sig[1] != sig.size() - 3) return false;
// Extract the length of the R element.
unsigned int lenR = sig[3];
// Make sure the length of the S element is still inside the signature.
if (5 + lenR >= sig.size()) return false;
// Extract the length of the S element.
unsigned int lenS = sig[5 + lenR];
// Verify that the length of the signature matches the sum of the length
// of the elements.
if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
// Check whether the R element is an integer.
if (sig[2] != 0x02) return false;
// Zero-length integers are not allowed for R.
if (lenR == 0) return false;
// Negative numbers are not allowed for R.
if (sig[4] & 0x80) return false;
// Null bytes at the start of R are not allowed, unless R would
// otherwise be interpreted as a negative number.
if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
// Check whether the S element is an integer.
if (sig[lenR + 4] != 0x02) return false;
// Zero-length integers are not allowed for S.
if (lenS == 0) return false;
// Negative numbers are not allowed for S.
if (sig[lenR + 6] & 0x80) return false;
// Null bytes at the start of S are not allowed, unless S would otherwise be
// interpreted as a negative number.
if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
return true;
}
bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
if (!IsValidSignatureEncoding(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_DER);
}
std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
if (!CPubKey::CheckLowS(vchSigCopy)) {
return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
}
return true;
}
bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
if (vchSig.size() == 0) {
return false;
}
unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
return false;
return true;
}
bool CheckSignatureEncoding(const vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
// Empty signature. Not strictly DER encoded, but allowed to provide a
// compact way to provide an invalid signature for use with CHECK(MULTI)SIG
if (vchSig.size() == 0) {
return true;
}
if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_DER);
} else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
// serror is set
return false;
} else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
}
return true;
}
bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) {
if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) {
return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
}
return true;
}
bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
if (data.size() == 0) {
// Could have used OP_0.
return opcode == OP_0;
} else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
// Could have used OP_1 .. OP_16.
return opcode == OP_1 + (data[0] - 1);
} else if (data.size() == 1 && data[0] == 0x81) {
// Could have used OP_1NEGATE.
return opcode == OP_1NEGATE;
} else if (data.size() <= 75) {
// Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
return opcode == data.size();
} else if (data.size() <= 255) {
// Could have used OP_PUSHDATA.
return opcode == OP_PUSHDATA1;
} else if (data.size() <= 65535) {
// Could have used OP_PUSHDATA2.
return opcode == OP_PUSHDATA2;
}
return true;
}
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
{
static const CScriptNum bnZero(0);
static const CScriptNum bnOne(1);
static const CScriptNum bnFalse(0);
static const CScriptNum bnTrue(1);
static const valtype vchFalse(0);
static const valtype vchZero(0);
static const valtype vchTrue(1, 1);
CScript::const_iterator pc = script.begin();
CScript::const_iterator pend = script.end();
CScript::const_iterator pbegincodehash = script.begin();
opcodetype opcode;
valtype vchPushValue;
vector<bool> vfExec;
vector<valtype> altstack;
set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
if (script.size() > MAX_SCRIPT_SIZE)
return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
int nOpCount = 0;
bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
try
{
while (pc < pend)
{
bool fExec = !count(vfExec.begin(), vfExec.end(), false);
//
// Read instruction
//
if (!script.GetOp(pc, opcode, vchPushValue))
return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
// Note how OP_RESERVED does not count towards the opcode limit.
if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
return set_error(serror, SCRIPT_ERR_OP_COUNT);
if (opcode == OP_CAT ||
opcode == OP_SUBSTR ||
opcode == OP_LEFT ||
opcode == OP_RIGHT ||
opcode == OP_INVERT ||
opcode == OP_AND ||
opcode == OP_OR ||
opcode == OP_XOR ||
opcode == OP_2MUL ||
opcode == OP_2DIV ||
opcode == OP_MUL ||
opcode == OP_DIV ||
opcode == OP_MOD ||
opcode == OP_LSHIFT ||
opcode == OP_RSHIFT)
return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
return set_error(serror, SCRIPT_ERR_MINIMALDATA);
}
stack.push_back(vchPushValue);
} else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
switch (opcode)
{
//
// Push value
//
case OP_1NEGATE:
case OP_1:
case OP_2:
case OP_3:
case OP_4:
case OP_5:
case OP_6:
case OP_7:
case OP_8:
case OP_9:
case OP_10:
case OP_11:
case OP_12:
case OP_13:
case OP_14:
case OP_15:
case OP_16:
{
// ( -- value)
CScriptNum bn((int)opcode - (int)(OP_1 - 1));
stack.push_back(bn.getvch());
// The result of these opcodes should always be the minimal way to push the data
// they push, so no need for a CheckMinimalPush here.
}
break;
//
// Control
//
case OP_NOP:
break;
case OP_CHECKLOCKTIMEVERIFY:
{
if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
// not enabled; treat as a NOP2
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// Note that elsewhere numeric opcodes are limited to
// operands in the range -2**31+1 to 2**31-1, however it is
// legal for opcodes to produce results exceeding that
// range. This limitation is implemented by CScriptNum's
// default 4-byte limit.
//
// If we kept to that limit we'd have a year 2038 problem,
// even though the nLockTime field in transactions
// themselves is uint32 which only becomes meaningless
// after the year 2106.
//
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums, which are good until 2**39-1, well
// beyond the 2**32-1 limit of the nLockTime field itself.
const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKLOCKTIMEVERIFY.
if (nLockTime < 0)
return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
// Actually compare the specified lock time with the transaction.
if (!checker.CheckLockTime(nLockTime))
return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
break;
}
case OP_CHECKSEQUENCEVERIFY:
{
if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
// not enabled; treat as a NOP3
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// nSequence, like nLockTime, is a 32-bit unsigned integer
// field. See the comment in CHECKLOCKTIMEVERIFY regarding
// 5-byte numeric operands.
const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKSEQUENCEVERIFY.
if (nSequence < 0)
return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
// To provide for future soft-fork extensibility, if the
// operand has the disabled lock-time flag set,
// CHECKSEQUENCEVERIFY behaves as a NOP.
if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
break;
// Compare the specified sequence number with the input.
if (!checker.CheckSequence(nSequence))
return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
break;
}
case OP_NOP1: case OP_NOP4: case OP_NOP5:
case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
{
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
case OP_IF:
case OP_NOTIF:
{
// <expression> if [statements] [else [statements]] endif
bool fValue = false;
if (fExec)
{
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
valtype& vch = stacktop(-1);
fValue = CastToBool(vch);
if (opcode == OP_NOTIF)
fValue = !fValue;
popstack(stack);
}
vfExec.push_back(fValue);
}
break;
case OP_ELSE:
{
if (vfExec.empty())
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
vfExec.back() = !vfExec.back();
}
break;
case OP_ENDIF:
{
if (vfExec.empty())
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
vfExec.pop_back();
}
break;
case OP_VERIFY:
{
// (true -- ) or
// (false -- false) and return
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
bool fValue = CastToBool(stacktop(-1));
if (fValue)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_VERIFY);
}
break;
case OP_RETURN:
{
return set_error(serror, SCRIPT_ERR_OP_RETURN);
}
break;
//
// Stack ops
//
case OP_TOALTSTACK:
{
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
altstack.push_back(stacktop(-1));
popstack(stack);
}
break;
case OP_FROMALTSTACK:
{
if (altstack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
stack.push_back(altstacktop(-1));
popstack(altstack);
}
break;
case OP_2DROP:
{
// (x1 x2 -- )
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
popstack(stack);
popstack(stack);
}
break;
case OP_2DUP:
{
// (x1 x2 -- x1 x2 x1 x2)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-2);
valtype vch2 = stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_3DUP:
{
// (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
if (stack.size() < 3)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-3);
valtype vch2 = stacktop(-2);
valtype vch3 = stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
stack.push_back(vch3);
}
break;
case OP_2OVER:
{
// (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
if (stack.size() < 4)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-4);
valtype vch2 = stacktop(-3);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_2ROT:
{
// (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
if (stack.size() < 6)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-6);
valtype vch2 = stacktop(-5);
stack.erase(stack.end()-6, stack.end()-4);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_2SWAP:
{
// (x1 x2 x3 x4 -- x3 x4 x1 x2)
if (stack.size() < 4)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
swap(stacktop(-4), stacktop(-2));
swap(stacktop(-3), stacktop(-1));
}
break;
case OP_IFDUP:
{
// (x - 0 | x x)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-1);
if (CastToBool(vch))
stack.push_back(vch);
}
break;
case OP_DEPTH:
{
// -- stacksize
CScriptNum bn(stack.size());
stack.push_back(bn.getvch());
}
break;
case OP_DROP:
{
// (x -- )
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
popstack(stack);
}
break;
case OP_DUP:
{
// (x -- x x)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-1);
stack.push_back(vch);
}
break;
case OP_NIP:
{
// (x1 x2 -- x2)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
stack.erase(stack.end() - 2);
}
break;
case OP_OVER:
{
// (x1 x2 -- x1 x2 x1)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-2);
stack.push_back(vch);
}
break;
case OP_PICK:
case OP_ROLL:
{
// (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
// (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
popstack(stack);
if (n < 0 || n >= (int)stack.size())
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-n-1);
if (opcode == OP_ROLL)
stack.erase(stack.end()-n-1);
stack.push_back(vch);
}
break;
case OP_ROT:
{
// (x1 x2 x3 -- x2 x3 x1)
// x2 x1 x3 after first swap
// x2 x3 x1 after second swap
if (stack.size() < 3)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
swap(stacktop(-3), stacktop(-2));
swap(stacktop(-2), stacktop(-1));
}
break;
case OP_SWAP:
{
// (x1 x2 -- x2 x1)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
swap(stacktop(-2), stacktop(-1));
}
break;
case OP_TUCK:
{
// (x1 x2 -- x2 x1 x2)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-1);
stack.insert(stack.end()-2, vch);
}
break;
case OP_SIZE:
{
// (in -- in size)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn(stacktop(-1).size());
stack.push_back(bn.getvch());
}
break;
//
// Bitwise logic
//
case OP_EQUAL:
case OP_EQUALVERIFY:
//case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
{
// (x1 x2 - bool)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype& vch1 = stacktop(-2);
valtype& vch2 = stacktop(-1);
bool fEqual = (vch1 == vch2);
// OP_NOTEQUAL is disabled because it would be too easy to say
// something like n != 1 and have some wiseguy pass in 1 with extra
// zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
//if (opcode == OP_NOTEQUAL)
// fEqual = !fEqual;
popstack(stack);
popstack(stack);
stack.push_back(fEqual ? vchTrue : vchFalse);
if (opcode == OP_EQUALVERIFY)
{
if (fEqual)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
}
}
break;
//
// Numeric
//
case OP_1ADD:
case OP_1SUB:
case OP_NEGATE:
case OP_ABS:
case OP_NOT:
case OP_0NOTEQUAL:
{
// (in -- out)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn(stacktop(-1), fRequireMinimal);
switch (opcode)
{
case OP_1ADD: bn += bnOne; break;
case OP_1SUB: bn -= bnOne; break;
case OP_NEGATE: bn = -bn; break;
case OP_ABS: if (bn < bnZero) bn = -bn; break;
case OP_NOT: bn = (bn == bnZero); break;
case OP_0NOTEQUAL: bn = (bn != bnZero); break;
default: assert(!"invalid opcode"); break;
}
popstack(stack);
stack.push_back(bn.getvch());
}
break;
case OP_ADD:
case OP_SUB:
case OP_BOOLAND:
case OP_BOOLOR:
case OP_NUMEQUAL:
case OP_NUMEQUALVERIFY:
case OP_NUMNOTEQUAL:
case OP_LESSTHAN:
case OP_GREATERTHAN:
case OP_LESSTHANOREQUAL:
case OP_GREATERTHANOREQUAL:
case OP_MIN:
case OP_MAX:
{
// (x1 x2 -- out)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn1(stacktop(-2), fRequireMinimal);
CScriptNum bn2(stacktop(-1), fRequireMinimal);
CScriptNum bn(0);
switch (opcode)
{
case OP_ADD:
bn = bn1 + bn2;
break;
case OP_SUB:
bn = bn1 - bn2;
break;
case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
case OP_NUMEQUAL: bn = (bn1 == bn2); break;
case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
case OP_LESSTHAN: bn = (bn1 < bn2); break;
case OP_GREATERTHAN: bn = (bn1 > bn2); break;
case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
default: assert(!"invalid opcode"); break;
}
popstack(stack);
popstack(stack);
stack.push_back(bn.getvch());
if (opcode == OP_NUMEQUALVERIFY)
{
if (CastToBool(stacktop(-1)))
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
}
}
break;
case OP_WITHIN:
{
// (x min max -- out)
if (stack.size() < 3)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn1(stacktop(-3), fRequireMinimal);
CScriptNum bn2(stacktop(-2), fRequireMinimal);
CScriptNum bn3(stacktop(-1), fRequireMinimal);
bool fValue = (bn2 <= bn1 && bn1 < bn3);
popstack(stack);
popstack(stack);
popstack(stack);
stack.push_back(fValue ? vchTrue : vchFalse);
}
break;
//
// Crypto
//
case OP_RIPEMD160:
case OP_SHA1:
case OP_SHA256:
case OP_HASH160:
case OP_HASH256:
{
// (in -- hash)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype& vch = stacktop(-1);
valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
if (opcode == OP_RIPEMD160)
CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_SHA1)
CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_SHA256)
CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_HASH160)
CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_HASH256)
CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
popstack(stack);
stack.push_back(vchHash);
}
break;
case OP_CODESEPARATOR:
{
// Hash starts after the code separator
pbegincodehash = pc;
}
break;
case OP_CHECKSIG:
case OP_CHECKSIGVERIFY:
{
// (sig pubkey -- bool)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype& vchSig = stacktop(-2);
valtype& vchPubKey = stacktop(-1);
// Subset of script starting at the most recent codeseparator
CScript scriptCode(pbegincodehash, pend);
// Drop the signature, since there's no way for a signature to sign itself
scriptCode.FindAndDelete(CScript(vchSig));
if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
//serror is set
return false;
}
bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode);
popstack(stack);
popstack(stack);
stack.push_back(fSuccess ? vchTrue : vchFalse);
if (opcode == OP_CHECKSIGVERIFY)
{
if (fSuccess)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
}
}
break;
case OP_CHECKMULTISIG:
case OP_CHECKMULTISIGVERIFY:
{
// ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
int i = 1;
if ((int)stack.size() < i)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
nOpCount += nKeysCount;
if (nOpCount > MAX_OPS_PER_SCRIPT)
return set_error(serror, SCRIPT_ERR_OP_COUNT);
int ikey = ++i;
i += nKeysCount;
if ((int)stack.size() < i)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
if (nSigsCount < 0 || nSigsCount > nKeysCount)
return set_error(serror, SCRIPT_ERR_SIG_COUNT);
int isig = ++i;
i += nSigsCount;
if ((int)stack.size() < i)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// Subset of script starting at the most recent codeseparator
CScript scriptCode(pbegincodehash, pend);
// Drop the signatures, since there's no way for a signature to sign itself
for (int k = 0; k < nSigsCount; k++)
{
valtype& vchSig = stacktop(-isig-k);
scriptCode.FindAndDelete(CScript(vchSig));
}
bool fSuccess = true;
while (fSuccess && nSigsCount > 0)
{
valtype& vchSig = stacktop(-isig);
valtype& vchPubKey = stacktop(-ikey);
// Note how this makes the exact order of pubkey/signature evaluation
// distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
// See the script_(in)valid tests for details.
if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
// serror is set
return false;
}
// Check signature
bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode);
if (fOk) {
isig++;
nSigsCount--;
}
ikey++;
nKeysCount--;
// If there are more signatures left than keys left,
// then too many signatures have failed. Exit early,
// without checking any further signatures.
if (nSigsCount > nKeysCount)
fSuccess = false;
}
// Clean up stack of actual arguments
while (i-- > 1)
popstack(stack);
// A bug causes CHECKMULTISIG to consume one extra argument
// whose contents were not checked in any way.
//
// Unfortunately this is a potential source of mutability,
// so optionally verify it is exactly equal to zero prior
// to removing it from the stack.
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
popstack(stack);
stack.push_back(fSuccess ? vchTrue : vchFalse);
if (opcode == OP_CHECKMULTISIGVERIFY)
{
if (fSuccess)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
}
}
break;
default:
return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
}
// Size limits
if (stack.size() + altstack.size() > 1000)
return set_error(serror, SCRIPT_ERR_STACK_SIZE);
}
}
catch (...)
{
return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
}
if (!vfExec.empty())
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
return set_success(serror);
}
namespace {
/**
* Wrapper that serializes like CTransaction, but with the modifications
* required for the signature hash done in-place
*/
class CTransactionSignatureSerializer {
private:
const CTransaction &txTo; //! reference to the spending transaction (the one being serialized)
const CScript &scriptCode; //! output script being consumed
const unsigned int nIn; //! input index of txTo being signed
const bool fAnyoneCanPay; //! whether the hashtype has the SIGHASH_ANYONECANPAY flag set
const bool fHashSingle; //! whether the hashtype is SIGHASH_SINGLE
const bool fHashNone; //! whether the hashtype is SIGHASH_NONE
public:
CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
/** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
template<typename S>
void SerializeScriptCode(S &s, int nType, int nVersion) const {
CScript::const_iterator it = scriptCode.begin();
CScript::const_iterator itBegin = it;
opcodetype opcode;
unsigned int nCodeSeparators = 0;
while (scriptCode.GetOp(it, opcode)) {
if (opcode == OP_CODESEPARATOR)
nCodeSeparators++;
}
::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
it = itBegin;
while (scriptCode.GetOp(it, opcode)) {
if (opcode == OP_CODESEPARATOR) {
s.write((char*)&itBegin[0], it-itBegin-1);
itBegin = it;
}
}
if (itBegin != scriptCode.end())
s.write((char*)&itBegin[0], it-itBegin);
}
/** Serialize an input of txTo */
template<typename S>
void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
// In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
if (fAnyoneCanPay)
nInput = nIn;
// Serialize the prevout
::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
// Serialize the script
if (nInput != nIn)
// Blank out other inputs' signatures
::Serialize(s, CScriptBase(), nType, nVersion);
else
SerializeScriptCode(s, nType, nVersion);
// Serialize the nSequence
if (nInput != nIn && (fHashSingle || fHashNone))
// let the others update at will
::Serialize(s, (int)0, nType, nVersion);
else
::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
}
/** Serialize an output of txTo */
template<typename S>
void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
if (fHashSingle && nOutput != nIn)
// Do not lock-in the txout payee at other indices as txin
::Serialize(s, CTxOut(), nType, nVersion);
else
::Serialize(s, txTo.vout[nOutput], nType, nVersion);
}
/** Serialize txTo */
template<typename S>
void Serialize(S &s, int nType, int nVersion) const {
// Serialize nVersion
::Serialize(s, txTo.nVersion, nType, nVersion);
// Serialize vin
unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
::WriteCompactSize(s, nInputs);
for (unsigned int nInput = 0; nInput < nInputs; nInput++)
SerializeInput(s, nInput, nType, nVersion);
// Serialize vout
unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
::WriteCompactSize(s, nOutputs);
for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
SerializeOutput(s, nOutput, nType, nVersion);
// Serialize nLockTime
::Serialize(s, txTo.nLockTime, nType, nVersion);
}
};
} // anon namespace
uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
if (nIn >= txTo.vin.size()) {
// nIn out of range
return one;
}
// Check for invalid use of SIGHASH_SINGLE
if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
if (nIn >= txTo.vout.size()) {
// nOut out of range
return one;
}
}
// Wrapper to serialize only the necessary parts of the transaction being signed
CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
{
return pubkey.Verify(sighash, vchSig);
}
bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode) const
{
CPubKey pubkey(vchPubKey);
if (!pubkey.IsValid())
return false;
// Hash type is one byte tacked on to the end of the signature
vector<unsigned char> vchSig(vchSigIn);
if (vchSig.empty())
return false;
int nHashType = vchSig.back();
vchSig.pop_back();
uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType);
if (!VerifySignature(vchSig, pubkey, sighash))
return false;
return true;
}
bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
{
// There are two kinds of nLockTime: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nLockTime < LOCKTIME_THRESHOLD.
//
// We want to compare apples to apples, so fail the script
// unless the type of nLockTime being tested is the same as
// the nLockTime in the transaction.
if (!(
(txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
(txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
))
return false;
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nLockTime > (int64_t)txTo->nLockTime)
return false;
// Finally the nLockTime feature can be disabled and thus
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
// finalized by setting nSequence to maxint. The
// transaction would be allowed into the blockchain, making
// the opcode ineffective.
//
// Testing if this vin is not final is sufficient to
// prevent this condition. Alternatively we could test all
// inputs, but testing just this input minimizes the data
// required to prove correct CHECKLOCKTIMEVERIFY execution.
if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
return false;
return true;
}
bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
{
// Relative lock times are supported by comparing the passed
// in operand to the sequence number of the input.
const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
// Fail if the transaction's version number is not set high
// enough to trigger BIP 68 rules.
if (static_cast<uint32_t>(txTo->nVersion) < 2)
return false;
// Sequence numbers with their most significant bit set are not
// consensus constrained. Testing that the transaction's sequence
// number do not have this bit set prevents using this property
// to get around a CHECKSEQUENCEVERIFY check.
if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
return false;
// Mask off any bits that do not have consensus-enforced meaning
// before doing the integer comparisons
const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
// There are two kinds of nSequence: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
//
// We want to compare apples to apples, so fail the script
// unless the type of nSequenceMasked being tested is the same as
// the nSequenceMasked in the transaction.
if (!(
(txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
(txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
)) {
return false;
}
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nSequenceMasked > txToSequenceMasked)
return false;
return true;
}
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
{
set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
}
vector<vector<unsigned char> > stack, stackCopy;
if (!EvalScript(stack, scriptSig, flags, checker, serror))
// serror is set
return false;
if (flags & SCRIPT_VERIFY_P2SH)
stackCopy = stack;
if (!EvalScript(stack, scriptPubKey, flags, checker, serror))
// serror is set
return false;
if (stack.empty())
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
if (CastToBool(stack.back()) == false)
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
// Additional validation for spend-to-script-hash transactions:
if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
{
// scriptSig must be literals-only or validation fails
if (!scriptSig.IsPushOnly())
return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
// Restore stack.
swap(stack, stackCopy);
// stack cannot be empty here, because if it was the
// P2SH HASH <> EQUAL scriptPubKey would be evaluated with
// an empty stack and the EvalScript above would return false.
assert(!stack.empty());
const valtype& pubKeySerialized = stack.back();
CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
popstack(stack);
if (!EvalScript(stack, pubKey2, flags, checker, serror))
// serror is set
return false;
if (stack.empty())
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
if (!CastToBool(stack.back()))
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
}
// The CLEANSTACK check is only performed after potential P2SH evaluation,
// as the non-P2SH evaluation of a P2SH script will obviously not result in
// a clean stack (the P2SH inputs remain).
if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
// Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
// would be possible, which is not a softfork (and P2SH should be one).
assert((flags & SCRIPT_VERIFY_P2SH) != 0);
if (stack.size() != 1) {
return set_error(serror, SCRIPT_ERR_CLEANSTACK);
}
}
return set_success(serror);
}
|
//
// Created by raver119 on 31.10.2017.
//
#include <helpers/logger.h>
namespace nd4j {
#ifdef __CUDACC__
__host__
#endif
void Logger::info(const char *format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
fflush(stdout);
}
#ifdef __CUDACC__
__host__
#endif
void Logger::printv(const char *format, std::vector<int>& vec) {
printf("%s: {", format);
for(int e = 0; e < vec.size(); e++) {
auto v = vec[e];
printf("%i", v);
if (e < vec.size() - 1)
printf(", ");
}
printf("}\n");
fflush(stdout);
}
#ifdef __CUDACC__
__host__
#endif
void Logger::printv(const char *format, std::vector<Nd4jLong>& vec) {
printf("%s: {", format);
for(int e = 0; e < vec.size(); e++) {
auto v = vec[e];
printf("%lld", (long long) v);
if (e < vec.size() - 1)
printf(", ");
}
printf("}\n");
fflush(stdout);
}
}
|
// Copyright (c) 2018 Hartmut Kaiser
// Copyright (c) 2018 Bita Hasheminezhad
// Copyright (c) 2018 Parsa Amini
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(PHYLANX_PLUGINS_MATRIXOPS_SQUEEZE_OPERATION)
#define PHYLANX_PLUGINS_MATRIXOPS_SQUEEZE_OPERATION
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/base_primitive.hpp>
#include <phylanx/execution_tree/primitives/primitive_component_base.hpp>
#include <phylanx/ir/node_data.hpp>
#include <hpx/lcos/future.hpp>
#include <hpx/util/optional.hpp>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace phylanx { namespace execution_tree { namespace primitives
{
/// \brief squeeze removes single-dimensional entries from the shape of an
/// array.
/// \param a The scalar, vector, or matrix to perform squeeze over
/// \param axis Optional. If provided, squeeze is calculated along the
/// provided axis for >2d arrays.
class squeeze_operation
: public primitive_component_base
, public std::enable_shared_from_this<squeeze_operation>
{
protected:
hpx::future<primitive_argument_type> eval(
primitive_arguments_type const& operands,
primitive_arguments_type const& args,
eval_context ctx) const override;
public:
static match_pattern_type const match_data;
squeeze_operation() = default;
squeeze_operation(primitive_arguments_type&& operands,
std::string const& name, std::string const& codename);
private:
primitive_argument_type squeeze0d(primitive_argument_type&& arg,
hpx::util::optional<std::int64_t> axis) const;
primitive_argument_type squeeze1d(primitive_argument_type&& arg,
hpx::util::optional<std::int64_t> axis) const;
primitive_argument_type squeeze2d(primitive_argument_type&& arg,
hpx::util::optional<std::int64_t> axis) const;
template <typename T>
primitive_argument_type squeeze1d(ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze2d_axis0(ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze2d_axis1(ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze2d_all_axes(
ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze2d(ir::node_data<T>&& arg,
hpx::util::optional<std::int64_t> axis) const;
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
primitive_argument_type squeeze3d(primitive_argument_type&& arg,
hpx::util::optional<std::int64_t> axis) const;
template <typename T>
primitive_argument_type squeeze3d_axis0(ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze3d_axis1(ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze3d_axis2(ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze3d_all_axes(
ir::node_data<T>&& arg) const;
template <typename T>
primitive_argument_type squeeze3d(ir::node_data<T>&& arg,
hpx::util::optional<std::int64_t> axis) const;
#endif
};
inline primitive create_squeeze_operation(hpx::id_type const& locality,
primitive_arguments_type&& operands,
std::string const& name = "", std::string const& codename = "")
{
return create_primitive_component(
locality, "squeeze", std::move(operands), name, codename);
}
}}}
#endif
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "net/base/completion_once_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/test_completion_callback.h"
#include "net/log/net_log_with_source.h"
#include "net/socket/socket_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
using net::test::IsError;
using net::test::IsOk;
//-----------------------------------------------------------------------------
namespace net {
namespace {
const char kMsg1[] = "\0hello!\xff";
const int kLen1 = base::size(kMsg1);
const char kMsg2[] = "\0a2345678\0";
const int kLen2 = base::size(kMsg2);
const char kMsg3[] = "bye!";
const int kLen3 = base::size(kMsg3);
const char kMsg4[] = "supercalifragilisticexpialidocious";
const int kLen4 = base::size(kMsg4);
// Helper class for starting the next operation operation reentrantly after the
// previous operation completed asynchronously. When OnIOComplete is called,
// it will first verify that the previous operation behaved as expected. This is
// specified by either SetExpectedRead or SetExpectedWrite. It will then invoke
// a read or write operation specified by SetInvokeRead or SetInvokeWrite.
class ReentrantHelper {
public:
ReentrantHelper(StreamSocket* socket)
: socket_(socket),
verify_read_(false),
first_read_data_(nullptr),
first_len_(-1),
second_read_(false),
second_write_data_(nullptr),
second_len_(-1) {}
// Expect that the previous operation will return |first_len| and will fill
// |first_read_data_| with |first_read_data|.
void SetExpectedRead(const char* first_read_data, int first_len) {
verify_read_ = true;
first_read_buf_ = base::MakeRefCounted<IOBuffer>(first_len);
first_read_data_ = first_read_data;
first_len_ = first_len;
}
// Expect that the previous operation will return |first_len|.
void SetExpectedWrite(int first_len) {
verify_read_ = false;
first_len_ = first_len;
}
// After verifying expectations, invoke a read of |read_len| bytes into
// |read_buf|, notifying |callback| when complete.
void SetInvokeRead(scoped_refptr<IOBuffer> read_buf,
int read_len,
int second_rv,
CompletionOnceCallback callback) {
second_read_ = true;
second_read_buf_ = read_buf;
second_rv_ = second_rv;
second_callback_ = std::move(callback);
second_len_ = read_len;
}
// After verifying expectations, invoke a write of |write_len| bytes from
// |write_data|, notifying |callback| when complete.
void SetInvokeWrite(const char* write_data,
int write_len,
int second_rv,
CompletionOnceCallback callback) {
second_read_ = false;
second_rv_ = second_rv;
second_write_data_ = write_data;
second_callback_ = std::move(callback);
second_len_ = write_len;
}
// Returns the OnIOComplete callback for this helper.
CompletionOnceCallback callback() {
return base::BindOnce(&ReentrantHelper::OnIOComplete,
base::Unretained(this));
}
// Retuns the buffer where data is expected to have been written,
// when checked by SetExpectRead()
scoped_refptr<IOBuffer> read_buf() { return first_read_buf_; }
private:
void OnIOComplete(int rv) {
CHECK_NE(-1, first_len_) << "Expectation not set.";
CHECK_NE(-1, second_len_) << "Invocation not set.";
ASSERT_EQ(first_len_, rv);
if (verify_read_) {
ASSERT_EQ(std::string(first_read_data_, first_len_),
std::string(first_read_buf_->data(), rv));
}
if (second_read_) {
ASSERT_EQ(second_rv_, socket_->Read(second_read_buf_.get(), second_len_,
std::move(second_callback_)));
} else {
scoped_refptr<IOBuffer> write_buf =
base::MakeRefCounted<IOBuffer>(second_len_);
memcpy(write_buf->data(), second_write_data_, second_len_);
ASSERT_EQ(second_rv_, socket_->Write(write_buf.get(), second_len_,
std::move(second_callback_),
TRAFFIC_ANNOTATION_FOR_TESTS));
}
}
StreamSocket* socket_;
bool verify_read_;
scoped_refptr<IOBuffer> first_read_buf_;
const char* first_read_data_;
int first_len_;
CompletionOnceCallback second_callback_;
bool second_read_;
int second_rv_;
scoped_refptr<IOBuffer> second_read_buf_;
const char* second_write_data_;
int second_len_;
DISALLOW_COPY_AND_ASSIGN(ReentrantHelper);
};
class SequencedSocketDataTest : public TestWithTaskEnvironment {
public:
SequencedSocketDataTest();
~SequencedSocketDataTest() override;
// This method is used as the completion callback for an async read
// operation and when invoked, it verifies that the correct data was read,
// then reads from the socket and verifies that that it returns the correct
// value.
void ReentrantReadCallback(const char* data,
int len1,
int len2,
int expected_rv2,
int rv);
// This method is used at the completion callback for an async operation.
// When executed, verifies that |rv| equals |expected_rv| and then
// attempts an aync read from the socket into |read_buf_| (initialized
// to |read_buf_len|) using |callback|.
void ReentrantAsyncReadCallback(int len1, int len2, int rv);
// This method is used as the completion callback for an async write
// operation and when invoked, it verifies that the write returned correctly,
// then
// attempts to write to the socket and verifies that that it returns the
// correct value.
void ReentrantWriteCallback(int expected_rv1,
const char* data,
int len,
int expected_rv2,
int rv);
// This method is used at the completion callback for an async operation.
// When executed, verifies that |rv| equals |expected_rv| and then
// attempts an aync write of |data| with |callback|
void ReentrantAsyncWriteCallback(const char* data,
int len,
CompletionOnceCallback callback,
int expected_rv,
int rv);
// Callback which adds a failure if it's ever called.
void FailingCompletionCallback(int rv);
protected:
void Initialize(base::span<const MockRead> reads,
base::span<const MockWrite> writes);
void AssertSyncReadEquals(const char* data, int len);
void AssertAsyncReadEquals(const char* data, int len);
void AssertReadReturns(int len, int rv);
void AssertReadBufferEquals(const char* data, int len);
void AssertSyncWriteEquals(const char* data, int len);
void AssertAsyncWriteEquals(const char* data, int len);
void AssertWriteReturns(const char* data, int len, int rv);
bool IsPaused() const;
void Resume();
void RunUntilPaused();
// When a given test completes, data_.at_eof() is expected to
// match the value specified here. Most test should consume all
// reads and writes, but some tests verify error handling behavior
// do not consume all data.
void set_expect_eof(bool expect_eof) { expect_eof_ = expect_eof; }
CompletionOnceCallback failing_callback() {
return base::BindOnce(&SequencedSocketDataTest::FailingCompletionCallback,
base::Unretained(this));
}
TestCompletionCallback read_callback_;
scoped_refptr<IOBuffer> read_buf_;
TestCompletionCallback write_callback_;
std::unique_ptr<SequencedSocketData> data_;
MockClientSocketFactory socket_factory_;
bool expect_eof_;
std::unique_ptr<StreamSocket> sock_;
};
SequencedSocketDataTest::SequencedSocketDataTest() : expect_eof_(true) {}
SequencedSocketDataTest::~SequencedSocketDataTest() {
// Make sure no unexpected pending tasks will cause a failure.
base::RunLoop().RunUntilIdle();
if (expect_eof_) {
EXPECT_EQ(expect_eof_, data_->AllReadDataConsumed());
EXPECT_EQ(expect_eof_, data_->AllWriteDataConsumed());
}
}
void SequencedSocketDataTest::Initialize(base::span<const MockRead> reads,
base::span<const MockWrite> writes) {
data_ = std::make_unique<SequencedSocketData>(MockConnect(SYNCHRONOUS, OK),
reads, writes);
socket_factory_.AddSocketDataProvider(data_.get());
sock_ = socket_factory_.CreateTransportClientSocket(
AddressList(IPEndPoint(IPAddress::IPv4Localhost(), 443)),
nullptr /* socket_performance_watcher */, nullptr /* net_log */,
NetLogSource());
TestCompletionCallback callback;
EXPECT_EQ(OK, sock_->Connect(callback.callback()));
}
void SequencedSocketDataTest::AssertSyncReadEquals(const char* data, int len) {
// Issue the read, which will complete immediately.
AssertReadReturns(len, len);
AssertReadBufferEquals(data, len);
}
void SequencedSocketDataTest::AssertAsyncReadEquals(const char* data, int len) {
// Issue the read, which will be completed asynchronously.
AssertReadReturns(len, ERR_IO_PENDING);
EXPECT_TRUE(sock_->IsConnected());
// Now the read should complete.
ASSERT_EQ(len, read_callback_.WaitForResult());
AssertReadBufferEquals(data, len);
}
void SequencedSocketDataTest::AssertReadReturns(int len, int rv) {
read_buf_ = base::MakeRefCounted<IOBuffer>(len);
if (rv == ERR_IO_PENDING) {
ASSERT_EQ(rv, sock_->Read(read_buf_.get(), len, read_callback_.callback()));
ASSERT_FALSE(read_callback_.have_result());
} else {
ASSERT_EQ(rv, sock_->Read(read_buf_.get(), len, failing_callback()));
}
}
void SequencedSocketDataTest::AssertReadBufferEquals(const char* data,
int len) {
ASSERT_EQ(std::string(data, len), std::string(read_buf_->data(), len));
}
void SequencedSocketDataTest::AssertSyncWriteEquals(const char* data, int len) {
// Issue the write, which should be complete immediately.
AssertWriteReturns(data, len, len);
ASSERT_FALSE(write_callback_.have_result());
}
void SequencedSocketDataTest::AssertAsyncWriteEquals(const char* data,
int len) {
// Issue the read, which should be completed asynchronously.
AssertWriteReturns(data, len, ERR_IO_PENDING);
EXPECT_FALSE(read_callback_.have_result());
EXPECT_TRUE(sock_->IsConnected());
ASSERT_EQ(len, write_callback_.WaitForResult());
}
bool SequencedSocketDataTest::IsPaused() const {
return data_->IsPaused();
}
void SequencedSocketDataTest::Resume() {
data_->Resume();
}
void SequencedSocketDataTest::RunUntilPaused() {
data_->RunUntilPaused();
}
void SequencedSocketDataTest::AssertWriteReturns(const char* data,
int len,
int rv) {
scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(len);
memcpy(buf->data(), data, len);
if (rv == ERR_IO_PENDING) {
ASSERT_EQ(rv, sock_->Write(buf.get(), len, write_callback_.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
ASSERT_FALSE(write_callback_.have_result());
} else {
ASSERT_EQ(rv, sock_->Write(buf.get(), len, failing_callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
}
}
void SequencedSocketDataTest::ReentrantReadCallback(const char* data,
int len1,
int len2,
int expected_rv2,
int rv) {
ASSERT_EQ(len1, rv);
AssertReadBufferEquals(data, len1);
AssertReadReturns(len2, expected_rv2);
}
void SequencedSocketDataTest::ReentrantAsyncReadCallback(int expected_rv,
int len,
int rv) {
ASSERT_EQ(expected_rv, rv);
AssertReadReturns(len, ERR_IO_PENDING);
}
void SequencedSocketDataTest::ReentrantWriteCallback(int expected_rv1,
const char* data,
int len,
int expected_rv2,
int rv) {
ASSERT_EQ(expected_rv1, rv);
AssertWriteReturns(data, len, expected_rv2);
}
void SequencedSocketDataTest::ReentrantAsyncWriteCallback(
const char* data,
int len,
CompletionOnceCallback callback,
int expected_rv,
int rv) {
EXPECT_EQ(expected_rv, rv);
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(len);
memcpy(write_buf->data(), data, len);
EXPECT_THAT(sock_->Write(write_buf.get(), len, std::move(callback),
TRAFFIC_ANNOTATION_FOR_TESTS),
IsError(ERR_IO_PENDING));
}
void SequencedSocketDataTest::FailingCompletionCallback(int rv) {
ADD_FAILURE() << "Callback should not have been invoked";
}
// ----------- Read
TEST_F(SequencedSocketDataTest, SingleSyncRead) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
};
Initialize(reads, base::span<MockWrite>());
AssertSyncReadEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, MultipleSyncReads) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
MockRead(SYNCHRONOUS, kMsg2, kLen2, 1),
MockRead(SYNCHRONOUS, kMsg3, kLen3, 2),
MockRead(SYNCHRONOUS, kMsg3, kLen3, 3),
MockRead(SYNCHRONOUS, kMsg2, kLen2, 4),
MockRead(SYNCHRONOUS, kMsg3, kLen3, 5),
MockRead(SYNCHRONOUS, kMsg1, kLen1, 6),
};
Initialize(reads, base::span<MockWrite>());
AssertSyncReadEquals(kMsg1, kLen1);
AssertSyncReadEquals(kMsg2, kLen2);
AssertSyncReadEquals(kMsg3, kLen3);
AssertSyncReadEquals(kMsg3, kLen3);
AssertSyncReadEquals(kMsg2, kLen2);
AssertSyncReadEquals(kMsg3, kLen3);
AssertSyncReadEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, SingleAsyncRead) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0),
};
Initialize(reads, base::span<MockWrite>());
AssertAsyncReadEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, MultipleAsyncReads) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0),
MockRead(ASYNC, kMsg2, kLen2, 1),
MockRead(ASYNC, kMsg3, kLen3, 2),
MockRead(ASYNC, kMsg3, kLen3, 3),
MockRead(ASYNC, kMsg2, kLen2, 4),
MockRead(ASYNC, kMsg3, kLen3, 5),
MockRead(ASYNC, kMsg1, kLen1, 6),
};
Initialize(reads, base::span<MockWrite>());
AssertAsyncReadEquals(kMsg1, kLen1);
AssertAsyncReadEquals(kMsg2, kLen2);
AssertAsyncReadEquals(kMsg3, kLen3);
AssertAsyncReadEquals(kMsg3, kLen3);
AssertAsyncReadEquals(kMsg2, kLen2);
AssertAsyncReadEquals(kMsg3, kLen3);
AssertAsyncReadEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, MixedReads) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
MockRead(ASYNC, kMsg2, kLen2, 1),
MockRead(SYNCHRONOUS, kMsg3, kLen3, 2),
MockRead(ASYNC, kMsg3, kLen3, 3),
MockRead(SYNCHRONOUS, kMsg2, kLen2, 4),
MockRead(ASYNC, kMsg3, kLen3, 5),
MockRead(SYNCHRONOUS, kMsg1, kLen1, 6),
};
Initialize(reads, base::span<MockWrite>());
AssertSyncReadEquals(kMsg1, kLen1);
AssertAsyncReadEquals(kMsg2, kLen2);
AssertSyncReadEquals(kMsg3, kLen3);
AssertAsyncReadEquals(kMsg3, kLen3);
AssertSyncReadEquals(kMsg2, kLen2);
AssertAsyncReadEquals(kMsg3, kLen3);
AssertSyncReadEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, SyncReadFromCompletionCallback) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0), MockRead(SYNCHRONOUS, kMsg2, kLen2, 1),
};
Initialize(reads, base::span<MockWrite>());
read_buf_ = base::MakeRefCounted<IOBuffer>(kLen1);
ASSERT_EQ(
ERR_IO_PENDING,
sock_->Read(
read_buf_.get(), kLen1,
base::BindOnce(&SequencedSocketDataTest::ReentrantReadCallback,
base::Unretained(this), kMsg1, kLen1, kLen2, kLen2)));
base::RunLoop().RunUntilIdle();
AssertReadBufferEquals(kMsg2, kLen2);
}
TEST_F(SequencedSocketDataTest, ManyReentrantReads) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0),
MockRead(ASYNC, kMsg2, kLen2, 1),
MockRead(ASYNC, kMsg3, kLen3, 2),
MockRead(ASYNC, kMsg4, kLen4, 3),
};
Initialize(reads, base::span<MockWrite>());
read_buf_ = base::MakeRefCounted<IOBuffer>(kLen4);
ReentrantHelper helper3(sock_.get());
helper3.SetExpectedRead(kMsg3, kLen3);
helper3.SetInvokeRead(read_buf_, kLen4, ERR_IO_PENDING,
read_callback_.callback());
ReentrantHelper helper2(sock_.get());
helper2.SetExpectedRead(kMsg2, kLen2);
helper2.SetInvokeRead(helper3.read_buf(), kLen3, ERR_IO_PENDING,
helper3.callback());
ReentrantHelper helper(sock_.get());
helper.SetExpectedRead(kMsg1, kLen1);
helper.SetInvokeRead(helper2.read_buf(), kLen2, ERR_IO_PENDING,
helper2.callback());
sock_->Read(helper.read_buf().get(), kLen1, helper.callback());
ASSERT_EQ(kLen4, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg4, kLen4);
}
TEST_F(SequencedSocketDataTest, AsyncReadFromCompletionCallback) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0), MockRead(ASYNC, kMsg2, kLen2, 1),
};
Initialize(reads, base::span<MockWrite>());
read_buf_ = base::MakeRefCounted<IOBuffer>(kLen1);
ASSERT_EQ(ERR_IO_PENDING,
sock_->Read(
read_buf_.get(), kLen1,
base::BindOnce(&SequencedSocketDataTest::ReentrantReadCallback,
base::Unretained(this), kMsg1, kLen1, kLen2,
ERR_IO_PENDING)));
ASSERT_FALSE(read_callback_.have_result());
ASSERT_EQ(kLen2, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg2, kLen2);
}
TEST_F(SequencedSocketDataTest, SingleSyncReadTooEarly) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 1),
};
MockWrite writes[] = {MockWrite(SYNCHRONOUS, 0, 0)};
Initialize(reads, writes);
EXPECT_NONFATAL_FAILURE(AssertReadReturns(kLen1, ERR_UNEXPECTED),
"Unable to perform synchronous IO while stopped");
set_expect_eof(false);
}
TEST_F(SequencedSocketDataTest, SingleSyncReadSmallBuffer) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
};
Initialize(reads, base::span<MockWrite>());
// Read the first chunk.
AssertReadReturns(kLen1 - 1, kLen1 - 1);
AssertReadBufferEquals(kMsg1, kLen1 - 1);
// Then read the second chunk.
AssertReadReturns(1, 1);
AssertReadBufferEquals(kMsg1 + kLen1 - 1, 1);
}
TEST_F(SequencedSocketDataTest, SingleSyncReadLargeBuffer) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
};
Initialize(reads, base::span<MockWrite>());
scoped_refptr<IOBuffer> read_buf = base::MakeRefCounted<IOBuffer>(2 * kLen1);
ASSERT_EQ(kLen1, sock_->Read(read_buf.get(), 2 * kLen1, failing_callback()));
ASSERT_EQ(std::string(kMsg1, kLen1), std::string(read_buf->data(), kLen1));
}
TEST_F(SequencedSocketDataTest, SingleAsyncReadLargeBuffer) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0),
};
Initialize(reads, base::span<MockWrite>());
scoped_refptr<IOBuffer> read_buf = base::MakeRefCounted<IOBuffer>(2 * kLen1);
ASSERT_EQ(ERR_IO_PENDING,
sock_->Read(read_buf.get(), 2 * kLen1, read_callback_.callback()));
ASSERT_EQ(kLen1, read_callback_.WaitForResult());
ASSERT_EQ(std::string(kMsg1, kLen1), std::string(read_buf->data(), kLen1));
}
TEST_F(SequencedSocketDataTest, HangingRead) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 0),
};
Initialize(reads, base::span<MockWrite>());
scoped_refptr<IOBuffer> read_buf = base::MakeRefCounted<IOBuffer>(1);
ASSERT_EQ(ERR_IO_PENDING,
sock_->Read(read_buf.get(), 1, read_callback_.callback()));
ASSERT_FALSE(read_callback_.have_result());
// Even though the read is scheduled to complete at sequence number 0,
// verify that the read callback in never called.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(read_callback_.have_result());
}
// ----------- Write
TEST_F(SequencedSocketDataTest, SingleSyncWriteTooEarly) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 1),
};
MockRead reads[] = {MockRead(SYNCHRONOUS, 0, 0)};
Initialize(reads, writes);
EXPECT_NONFATAL_FAILURE(AssertWriteReturns(kMsg1, kLen1, ERR_UNEXPECTED),
"Unable to perform synchronous IO while stopped");
set_expect_eof(false);
}
TEST_F(SequencedSocketDataTest, SingleSyncWriteTooSmall) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 0),
};
Initialize(base::span<MockRead>(), writes);
// Expecting too small of a write triggers multiple expectation failures.
//
// The gtest infrastructure does not have a macro similar to
// EXPECT_NONFATAL_FAILURE which works when there is more than one
// failure.
//
// However, tests can gather the TestPartResultArray and directly
// validate the test failures. That's what the rest of this test does.
::testing::TestPartResultArray gtest_failures;
{
::testing::ScopedFakeTestPartResultReporter gtest_reporter(
::testing::ScopedFakeTestPartResultReporter::
INTERCEPT_ONLY_CURRENT_THREAD,
>est_failures);
AssertSyncWriteEquals(kMsg1, kLen1 - 1);
}
static const char* kExpectedFailures[] = {
"Expected: (data.length()) >= (expected_data.length())",
"Value of: actual_data == expected_data\n Actual: false\nExpected: true",
"Expected equality of these values:\n rv"};
ASSERT_EQ(base::size(kExpectedFailures),
static_cast<size_t>(gtest_failures.size()));
for (int i = 0; i < gtest_failures.size(); ++i) {
const ::testing::TestPartResult& result =
gtest_failures.GetTestPartResult(i);
EXPECT_TRUE(strstr(result.message(), kExpectedFailures[i]) != nullptr);
}
set_expect_eof(false);
}
TEST_F(SequencedSocketDataTest, SingleSyncPartialWrite) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1 - 1, 0),
MockWrite(SYNCHRONOUS, kMsg1 + kLen1 - 1, 1, 1),
};
Initialize(base::span<MockRead>(), writes);
// Attempt to write all of the message, but only some will be written.
AssertSyncWriteEquals(kMsg1, kLen1 - 1);
// Write the rest of the message.
AssertSyncWriteEquals(kMsg1 + kLen1 - 1, 1);
}
TEST_F(SequencedSocketDataTest, SingleSyncWrite) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 0),
};
Initialize(base::span<MockRead>(), writes);
AssertSyncWriteEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, MultipleSyncWrites) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 0),
MockWrite(SYNCHRONOUS, kMsg2, kLen2, 1),
MockWrite(SYNCHRONOUS, kMsg3, kLen3, 2),
MockWrite(SYNCHRONOUS, kMsg3, kLen3, 3),
MockWrite(SYNCHRONOUS, kMsg2, kLen2, 4),
MockWrite(SYNCHRONOUS, kMsg3, kLen3, 5),
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 6),
};
Initialize(base::span<MockRead>(), writes);
AssertSyncWriteEquals(kMsg1, kLen1);
AssertSyncWriteEquals(kMsg2, kLen2);
AssertSyncWriteEquals(kMsg3, kLen3);
AssertSyncWriteEquals(kMsg3, kLen3);
AssertSyncWriteEquals(kMsg2, kLen2);
AssertSyncWriteEquals(kMsg3, kLen3);
AssertSyncWriteEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, SingleAsyncWrite) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0),
};
Initialize(base::span<MockRead>(), writes);
AssertAsyncWriteEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, MultipleAsyncWrites) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0),
MockWrite(ASYNC, kMsg2, kLen2, 1),
MockWrite(ASYNC, kMsg3, kLen3, 2),
MockWrite(ASYNC, kMsg3, kLen3, 3),
MockWrite(ASYNC, kMsg2, kLen2, 4),
MockWrite(ASYNC, kMsg3, kLen3, 5),
MockWrite(ASYNC, kMsg1, kLen1, 6),
};
Initialize(base::span<MockRead>(), writes);
AssertAsyncWriteEquals(kMsg1, kLen1);
AssertAsyncWriteEquals(kMsg2, kLen2);
AssertAsyncWriteEquals(kMsg3, kLen3);
AssertAsyncWriteEquals(kMsg3, kLen3);
AssertAsyncWriteEquals(kMsg2, kLen2);
AssertAsyncWriteEquals(kMsg3, kLen3);
AssertAsyncWriteEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, MixedWrites) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 0),
MockWrite(ASYNC, kMsg2, kLen2, 1),
MockWrite(SYNCHRONOUS, kMsg3, kLen3, 2),
MockWrite(ASYNC, kMsg3, kLen3, 3),
MockWrite(SYNCHRONOUS, kMsg2, kLen2, 4),
MockWrite(ASYNC, kMsg3, kLen3, 5),
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 6),
};
Initialize(base::span<MockRead>(), writes);
AssertSyncWriteEquals(kMsg1, kLen1);
AssertAsyncWriteEquals(kMsg2, kLen2);
AssertSyncWriteEquals(kMsg3, kLen3);
AssertAsyncWriteEquals(kMsg3, kLen3);
AssertSyncWriteEquals(kMsg2, kLen2);
AssertAsyncWriteEquals(kMsg3, kLen3);
AssertSyncWriteEquals(kMsg1, kLen1);
}
TEST_F(SequencedSocketDataTest, SyncWriteFromCompletionCallback) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0),
MockWrite(SYNCHRONOUS, kMsg2, kLen2, 1),
};
Initialize(base::span<MockRead>(), writes);
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(kLen1);
memcpy(write_buf->data(), kMsg1, kLen1);
ASSERT_EQ(
ERR_IO_PENDING,
sock_->Write(
write_buf.get(), kLen1,
base::BindOnce(&SequencedSocketDataTest::ReentrantWriteCallback,
base::Unretained(this), kLen1, kMsg2, kLen2, kLen2),
TRAFFIC_ANNOTATION_FOR_TESTS));
base::RunLoop().RunUntilIdle();
}
TEST_F(SequencedSocketDataTest, AsyncWriteFromCompletionCallback) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0), MockWrite(ASYNC, kMsg2, kLen2, 1),
};
Initialize(base::span<MockRead>(), writes);
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(kLen1);
memcpy(write_buf->data(), kMsg1, kLen1);
ASSERT_EQ(ERR_IO_PENDING,
sock_->Write(
write_buf.get(), kLen1,
base::BindOnce(&SequencedSocketDataTest::ReentrantWriteCallback,
base::Unretained(this), kLen1, kMsg2, kLen2,
ERR_IO_PENDING),
TRAFFIC_ANNOTATION_FOR_TESTS));
ASSERT_FALSE(write_callback_.have_result());
ASSERT_EQ(kLen2, write_callback_.WaitForResult());
}
TEST_F(SequencedSocketDataTest, ManyReentrantWrites) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0),
MockWrite(ASYNC, kMsg2, kLen2, 1),
MockWrite(ASYNC, kMsg3, kLen3, 2),
MockWrite(ASYNC, kMsg4, kLen4, 3),
};
Initialize(base::span<MockRead>(), writes);
ReentrantHelper helper3(sock_.get());
helper3.SetExpectedWrite(kLen3);
helper3.SetInvokeWrite(kMsg4, kLen4, ERR_IO_PENDING,
write_callback_.callback());
ReentrantHelper helper2(sock_.get());
helper2.SetExpectedWrite(kLen2);
helper2.SetInvokeWrite(kMsg3, kLen3, ERR_IO_PENDING, helper3.callback());
ReentrantHelper helper(sock_.get());
helper.SetExpectedWrite(kLen1);
helper.SetInvokeWrite(kMsg2, kLen2, ERR_IO_PENDING, helper2.callback());
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(kLen1);
memcpy(write_buf->data(), kMsg1, kLen1);
sock_->Write(write_buf.get(), kLen1, helper.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS);
ASSERT_EQ(kLen4, write_callback_.WaitForResult());
}
// ----------- Mixed Reads and Writes
TEST_F(SequencedSocketDataTest, MixedSyncOperations) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
MockRead(SYNCHRONOUS, kMsg2, kLen2, 3),
};
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg2, kLen2, 1),
MockWrite(SYNCHRONOUS, kMsg3, kLen3, 2),
};
Initialize(reads, writes);
AssertSyncReadEquals(kMsg1, kLen1);
AssertSyncWriteEquals(kMsg2, kLen2);
AssertSyncWriteEquals(kMsg3, kLen3);
AssertSyncReadEquals(kMsg2, kLen2);
}
TEST_F(SequencedSocketDataTest, MixedAsyncOperations) {
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0), MockRead(ASYNC, kMsg2, kLen2, 3),
};
MockWrite writes[] = {
MockWrite(ASYNC, kMsg2, kLen2, 1), MockWrite(ASYNC, kMsg3, kLen3, 2),
};
Initialize(reads, writes);
AssertAsyncReadEquals(kMsg1, kLen1);
AssertAsyncWriteEquals(kMsg2, kLen2);
AssertAsyncWriteEquals(kMsg3, kLen3);
AssertAsyncReadEquals(kMsg2, kLen2);
}
TEST_F(SequencedSocketDataTest, InterleavedAsyncOperations) {
// Order of completion is read, write, write, read.
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0), MockRead(ASYNC, kMsg2, kLen2, 3),
};
MockWrite writes[] = {
MockWrite(ASYNC, kMsg2, kLen2, 1), MockWrite(ASYNC, kMsg3, kLen3, 2),
};
Initialize(reads, writes);
// Issue the write, which will block until the read completes.
AssertWriteReturns(kMsg2, kLen2, ERR_IO_PENDING);
// Issue the read which will return first.
AssertReadReturns(kLen1, ERR_IO_PENDING);
ASSERT_EQ(kLen1, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg1, kLen1);
// Run posted OnWriteComplete().
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(write_callback_.have_result());
ASSERT_EQ(kLen2, write_callback_.WaitForResult());
// Issue the read, which will block until the write completes.
AssertReadReturns(kLen2, ERR_IO_PENDING);
// Issue the writes which will return first.
AssertWriteReturns(kMsg3, kLen3, ERR_IO_PENDING);
ASSERT_EQ(kLen3, write_callback_.WaitForResult());
ASSERT_EQ(kLen2, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg2, kLen2);
}
TEST_F(SequencedSocketDataTest, InterleavedMixedOperations) {
// Order of completion is read, write, write, read.
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
MockRead(ASYNC, kMsg2, kLen2, 3),
MockRead(ASYNC, kMsg3, kLen3, 5),
};
MockWrite writes[] = {
MockWrite(ASYNC, kMsg2, kLen2, 1),
MockWrite(SYNCHRONOUS, kMsg3, kLen3, 2),
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 4),
};
Initialize(reads, writes);
// Issue the write, which will block until the read completes.
AssertWriteReturns(kMsg2, kLen2, ERR_IO_PENDING);
// Issue the writes which will complete immediately.
AssertSyncReadEquals(kMsg1, kLen1);
ASSERT_FALSE(write_callback_.have_result());
ASSERT_EQ(kLen2, write_callback_.WaitForResult());
// Issue the read, which will block until the write completes.
AssertReadReturns(kLen2, ERR_IO_PENDING);
// Issue the writes which will complete immediately.
AssertSyncWriteEquals(kMsg3, kLen3);
ASSERT_FALSE(read_callback_.have_result());
ASSERT_EQ(kLen2, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg2, kLen2);
// Issue the read, which will block until the write completes.
AssertReadReturns(kLen2, ERR_IO_PENDING);
// Issue the writes which will complete immediately.
AssertSyncWriteEquals(kMsg1, kLen1);
ASSERT_FALSE(read_callback_.have_result());
ASSERT_EQ(kLen3, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg3, kLen3);
}
TEST_F(SequencedSocketDataTest, AsyncReadFromWriteCompletionCallback) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0),
};
MockRead reads[] = {
MockRead(ASYNC, kMsg2, kLen2, 1),
};
Initialize(reads, writes);
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(kLen1);
memcpy(write_buf->data(), kMsg1, kLen1);
ASSERT_EQ(
ERR_IO_PENDING,
sock_->Write(
write_buf.get(), kLen1,
base::BindOnce(&SequencedSocketDataTest::ReentrantAsyncReadCallback,
base::Unretained(this), kLen1, kLen2),
TRAFFIC_ANNOTATION_FOR_TESTS));
ASSERT_FALSE(read_callback_.have_result());
ASSERT_EQ(kLen2, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg2, kLen2);
}
TEST_F(SequencedSocketDataTest, AsyncWriteFromReadCompletionCallback) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg2, kLen2, 1),
};
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0),
};
Initialize(reads, writes);
scoped_refptr<IOBuffer> read_buf = base::MakeRefCounted<IOBuffer>(kLen1);
ASSERT_EQ(
ERR_IO_PENDING,
sock_->Read(
read_buf.get(), kLen1,
base::BindOnce(&SequencedSocketDataTest::ReentrantAsyncWriteCallback,
base::Unretained(this), kMsg2, kLen2,
write_callback_.callback(), kLen1)));
ASSERT_FALSE(write_callback_.have_result());
ASSERT_EQ(kLen2, write_callback_.WaitForResult());
}
TEST_F(SequencedSocketDataTest, MixedReentrantOperations) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0), MockWrite(ASYNC, kMsg3, kLen3, 2),
};
MockRead reads[] = {
MockRead(ASYNC, kMsg2, kLen2, 1), MockRead(ASYNC, kMsg4, kLen4, 3),
};
Initialize(reads, writes);
read_buf_ = base::MakeRefCounted<IOBuffer>(kLen4);
ReentrantHelper helper3(sock_.get());
helper3.SetExpectedWrite(kLen3);
helper3.SetInvokeRead(read_buf_, kLen4, ERR_IO_PENDING,
read_callback_.callback());
ReentrantHelper helper2(sock_.get());
helper2.SetExpectedRead(kMsg2, kLen2);
helper2.SetInvokeWrite(kMsg3, kLen3, ERR_IO_PENDING, helper3.callback());
ReentrantHelper helper(sock_.get());
helper.SetExpectedWrite(kLen1);
helper.SetInvokeRead(helper2.read_buf(), kLen2, ERR_IO_PENDING,
helper2.callback());
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(kLen1);
memcpy(write_buf->data(), kMsg1, kLen1);
sock_->Write(write_buf.get(), kLen1, helper.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS);
ASSERT_EQ(kLen4, read_callback_.WaitForResult());
}
TEST_F(SequencedSocketDataTest, MixedReentrantOperationsThenSynchronousRead) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg1, kLen1, 0), MockWrite(ASYNC, kMsg3, kLen3, 2),
};
MockRead reads[] = {
MockRead(ASYNC, kMsg2, kLen2, 1), MockRead(SYNCHRONOUS, kMsg4, kLen4, 3),
};
Initialize(reads, writes);
read_buf_ = base::MakeRefCounted<IOBuffer>(kLen4);
ReentrantHelper helper3(sock_.get());
helper3.SetExpectedWrite(kLen3);
helper3.SetInvokeRead(read_buf_, kLen4, kLen4, failing_callback());
ReentrantHelper helper2(sock_.get());
helper2.SetExpectedRead(kMsg2, kLen2);
helper2.SetInvokeWrite(kMsg3, kLen3, ERR_IO_PENDING, helper3.callback());
ReentrantHelper helper(sock_.get());
helper.SetExpectedWrite(kLen1);
helper.SetInvokeRead(helper2.read_buf(), kLen2, ERR_IO_PENDING,
helper2.callback());
scoped_refptr<IOBuffer> write_buf = base::MakeRefCounted<IOBuffer>(kLen1);
memcpy(write_buf->data(), kMsg1, kLen1);
ASSERT_EQ(ERR_IO_PENDING,
sock_->Write(write_buf.get(), kLen1, helper.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
base::RunLoop().RunUntilIdle();
AssertReadBufferEquals(kMsg4, kLen4);
}
TEST_F(SequencedSocketDataTest, MixedReentrantOperationsThenSynchronousWrite) {
MockWrite writes[] = {
MockWrite(ASYNC, kMsg2, kLen2, 1),
MockWrite(SYNCHRONOUS, kMsg4, kLen4, 3),
};
MockRead reads[] = {
MockRead(ASYNC, kMsg1, kLen1, 0), MockRead(ASYNC, kMsg3, kLen3, 2),
};
Initialize(reads, writes);
read_buf_ = base::MakeRefCounted<IOBuffer>(kLen4);
ReentrantHelper helper3(sock_.get());
helper3.SetExpectedRead(kMsg3, kLen3);
helper3.SetInvokeWrite(kMsg4, kLen4, kLen4, failing_callback());
ReentrantHelper helper2(sock_.get());
helper2.SetExpectedWrite(kLen2);
helper2.SetInvokeRead(helper3.read_buf(), kLen3, ERR_IO_PENDING,
helper3.callback());
ReentrantHelper helper(sock_.get());
helper.SetExpectedRead(kMsg1, kLen1);
helper.SetInvokeWrite(kMsg2, kLen2, ERR_IO_PENDING, helper2.callback());
ASSERT_EQ(ERR_IO_PENDING,
sock_->Read(helper.read_buf().get(), kLen1, helper.callback()));
base::RunLoop().RunUntilIdle();
}
// Test the basic case where a read is paused.
TEST_F(SequencedSocketDataTest, PauseAndResume_PauseRead) {
MockRead reads[] = {
MockRead(ASYNC, ERR_IO_PENDING, 0), MockRead(ASYNC, kMsg1, kLen1, 1),
};
Initialize(reads, base::span<MockWrite>());
AssertReadReturns(kLen1, ERR_IO_PENDING);
ASSERT_FALSE(read_callback_.have_result());
RunUntilPaused();
ASSERT_TRUE(IsPaused());
// Spinning the message loop should do nothing.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(read_callback_.have_result());
ASSERT_TRUE(IsPaused());
Resume();
ASSERT_FALSE(IsPaused());
ASSERT_TRUE(read_callback_.have_result());
ASSERT_EQ(kLen1, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg1, kLen1);
}
// Test the case where a read that will be paused is started before write that
// completes before the pause.
TEST_F(SequencedSocketDataTest, PauseAndResume_WritePauseRead) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMsg1, kLen1, 0),
};
MockRead reads[] = {
MockRead(ASYNC, ERR_IO_PENDING, 1), MockRead(ASYNC, kMsg2, kLen2, 2),
};
Initialize(reads, writes);
AssertReadReturns(kLen2, ERR_IO_PENDING);
ASSERT_FALSE(read_callback_.have_result());
// Nothing should happen until the write starts.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(read_callback_.have_result());
ASSERT_FALSE(IsPaused());
AssertSyncWriteEquals(kMsg1, kLen1);
RunUntilPaused();
ASSERT_FALSE(read_callback_.have_result());
ASSERT_TRUE(IsPaused());
// Spinning the message loop should do nothing.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(read_callback_.have_result());
ASSERT_TRUE(IsPaused());
Resume();
ASSERT_FALSE(IsPaused());
ASSERT_TRUE(read_callback_.have_result());
ASSERT_EQ(kLen2, read_callback_.WaitForResult());
AssertReadBufferEquals(kMsg2, kLen2);
}
// Test the basic case where a write is paused.
TEST_F(SequencedSocketDataTest, PauseAndResume_PauseWrite) {
MockWrite writes[] = {
MockWrite(ASYNC, ERR_IO_PENDING, 0), MockWrite(ASYNC, kMsg1, kLen1, 1),
};
Initialize(base::span<MockRead>(), writes);
AssertWriteReturns(kMsg1, kLen1, ERR_IO_PENDING);
ASSERT_FALSE(write_callback_.have_result());
RunUntilPaused();
ASSERT_TRUE(IsPaused());
// Spinning the message loop should do nothing.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(write_callback_.have_result());
ASSERT_TRUE(IsPaused());
Resume();
ASSERT_FALSE(IsPaused());
ASSERT_TRUE(write_callback_.have_result());
ASSERT_EQ(kLen1, write_callback_.WaitForResult());
}
// Test the case where a write that will be paused is started before read that
// completes before the pause.
TEST_F(SequencedSocketDataTest, PauseAndResume_ReadPauseWrite) {
MockWrite writes[] = {
MockWrite(ASYNC, ERR_IO_PENDING, 1), MockWrite(ASYNC, kMsg2, kLen2, 2),
};
MockRead reads[] = {
MockRead(SYNCHRONOUS, kMsg1, kLen1, 0),
};
Initialize(reads, writes);
AssertWriteReturns(kMsg2, kLen2, ERR_IO_PENDING);
ASSERT_FALSE(write_callback_.have_result());
// Nothing should happen until the write starts.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(write_callback_.have_result());
ASSERT_FALSE(IsPaused());
AssertSyncReadEquals(kMsg1, kLen1);
RunUntilPaused();
ASSERT_FALSE(write_callback_.have_result());
ASSERT_TRUE(IsPaused());
// Spinning the message loop should do nothing.
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(write_callback_.have_result());
ASSERT_TRUE(IsPaused());
Resume();
ASSERT_FALSE(IsPaused());
ASSERT_TRUE(write_callback_.have_result());
ASSERT_EQ(kLen2, write_callback_.WaitForResult());
}
} // namespace
} // namespace net
|
/*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaVMEMeter
Authors: Marco Petrone, Paolo Quadrani
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "albaVMEMeter.h"
#include "albaVMEOutputMeter.h"
#include "albaVMELandmarkCloud.h"
#include "albaVMELandmark.h"
#include "mmaMeter.h"
#include "mmaMaterial.h"
#include "albaTransform.h"
#include "albaStorageElement.h"
#include "albaIndent.h"
#include "albaDataPipeCustom.h"
#include "mmuIdFactory.h"
#include "albaGUI.h"
#include "albaAbsMatrixPipe.h"
#include "vtkALBASmartPointer.h"
#include "albaRWI.h"
#include "albaGUIDialogPreview.h"
#include "vtkALBADataPipe.h"
#include "vtkMath.h"
#include "vtkALBASmartPointer.h"
#include "vtkPolyData.h"
#include "vtkLine.h"
#include "vtkLineSource.h"
#include "vtkAppendPolyData.h"
#include "vtkProbeFilter.h"
#include "vtkXYPlotActor.h"
#include "vtkTextProperty.h"
#include "vtkProperty2D.h"
#include "vtkRenderer.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"
#include <assert.h>
ALBA_ID_IMP(albaVMEMeter::LENGTH_THRESHOLD_EVENT);
//-------------------------------------------------------------------------
albaCxxTypeMacro(albaVMEMeter)
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
albaVMEMeter::albaVMEMeter()
//-------------------------------------------------------------------------
{
m_Distance = -1.0;
m_Angle = 0.0;
m_StartVmeName = "";
m_EndVme1Name = "";
m_EndVme2Name = "";
m_ProbeVmeName = "";
albaNEW(m_Transform);
albaVMEOutputMeter *output = albaVMEOutputMeter::New(); // an output with no data
output->SetTransform(m_Transform); // force my transform in the output
SetOutput(output);
vtkNEW(m_LineSource);
vtkNEW(m_LineSource2);
vtkNEW(m_Goniometer);
vtkNEW(m_PolyData);
m_Goniometer->AddInput(m_LineSource->GetOutput());
m_Goniometer->AddInput(m_LineSource2->GetOutput());
m_PolyData->DeepCopy(m_Goniometer->GetOutput());
albaNEW(m_TmpTransform);
DependsOnLinkedNodeOn();
// attach a data pipe which creates a bridge between VTK and ALBA
albaDataPipeCustom *dpipe = albaDataPipeCustom::New();
dpipe->SetDependOnAbsPose(true);
SetDataPipe(dpipe);
dpipe->SetInput(m_PolyData);
// histogram
// Probing tool
vtkNEW(m_ProbingLine);
m_ProbingLine->SetResolution(512);
m_ProbedVME = NULL;
albaString plot_title = _("Density vs. Length (mm)");
albaString plot_titleX = "mm";
albaString plot_titleY = _("Dens.");
vtkNEW(m_PlotActor);
m_PlotActor->GetProperty()->SetColor(0.02,0.06,0.62);
m_PlotActor->GetProperty()->SetLineWidth(2);
m_PlotActor->SetPosition(0.03,0.03);
m_PlotActor->SetPosition2(0.9,0.9);
m_PlotActor->SetLabelFormat("%g");
m_PlotActor->SetXRange(0,300);
m_PlotActor->SetPlotCoordinate(0,300);
m_PlotActor->SetNumberOfXLabels(10);
m_PlotActor->SetXValuesToIndex();
m_PlotActor->SetTitle(plot_title);
m_PlotActor->SetXTitle(plot_titleX);
m_PlotActor->SetYTitle(plot_titleY);
vtkTextProperty* tprop = m_PlotActor->GetTitleTextProperty();
tprop->SetColor(0.02,0.06,0.62);
tprop->SetFontFamilyToArial();
tprop->ItalicOff();
tprop->BoldOff();
tprop->SetFontSize(12);
m_PlotActor->SetPlotColor(0,.8,.3,.3);
m_HistogramDialog = NULL;
m_HistogramRWI = NULL;
m_GenerateHistogram = 0;
}
//-------------------------------------------------------------------------
albaVMEMeter::~albaVMEMeter()
//-------------------------------------------------------------------------
{
albaDEL(m_Transform);
vtkDEL(m_LineSource);
vtkDEL(m_LineSource2);
vtkDEL(m_Goniometer);
albaDEL(m_TmpTransform);
vtkDEL(m_PolyData);
SetOutput(NULL);
if(m_HistogramRWI)
m_HistogramRWI->m_RenFront->RemoveActor(m_PlotActor);
vtkDEL(m_PlotActor);
vtkDEL(m_ProbingLine);
cppDEL(m_HistogramDialog);
}
//-------------------------------------------------------------------------
int albaVMEMeter::DeepCopy(albaVME *a)
//-------------------------------------------------------------------------
{
if (Superclass::DeepCopy(a)==ALBA_OK)
{
albaVMEMeter *meter = albaVMEMeter::SafeDownCast(a);
m_Transform->SetMatrix(meter->m_Transform->GetMatrix());
albaDataPipeCustom *dpipe = albaDataPipeCustom::SafeDownCast(GetDataPipe());
if (dpipe)
{
dpipe->SetInput(m_Goniometer->GetOutput());
m_Goniometer->Update();
}
return ALBA_OK;
}
return ALBA_ERROR;
}
//-------------------------------------------------------------------------
bool albaVMEMeter::Equals(albaVME *vme)
//-------------------------------------------------------------------------
{
bool ret = false;
if (Superclass::Equals(vme))
{
ret = m_Transform->GetMatrix() == ((albaVMEMeter *)vme)->m_Transform->GetMatrix() && \
GetLink("StartVME") == ((albaVMEMeter *)vme)->GetLink("StartVME") && \
GetLink("EndVME1") == ((albaVMEMeter *)vme)->GetLink("EndVME1") && \
GetLink("EndVME2") == ((albaVMEMeter *)vme)->GetLink("EndVME2") && \
GetLink("PlottedVME") == ((albaVMEMeter *)vme)->GetLink("EndVME2");
}
return ret;
}
//-------------------------------------------------------------------------
int albaVMEMeter::InternalInitialize()
//-------------------------------------------------------------------------
{
if (Superclass::InternalInitialize()==ALBA_OK)
{
// force material allocation
GetMaterial();
return ALBA_OK;
}
return ALBA_ERROR;
}
//-------------------------------------------------------------------------
mmaMaterial *albaVMEMeter::GetMaterial()
//-------------------------------------------------------------------------
{
mmaMaterial *material = (mmaMaterial *)GetAttribute("MaterialAttributes");
if (material == NULL)
{
material = mmaMaterial::New();
SetAttribute("MaterialAttributes", material);
}
return material;
}
//-------------------------------------------------------------------------
albaVMEOutputPolyline *albaVMEMeter::GetPolylineOutput()
//-------------------------------------------------------------------------
{
return (albaVMEOutputPolyline *)GetOutput();
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMatrix(const albaMatrix &mat)
//-------------------------------------------------------------------------
{
m_Transform->SetMatrix(mat);
Modified();
}
//-------------------------------------------------------------------------
bool albaVMEMeter::IsAnimated()
//-------------------------------------------------------------------------
{
return false;
}
//-------------------------------------------------------------------------
void albaVMEMeter::GetLocalTimeStamps(std::vector<albaTimeStamp> &kframes)
//-------------------------------------------------------------------------
{
kframes.clear(); // no timestamps
}
//-----------------------------------------------------------------------
void albaVMEMeter::InternalPreUpdate()
//-----------------------------------------------------------------------
{
GetMeterAttributes();
}
//-----------------------------------------------------------------------
void albaVMEMeter::InternalUpdate()
//-----------------------------------------------------------------------
{
GetMeterAttributes()->m_ThresholdEvent = GetGenerateEvent();
GetMeterAttributes()->m_DeltaPercent = GetDeltaPercent();
GetMeterAttributes()->m_InitMeasure = GetInitMeasure();
double threshold = GetMeterAttributes()->m_InitMeasure * (1 + GetMeterAttributes()->m_DeltaPercent / 100.0);
UpdateLinks();
if (GetMeterMode() == albaVMEMeter::POINT_DISTANCE)
{
albaVME *start_vme = GetStartVME();
albaVME *end_vme = GetEnd1VME();
bool start_ok = true, end_ok = true;
double orientation[3];
if (start_vme && end_vme)
{
start_vme->GetOutput()->Update();
start_vme->GetOutput()->GetAbsPose(m_StartPoint, orientation);
end_vme->GetOutput()->Update();
end_vme->GetOutput()->GetAbsPose(m_EndPoint, orientation);
}
else
{
start_ok = false;
end_ok = false;
}
if (start_ok && end_ok)
{
// compute distance between points
m_Distance = sqrt(vtkMath::Distance2BetweenPoints(m_StartPoint, m_EndPoint));
if(GetMeterMeasureType() == albaVMEMeter::RELATIVE_MEASURE)
m_Distance -= GetMeterAttributes()->m_InitMeasure;
// compute start point in local coordinate system
double local_start[3];
m_TmpTransform->SetMatrix(GetOutput()->GetAbsTransform()->GetMatrix());
m_TmpTransform->Invert();
m_TmpTransform->TransformPoint(m_StartPoint, local_start); // m_TmpTransform needed to fix a memory leaks of GetInverse()
// compute end point in local coordinate system
double local_end[3];
m_TmpTransform->TransformPoint(m_EndPoint,local_end);
m_LineSource2->SetPoint1(local_start[0],local_start[1],local_start[2]);
m_LineSource2->SetPoint2(local_start[0],local_start[1],local_start[2]);
m_LineSource2->Update();
m_LineSource->SetPoint1(local_start[0],local_start[1],local_start[2]);
m_LineSource->SetPoint2(local_end[0],local_end[1],local_end[2]);
m_LineSource->Update();
m_Goniometer->Modified();
GenerateHistogram(m_GenerateHistogram);
}
else
m_Distance = -1;
GetOutput()->Update();
InvokeEvent(this,VME_OUTPUT_DATA_UPDATE);
if(GetMeterMeasureType() == albaVMEMeter::ABSOLUTE_MEASURE && GetMeterAttributes()->m_ThresholdEvent > 0 && m_Distance >= 0 && m_Distance >= threshold)
InvokeEvent(this,LENGTH_THRESHOLD_EVENT);
}
else if (GetMeterMode() == albaVMEMeter::LINE_DISTANCE)
{
albaVME *start_vme = GetStartVME();
albaVME *end1_vme = GetEnd1VME();
albaVME *end2_vme = GetEnd2VME();
bool start_ok = true, end1_ok = true, end2_ok = true;
double orientation[3];
if (start_vme && end1_vme && end2_vme)
{
start_vme->GetOutput()->Update();
start_vme->GetOutput()->GetAbsPose(m_StartPoint, orientation);
end1_vme->GetOutput()->Update();
end1_vme->GetOutput()->GetAbsPose(m_EndPoint, orientation);
end2_vme->GetOutput()->Update();
end2_vme->GetOutput()->GetAbsPose(m_EndPoint2, orientation);
}
else
{
start_ok = false;
end1_ok = false;
end2_ok = false;
}
if (start_ok && end1_ok && end2_ok)
{
double start[3],p1[3],p2[3],p3[3],t;
start[0] = m_StartPoint[0];
start[1] = m_StartPoint[1];
start[2] = m_StartPoint[2];
p1[0] = m_EndPoint[0];
p1[1] = m_EndPoint[1];
p1[2] = m_EndPoint[2];
p2[0] = m_EndPoint2[0];
p2[1] = m_EndPoint2[1];
p2[2] = m_EndPoint2[2];
vtkLine::DistanceToLine(start,p1,p2,t,p3);
// compute distance between start and closest point
m_Distance = sqrt(vtkMath::Distance2BetweenPoints(start,p3));
if(GetMeterMeasureType() == albaVMEMeter::RELATIVE_MEASURE)
m_Distance -= GetMeterAttributes()->m_InitMeasure;
// compute start point in local coordinate system
double local_start[3];
m_TmpTransform->SetMatrix(GetOutput()->GetAbsTransform()->GetMatrix());
m_TmpTransform->Invert();
m_TmpTransform->TransformPoint(start,local_start);
// compute end point in local coordinate system
double local_closest[3];
m_TmpTransform->TransformPoint(p3,local_closest);
double local_p1[3];
m_TmpTransform->TransformPoint(p1,local_p1);
double local_p2[3];
m_TmpTransform->TransformPoint(p2,local_p2);
m_LineSource->SetPoint1(local_start);
m_LineSource->SetPoint2(local_closest);
m_LineSource->Update();
m_LineSource2->SetPoint1(local_p1);
m_LineSource2->SetPoint2(local_p2);
m_LineSource2->Update();
m_Goniometer->Modified();
}
else
m_Distance = -1;
GetOutput()->Update();
InvokeEvent(this,VME_OUTPUT_DATA_UPDATE);
if(GetMeterMeasureType() == albaVMEMeter::ABSOLUTE_MEASURE && GetMeterAttributes()->m_ThresholdEvent > 0 && m_Distance >= 0 && m_Distance >= threshold)
InvokeEvent(this,LENGTH_THRESHOLD_EVENT);
}
else if (GetMeterMode() == albaVMEMeter::LINE_ANGLE)
{
albaVME *start_vme = GetStartVME();
albaVME *end1_vme = GetEnd1VME();
albaVME *end2_vme = GetEnd2VME();
double orientation[3];
bool start_ok = true, end1_ok = true, end2_ok = true;
if (start_vme && end1_vme && end2_vme)
{
start_vme->GetOutput()->Update();
start_vme->GetOutput()->GetAbsPose(m_StartPoint, orientation);
end1_vme->GetOutput()->Update();
end1_vme->GetOutput()->GetAbsPose(m_EndPoint, orientation);
end2_vme->GetOutput()->Update();
end2_vme->GetOutput()->GetAbsPose(m_EndPoint2, orientation);
}
else
{
start_ok = false;
end1_ok = false;
end2_ok = false;
}
if (start_ok && end1_ok && end2_ok)
{
double start[3],p1[3],p2[3], v1[3], v2[3], vn1, vn2, s;
start[0] = m_StartPoint[0];
start[1] = m_StartPoint[1];
start[2] = m_StartPoint[2];
p1[0] = m_EndPoint[0];
p1[1] = m_EndPoint[1];
p1[2] = m_EndPoint[2];
p2[0] = m_EndPoint2[0];
p2[1] = m_EndPoint2[1];
p2[2] = m_EndPoint2[2];
v1[0] = p1[0] - start[0];
v1[1] = p1[1] - start[1];
v1[2] = p1[2] - start[2];
v2[0] = p2[0] - start[0];
v2[1] = p2[1] - start[1];
v2[2] = p2[2] - start[2];
vn1 = vtkMath::Norm(v1);
vn2 = vtkMath::Norm(v2);
s = vtkMath::Dot(v1,v2);
if(vn1 != 0 && vn2 != 0)
{
m_Angle = acos(s / (vn1 * vn2)) * vtkMath::RadiansToDegrees();
if(GetMeterMeasureType() == albaVMEMeter::RELATIVE_MEASURE)
m_Angle -= GetMeterAttributes()->m_InitMeasure;
}
else
m_Angle = 0;
// compute points in local coordinate system
double local_start[3];
m_TmpTransform->SetMatrix(GetOutput()->GetAbsTransform()->GetMatrix());
m_TmpTransform->Invert();
m_TmpTransform->TransformPoint(start,local_start);
double local_end1[3];
m_TmpTransform->TransformPoint(p1,local_end1);
double local_end2[3];
m_TmpTransform->TransformPoint(p2,local_end2);
m_LineSource->SetPoint1(local_start);
m_LineSource->SetPoint2(local_end1);
m_LineSource->Update();
m_LineSource2->SetPoint1(local_start);
m_LineSource2->SetPoint2(local_end2);
m_LineSource2->Update();
m_Goniometer->Modified();
}
else
m_Angle = 0;
GetOutput()->Update();
InvokeEvent(this, VME_OUTPUT_DATA_UPDATE);
if(GetMeterMeasureType() == albaVMEMeter::ABSOLUTE_MEASURE && GetMeterAttributes()->m_ThresholdEvent > 0 && m_Angle > 0 && m_Angle >= threshold)
InvokeEvent(this, LENGTH_THRESHOLD_EVENT);
}
m_Goniometer->Update();
vtkPolyData *polydata = m_Goniometer->GetOutput();
int num = m_Goniometer->GetOutput()->GetNumberOfPoints();
vtkIdType pointId[2];
vtkALBASmartPointer<vtkCellArray> cellArray;
for(int i = 0; i< num;i++)
{
if (i > 0)
{
pointId[0] = i - 1;
pointId[1] = i;
cellArray->InsertNextCell(2 , pointId);
}
}
m_PolyData->SetPoints(m_Goniometer->GetOutput()->GetPoints());
m_PolyData->SetLines(cellArray);
m_PolyData->Update();
}
//-----------------------------------------------------------------------
int albaVMEMeter::InternalStore(albaStorageElement *parent)
//-----------------------------------------------------------------------
{
if (Superclass::InternalStore(parent)==ALBA_OK)
{
parent->StoreMatrix("Transform",&m_Transform->GetMatrix());
return ALBA_OK;
}
return ALBA_ERROR;
}
//-----------------------------------------------------------------------
int albaVMEMeter::InternalRestore(albaStorageElement *node)
//-----------------------------------------------------------------------
{
if (Superclass::InternalRestore(node)==ALBA_OK)
{
albaMatrix matrix;
if (node->RestoreMatrix("Transform",&matrix)==ALBA_OK)
{
m_Transform->SetMatrix(matrix);
return ALBA_OK;
}
}
return ALBA_ERROR;
}
//-----------------------------------------------------------------------
void albaVMEMeter::Print(std::ostream& os, const int tabs)
//-----------------------------------------------------------------------
{
Superclass::Print(os,tabs);
albaIndent indent(tabs);
albaMatrix m = m_Transform->GetMatrix();
m.Print(os,indent.GetNextIndent());
}
//-------------------------------------------------------------------------
char** albaVMEMeter::GetIcon()
{
#include "albaVMEMeter.xpm"
return albaVMEMeter_xpm;
}
//-------------------------------------------------------------------------
mmaMeter *albaVMEMeter::GetMeterAttributes()
//-------------------------------------------------------------------------
{
mmaMeter *meter_attributes = (mmaMeter *)GetAttribute("MeterAttributes");
if (meter_attributes == NULL)
{
meter_attributes = mmaMeter::New();
SetAttribute("MeterAttributes", meter_attributes);
}
return meter_attributes;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterMode(int mode)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_MeterMode = mode;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetMeterMode()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_MeterMode;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetDistanceRange(double min, double max)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_DistanceRange[0] = min;
GetMeterAttributes()->m_DistanceRange[1] = max;
}
//-------------------------------------------------------------------------
double *albaVMEMeter::GetDistanceRange()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_DistanceRange;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterColorMode(int mode)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_ColorMode = mode;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetMeterColorMode()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_ColorMode;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterMeasureType(int type)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_MeasureType = type;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetMeterMeasureType()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_MeasureType;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterRepresentation(int representation)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_Representation = representation;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetMeterRepresentation()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_Representation;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterCapping(int capping)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_Capping = capping;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetMeterCapping()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_Capping;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetGenerateEvent(int generate)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_GenerateEvent = generate;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetGenerateEvent()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_GenerateEvent;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetInitMeasure(double init_measure)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_InitMeasure = init_measure;
}
//-------------------------------------------------------------------------
double albaVMEMeter::GetInitMeasure()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_InitMeasure;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterRadius(double radius)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_TubeRadius = radius;
}
//-------------------------------------------------------------------------
double albaVMEMeter::GetMeterRadius()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_TubeRadius;
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetDeltaPercent(int delta_percent)
//-------------------------------------------------------------------------
{
GetMeterAttributes()->m_DeltaPercent = delta_percent;
}
//-------------------------------------------------------------------------
int albaVMEMeter::GetDeltaPercent()
//-------------------------------------------------------------------------
{
return GetMeterAttributes()->m_DeltaPercent;
}
//-------------------------------------------------------------------------
double albaVMEMeter::GetDistance()
//-------------------------------------------------------------------------
{
return m_Distance;
}
//-------------------------------------------------------------------------
double albaVMEMeter::GetAngle()
//-------------------------------------------------------------------------
{
return m_Angle;
}
//-------------------------------------------------------------------------
albaGUI* albaVMEMeter::CreateGui()
//-------------------------------------------------------------------------
{
int num_mode = 3;
const wxString mode_choices_string[] = {_("point distance"), _("line distance"), _("line angle")};
m_Gui = albaVME::CreateGui(); // Called to show info about vmes' type and name
m_Gui->SetListener(this);
m_Gui->Divider();
m_Gui->Combo(ID_METER_MODE,_("Mode"),&(GetMeterAttributes()->m_MeterMode),num_mode,mode_choices_string,_("Choose the meter mode"));
m_Gui->Divider();
UpdateLinks();
m_Gui->Button(ID_START_METER_LINK,&m_StartVmeName,_("Start"), _("Select the start vme for the meter"));
m_Gui->Button(ID_END1_METER_LINK,&m_EndVme1Name,_("End 1"), _("Select the end vme for point distance"));
m_Gui->Button(ID_END2_METER_LINK,&m_EndVme2Name,_("End 2"), _("Select the vme representing \nthe point for line distance"));
if(GetMeterAttributes()->m_MeterMode == POINT_DISTANCE)
m_Gui->Enable(ID_END2_METER_LINK,false);
m_Gui->Bool(ID_PLOT_PROFILE,_("Plot profile"),&m_GenerateHistogram);
m_Gui->Enable(ID_PLOT_PROFILE,GetMeterAttributes()->m_MeterMode == POINT_DISTANCE);
m_Gui->Button(ID_PLOTTED_VME_LINK,&m_ProbeVmeName,_("Probed"), _("Select the vme that will be plotted"));
m_Gui->Enable(ID_PLOTTED_VME_LINK, GetMeterAttributes()->m_MeterMode == POINT_DISTANCE);
m_Gui->Divider();
InternalUpdate();
GetPolylineOutput()->Update();
return m_Gui;
}
//-------------------------------------------------------------------------
void albaVMEMeter::UpdateLinks()
//-------------------------------------------------------------------------
{
albaID sub_id = -1;
albaVME *start_vme = GetStartVME();
albaVME *end_vme1 = GetEnd1VME();
albaVME *end_vme2 = GetEnd2VME();
albaVME *probedVme = GetPlottedVME();
m_StartVmeName = start_vme ? start_vme->GetName() : _("none");
m_EndVme1Name = end_vme1 ? end_vme1->GetName() : _("none");
m_EndVme2Name = end_vme2 ? end_vme2->GetName() : _("none");
m_ProbedVME = albaVMEVolumeGray::SafeDownCast(probedVme);
m_ProbeVmeName = probedVme ? probedVme->GetName() : _("none");
}
//-------------------------------------------------------------------------
void albaVMEMeter::OnEvent(albaEventBase *alba_event)
//-------------------------------------------------------------------------
{
// events to be sent up or down in the tree are simply forwarded
if (albaEvent *e = albaEvent::SafeDownCast(alba_event))
{
switch(e->GetId())
{
case ID_START_METER_LINK:
case ID_END1_METER_LINK:
case ID_END2_METER_LINK:
{
albaID button_id = e->GetId();
albaString title = _("Choose meter vme link");
e->SetId(VME_CHOOSE);
e->SetPointer(&albaVMEMeter::VMEAccept);
e->SetString(&title);
ForwardUpEvent(e);
albaVME *n = e->GetVme();
if (n != NULL)
{
if (button_id == ID_START_METER_LINK)
{
SetLink("StartVME", n);
m_StartVmeName = n->GetName();
}
else if (button_id == ID_END1_METER_LINK)
{
SetLink("EndVME1", n);
m_EndVme1Name = n->GetName();
}
else
{
SetLink("EndVME2", n);
m_EndVme2Name = n->GetName();
}
m_Gui->Update();
}
}
break;
case ID_PLOTTED_VME_LINK:
{
albaID button_id = e->GetId();
albaString title = _("Choose meter vme link");
e->SetId(VME_CHOOSE);
e->SetPointer(&albaVMEMeter::VolumeAccept);
e->SetString(&title);
ForwardUpEvent(e);
albaVME *n = e->GetVme();
if (n != NULL)
{
SetLink("PlottedVME",n);
m_ProbedVME = albaVMEVolumeGray::SafeDownCast(n);
m_ProbeVmeName = n->GetName();
CreateHistogram();
}
m_Gui->Update();
}
break;
case ID_METER_MODE:
{
if(GetMeterAttributes()->m_MeterMode == POINT_DISTANCE)
{
m_Gui->Enable(ID_END2_METER_LINK,false);
}
else if(GetMeterAttributes()->m_MeterMode == LINE_DISTANCE)
{
m_Gui->Enable(ID_END2_METER_LINK,true);
}
else if(GetMeterAttributes()->m_MeterMode == LINE_ANGLE)
{
m_Gui->Enable(ID_END2_METER_LINK,true);
}
m_Gui->Enable(ID_PLOT_PROFILE,GetMeterAttributes()->m_MeterMode == POINT_DISTANCE);
m_Gui->Enable(ID_PLOTTED_VME_LINK, GetMeterAttributes()->m_MeterMode == POINT_DISTANCE);
this->Modified();
albaID button_id = e->GetId();
e->SetId(CAMERA_UPDATE);
ForwardUpEvent(e);
}
break;
case ID_PLOT_PROFILE:
{
// Histogram dialog
if(m_HistogramDialog == NULL)
{
int width = 400;
int height = 300;
int x_init,y_init;
x_init = albaGetFrame()->GetPosition().x;
y_init = albaGetFrame()->GetPosition().y;
m_HistogramDialog = new albaGUIDialogPreview(_("Histogram Dialog"), albaCLOSEWINDOW | albaUSERWI);
m_HistogramRWI = m_HistogramDialog->GetRWI();
m_HistogramRWI->SetListener(this);
m_HistogramRWI->m_RenFront->AddActor2D(m_PlotActor);
m_HistogramRWI->m_RenFront->SetBackground(1,1,1);
m_HistogramRWI->SetSize(0,0,width,height);
m_HistogramDialog->SetSize(x_init,y_init,width,height);
m_HistogramDialog->Show(FALSE);
}
GenerateHistogram(m_GenerateHistogram);
}
break;
default:
albaVME::OnEvent(alba_event);
}
}
else
{
Superclass::OnEvent(alba_event);
}
}
//-------------------------------------------------------------------------
void albaVMEMeter::SetMeterLink(const char *link_name, albaVME *n)
//-------------------------------------------------------------------------
{
SetLink(link_name, n);
}
//-------------------------------------------------------------------------
albaVME *albaVMEMeter::GetStartVME()
//-------------------------------------------------------------------------
{
return GetLink("StartVME");
}
//-------------------------------------------------------------------------
albaVME *albaVMEMeter::GetEnd1VME()
//-------------------------------------------------------------------------
{
return GetLink("EndVME1");
}
//-------------------------------------------------------------------------
albaVME *albaVMEMeter::GetEnd2VME()
//-------------------------------------------------------------------------
{
return GetLink("EndVME2");
}
//-------------------------------------------------------------------------
albaVME *albaVMEMeter::GetPlottedVME()
//-------------------------------------------------------------------------
{
return GetLink("PlottedVME");
}
//----------------------------------------------------------------------------
void albaVMEMeter::GenerateHistogram(int generate)
//----------------------------------------------------------------------------
{
if(m_HistogramDialog)
{
m_GenerateHistogram = generate;
if (m_GenerateHistogram)
{
CreateHistogram();
m_HistogramRWI->m_RwiBase->Render();
}
m_HistogramDialog->Show(m_GenerateHistogram != 0);
}
}
//----------------------------------------------------------------------------
void albaVMEMeter::CreateHistogram()
//----------------------------------------------------------------------------
{
if (m_ProbedVME != NULL)
{
vtkDataSet *probed_data = m_ProbedVME->GetOutput()->GetVTKData();
probed_data->Update();
m_PlotActor->SetXRange(0,m_Distance);
double srY[2];
m_ProbedVME->GetOutput()->GetVTKData()->GetScalarRange(srY);
m_PlotActor->SetYRange(srY);
m_PlotActor->SetPlotCoordinate(0,m_Distance);
double b[6];
m_ProbedVME->GetOutput()->GetBounds(b);
m_ProbingLine->SetPoint1(m_StartPoint);
m_ProbingLine->SetPoint2(m_EndPoint);
m_ProbingLine->SetResolution((int)m_Distance);
m_ProbingLine->Update();
vtkALBASmartPointer<vtkProbeFilter> prober;
prober->SetInput(m_ProbingLine->GetOutput());
prober->SetSource(probed_data);
prober->Update();
m_PlotActor->RemoveAllInputs();
vtkPolyData *probimg_result = prober->GetPolyDataOutput();
m_PlotActor->AddInput(probimg_result);
if(m_HistogramRWI) m_HistogramRWI->m_RwiBase->Render();
}
}
|
// Andrei Gaponenko, 2011
#include <string>
#include <vector>
#include <algorithm>
// Mu2e includes.
#include "Offline/MCDataProducts/inc/StatusG4.hh"
#include "Offline/MCDataProducts/inc/StepPointMC.hh"
#include "Offline/Mu2eUtilities/inc/compressSimParticleCollection.hh"
// art includes.
#include "fhiclcpp/ParameterSet.h"
#include "art/Framework/Core/EDFilter.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Principal/Run.h"
#include "art_root_io/TFileService.h"
//#define AGDEBUG(stuff) std::cerr<<"AG: "<<__FILE__<<", line "<<__LINE__<<": "<<stuff<<std::endl;
#define AGDEBUG(stuff)
namespace mu2e {
// Use art::Ptr instead of bare ptr to get the desired sorting
typedef std::set<art::Ptr<SimParticle> > TrackSet;
// Adapter for compressSimParticleCollection()
class ParticleSelector {
public:
ParticleSelector(const TrackSet& m) {
for(TrackSet::const_iterator i = m.begin(); i!=m.end(); ++i) {
m_keys.insert((*i)->id());
}
}
bool operator[]( cet::map_vector_key key ) const {
return m_keys.find(key) != m_keys.end();
}
private:
std::set<cet::map_vector_key> m_keys;
};
//================================================================
class FilterVDHits : public art::EDFilter {
std::string _outInstanceName;
std::string _inModuleLabel;
std::string _inInstanceName;
typedef StepPointMC::VolumeId_type VolumeId;
// The anticipated use case is to select hits for one or a few
// VDs. Therefore we use a vector: the log-vs-linear efficiency
// gain from using a set is probably negated by the overheads
// of dealing with a more complicated data structure that is not
// local in memory.
std::vector<VolumeId> _vids; // preserve hits in just those volumes
bool _positionCut;
std::vector<double> _positionCenter;
std::vector<double> _positionHalfLength;
bool _storeParents;
bool _storeExtraHits; // store all VD hits for saved particles, not just in _vids.
public:
explicit FilterVDHits(const fhicl::ParameterSet& pset);
virtual bool filter(art::Event& event);
virtual bool beginRun(art::Run& run) { std::cout<<"AG: beginRun() called"<<std::endl; return true; }
virtual bool endRun(art::Run& run) { std::cout<<"AG: endRun() called"<<std::endl; return true; }
};
//================================================================
FilterVDHits::FilterVDHits(const fhicl::ParameterSet& pset)
: EDFilter{pset}
, _inModuleLabel(pset.get<std::string>("inputModuleLabel"))
, _inInstanceName(pset.get<std::string>("inputInstanceName"))
, _vids(pset.get<std::vector<VolumeId> >("acceptedVids"))
, _positionCut(pset.get<bool>("positionCut", false))
, _positionCenter(std::vector<double>(3, 0.0))
, _positionHalfLength(std::vector<double>(3, 0.0))
, _storeParents(pset.get<bool>("storeParents"))
// default to false for compatibility with existing .fcl files.
, _storeExtraHits(pset.get<bool>("storeExtraHits", false))
{
if (_positionCut) {
_positionCenter = pset.get<std::vector<double> >("positionCenter");
_positionHalfLength = pset.get<std::vector<double> >("positionHalfLength");
}
std::cout<<"FilterVDHits(): storeParents = "<<_storeParents<<std::endl;
std::cout<<"FilterVDHits(): storeExtraVDs = "<<_storeExtraHits<<std::endl;
if(_storeExtraHits && !_storeParents) {
throw cet::exception("BADCONFIG")
<<"FilterVDHits: attempting to storeExtraHits without storeParents probably does not make sense.";
}
produces<StepPointMCCollection>();
produces<SimParticleCollection>();
if(_storeExtraHits) {
produces<StepPointMCCollection>("extraHits");
}
}
//================================================================
bool FilterVDHits::filter(art::Event& event) {
AGDEBUG("FilterVDHits begin event "<<event.id());
// Use art::Ptr instead of bare ptr to get the desired sorting
TrackSet particlesWithHits;
art::Handle<StepPointMCCollection> ih;
event.getByLabel(_inModuleLabel, _inInstanceName, ih);
const StepPointMCCollection& inhits(*ih);
std::unique_ptr<StepPointMCCollection> outhits(new StepPointMCCollection());
std::unique_ptr<StepPointMCCollection> extrahits(new StepPointMCCollection());
for(StepPointMCCollection::const_iterator i=inhits.begin(); i!=inhits.end(); ++i) {
if(std::find(_vids.begin(), _vids.end(), i->volumeId()) != _vids.end()) {
if ( _positionCut &&
( fabs(i->position().x() - _positionCenter[0]) > _positionHalfLength[0] ||
fabs(i->position().y() - _positionCenter[1]) > _positionHalfLength[1] ||
fabs(i->position().z() - _positionCenter[2]) > _positionHalfLength[2] ) )
continue;
outhits->push_back(*i);
AGDEBUG("here");
const art::Ptr<SimParticle>& particle = outhits->back().simParticle();
AGDEBUG("here");
if(!particle.get()) {
throw cet::exception("MISSINGINFO")
<<"NULL particle pointer for StepPointMC = "<<*i
<<" in event "<<event.id()
;
}
else {
AGDEBUG("here: particle = "<<particle<<" (internal id = "<< particle->id()<<")"<<" for hit "<<*i);
particlesWithHits.insert(particle);
}
}
}
AGDEBUG("here");
if(_storeParents) {
// For each particle hitting our VD also save
// all the parents in the chain up to the primary.
for(TrackSet::const_iterator i=particlesWithHits.begin(); i!=particlesWithHits.end(); ++i) {
art::Ptr<SimParticle> current = *i;
while(current->hasParent()) {
current = current->parent();
// Insertion into the set does not invalidate the iterator (i)
particlesWithHits.insert(current);
}
}
}
// The case when parents are stored is supported by compressSimParticleCollection()
// otherwise we need to prepare the output SimParticleCollection by hand
std::unique_ptr<SimParticleCollection> outparts(new SimParticleCollection());
art::ProductID newProductId(event.getProductID<SimParticleCollection>());
const art::EDProductGetter *newProductGetter(event.productGetter(newProductId));
if(!_storeParents) {
// Need to save SimParticles that produced the hits Particles
// must come in order, and there may be no one-to-one
// correspondence with saved hits, so this must be a separate
// loop.
//
// Note that the art::Ptr comparison operator sorts the set in
// the correct order for our use.
for(TrackSet::const_iterator i=particlesWithHits.begin(); i!=particlesWithHits.end(); ++i) {
AGDEBUG("here");
cet::map_vector_key key = (*i)->id();
AGDEBUG("here: key = "<<key);
// Copy the original particle to the output
// FIXME: why does push_back() screw up the given key?
// outparts->push_back(std::make_pair(key, **i));
(*outparts)[key] = **i;
SimParticle& particle(outparts->getOrThrow(key));
// Zero internal pointers: intermediate particles are not preserved to reduce data size
AGDEBUG("here");
particle.setDaughterPtrs(std::vector<art::Ptr<SimParticle> >());
AGDEBUG("here");
particle.parent() = art::Ptr<SimParticle>();
AGDEBUG("after p/d reset: particle id = "<<particle.id());
}
} // if(_storeParents)
else {
art::Handle<SimParticleCollection> inparts;
event.getByLabel(_inModuleLabel, "", inparts);
ParticleSelector selector(particlesWithHits);
compressSimParticleCollection(newProductId, newProductGetter, *inparts, selector, *outparts);
} // else(_storeParents)
//----------------------------------------------------------------
// We have a set of saved particles. Some of their hits are
// already in the output collection, _storeExtraHits requrests to
// add any remaining hits made by those particles.
if(_storeExtraHits) {
for(StepPointMCCollection::const_iterator i=inhits.begin(); i!=inhits.end(); ++i) {
// Hits in _vids are already stored. Just store the complement.
if(std::find(_vids.begin(), _vids.end(), i->volumeId()) == _vids.end() ) {
const art::Ptr<SimParticle>& particle = i->simParticle();
if(!particle.get()) {
throw cet::exception("MISSINGINFO")
<<"storeExtraHits: NULL particle pointer for StepPointMC = "<<*i
<<" in event "<<event.id()
;
}
else {
AGDEBUG("here: particle = "<<particle<<" (internal id = "<< particle->id()<<")"<<" for hit "<<*i);
if(outparts->has(particle->id())) {
extrahits->push_back(*i);
}
}
}
}
} // if(_storeExtraHits)
//----------------------------------------------------------------
AGDEBUG("here");
event.put(std::move(outparts));
// Update pointers in the hit collection
AGDEBUG("here");
for(StepPointMCCollection::iterator i=outhits->begin(); i!=outhits->end(); ++i) {
AGDEBUG("here");
art::Ptr<SimParticle> oldPtr(i->simParticle());
AGDEBUG("here: settting id = "<< oldPtr->id()<<", newProductId = "<<newProductId <<" for hit "<<*i);
i->simParticle() = art::Ptr<SimParticle>(newProductId, oldPtr->id().asUint(), newProductGetter);
}
AGDEBUG("here");
if(_storeExtraHits) {
// Update pointers in the extra hits collection
AGDEBUG("here");
for(StepPointMCCollection::iterator i=extrahits->begin(); i!=extrahits->end(); ++i) {
AGDEBUG("here");
art::Ptr<SimParticle> oldPtr(i->simParticle());
AGDEBUG("here: settting id = "<< oldPtr->id()<<", newProductId = "<<newProductId <<" for hit "<<*i);
i->simParticle() = art::Ptr<SimParticle>(newProductId, oldPtr->id().asUint(), newProductGetter);
}
AGDEBUG("here");
event.put(std::move(extrahits), "extraHits");
}
//----------------------------------------------------------------
bool nonEmpty = !outhits->empty();
event.put(std::move(outhits));
return nonEmpty;
}
//================================================================
} // namespace mu2e
DEFINE_ART_MODULE(mu2e::FilterVDHits);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.